From 4b5a7d721d994a49057e9bfb403c7bff1b376660 Mon Sep 17 00:00:00 2001 From: Instrumental Date: Fri, 7 Sep 2018 12:21:34 -0500 Subject: [PATCH] Mass removal of all Tabs (Style Warnings) Issue-ID: AAF-473 Change-Id: Iaf0ef8120882937959bb0065f2f6ba74a021940f Signed-off-by: Instrumental --- .../src/main/java/org/onap/aaf/auth/Batch.java | 770 +- .../java/org/onap/aaf/auth/BatchException.java | 48 +- .../java/org/onap/aaf/auth/BatchPrincipal.java | 26 +- .../src/main/java/org/onap/aaf/auth/CassBatch.java | 72 +- .../java/org/onap/aaf/auth/actions/Action.java | 2 +- .../java/org/onap/aaf/auth/actions/ActionDAO.java | 68 +- .../org/onap/aaf/auth/actions/ActionPuntDAO.java | 66 +- .../java/org/onap/aaf/auth/actions/CacheTouch.java | 36 +- .../java/org/onap/aaf/auth/actions/CredDelete.java | 36 +- .../java/org/onap/aaf/auth/actions/CredPrint.java | 46 +- .../java/org/onap/aaf/auth/actions/CredPunt.java | 62 +- .../main/java/org/onap/aaf/auth/actions/Email.java | 360 +- .../java/org/onap/aaf/auth/actions/EmailPrint.java | 122 +- .../org/onap/aaf/auth/actions/FuturePrint.java | 18 +- .../main/java/org/onap/aaf/auth/actions/Key.java | 2 +- .../java/org/onap/aaf/auth/actions/Message.java | 46 +- .../java/org/onap/aaf/auth/actions/NSACreate.java | 46 +- .../java/org/onap/aaf/auth/actions/NSADelete.java | 46 +- .../org/onap/aaf/auth/actions/NSDescUpdate.java | 46 +- .../java/org/onap/aaf/auth/actions/PermCreate.java | 62 +- .../java/org/onap/aaf/auth/actions/PermDelete.java | 56 +- .../java/org/onap/aaf/auth/actions/PermModify.java | 198 +- .../java/org/onap/aaf/auth/actions/RoleCreate.java | 58 +- .../java/org/onap/aaf/auth/actions/RoleDelete.java | 52 +- .../java/org/onap/aaf/auth/actions/RoleModify.java | 222 +- .../main/java/org/onap/aaf/auth/actions/URAdd.java | 38 +- .../java/org/onap/aaf/auth/actions/URDelete.java | 46 +- .../org/onap/aaf/auth/actions/URFutureApprove.java | 128 +- .../onap/aaf/auth/actions/URFutureApproveExec.java | 124 +- .../org/onap/aaf/auth/actions/URFuturePrint.java | 18 +- .../java/org/onap/aaf/auth/actions/URModify.java | 82 +- .../java/org/onap/aaf/auth/actions/URPrint.java | 18 +- .../java/org/onap/aaf/auth/actions/URPunt.java | 58 +- .../java/org/onap/aaf/auth/helpers/Approval.java | 488 +- .../java/org/onap/aaf/auth/helpers/Approver.java | 60 +- .../org/onap/aaf/auth/helpers/CacheChange.java | 66 +- .../java/org/onap/aaf/auth/helpers/Creator.java | 24 +- .../main/java/org/onap/aaf/auth/helpers/Cred.java | 462 +- .../java/org/onap/aaf/auth/helpers/Future.java | 308 +- .../java/org/onap/aaf/auth/helpers/History.java | 246 +- .../org/onap/aaf/auth/helpers/InputIterator.java | 78 +- .../java/org/onap/aaf/auth/helpers/Loader.java | 2 +- .../java/org/onap/aaf/auth/helpers/MiscID.java | 280 +- .../java/org/onap/aaf/auth/helpers/MonthData.java | 130 +- .../main/java/org/onap/aaf/auth/helpers/NS.java | 214 +- .../org/onap/aaf/auth/helpers/Notification.java | 286 +- .../java/org/onap/aaf/auth/helpers/NsAttrib.java | 106 +- .../main/java/org/onap/aaf/auth/helpers/Perm.java | 218 +- .../main/java/org/onap/aaf/auth/helpers/Role.java | 226 +- .../java/org/onap/aaf/auth/helpers/UserRole.java | 476 +- .../java/org/onap/aaf/auth/javax/JavaxMailer.java | 240 +- .../org/onap/aaf/auth/reports/ExpiringNext.java | 160 +- .../java/org/onap/aaf/auth/update/Expiring.java | 756 +- .../java/org/onap/aaf/auth/update/ExpiringP2.java | 200 +- .../org/onap/aaf/auth/update/NotifyApprovals.java | 346 +- .../onap/aaf/auth/update/NotifyCredExpiring.java | 502 +- .../onap/aaf/auth/actions/test/JU_ActionDAO.java | 78 +- .../org/onap/aaf/auth/actions/test/JU_Email.java | 198 +- .../onap/aaf/auth/actions/test/JU_EmailPrint.java | 88 +- .../org/onap/aaf/auth/actions/test/JU_Message.java | 48 +- .../onap/aaf/auth/helpers/test/JU_Approval.java | 220 +- .../onap/aaf/auth/helpers/test/JU_Approver.java | 50 +- .../onap/aaf/auth/helpers/test/JU_CacheChange.java | 72 +- .../org/onap/aaf/auth/helpers/test/JU_Creator.java | 54 +- .../org/onap/aaf/auth/helpers/test/JU_Cred.java | 174 +- .../org/onap/aaf/auth/helpers/test/JU_Future.java | 128 +- .../org/onap/aaf/auth/helpers/test/JU_History.java | 52 +- .../aaf/auth/helpers/test/JU_InputIterator.java | 56 +- .../org/onap/aaf/auth/helpers/test/JU_MiscID.java | 106 +- .../onap/aaf/auth/helpers/test/JU_MonthData.java | 116 +- .../java/org/onap/aaf/auth/helpers/test/JU_NS.java | 76 +- .../onap/aaf/auth/helpers/test/JU_NsAttrib.java | 24 +- .../org/onap/aaf/auth/helpers/test/JU_Perm.java | 108 +- .../org/onap/aaf/auth/helpers/test/JU_Role.java | 98 +- .../onap/aaf/auth/helpers/test/JU_UserRole.java | 198 +- .../test/java/org/onap/aaf/auth/test/JU_Batch.java | 76 +- .../org/onap/aaf/auth/test/JU_BatchException.java | 40 +- .../org/onap/aaf/auth/test/JU_BatchPrincipal.java | 16 +- .../java/org/onap/aaf/auth/test/JU_CassBatch.java | 44 +- .../java/org/onap/aaf/auth/dao/AbsCassDAO.java | 854 +-- .../java/org/onap/aaf/auth/dao/Bytification.java | 4 +- .../src/main/java/org/onap/aaf/auth/dao/CIDAO.java | 36 +- .../main/java/org/onap/aaf/auth/dao/Cacheable.java | 2 +- .../main/java/org/onap/aaf/auth/dao/Cached.java | 320 +- .../main/java/org/onap/aaf/auth/dao/CachedDAO.java | 348 +- .../java/org/onap/aaf/auth/dao/CassAccess.java | 360 +- .../java/org/onap/aaf/auth/dao/CassDAOImpl.java | 560 +- .../src/main/java/org/onap/aaf/auth/dao/DAO.java | 12 +- .../java/org/onap/aaf/auth/dao/DAOException.java | 28 +- .../main/java/org/onap/aaf/auth/dao/DAO_RO.java | 48 +- .../main/java/org/onap/aaf/auth/dao/Loader.java | 334 +- .../main/java/org/onap/aaf/auth/dao/Streamer.java | 4 +- .../main/java/org/onap/aaf/auth/dao/Touchable.java | 2 +- .../onap/aaf/auth/dao/cached/CachedCertDAO.java | 38 +- .../onap/aaf/auth/dao/cached/CachedCredDAO.java | 62 +- .../org/onap/aaf/auth/dao/cached/CachedNSDAO.java | 6 +- .../onap/aaf/auth/dao/cached/CachedPermDAO.java | 162 +- .../onap/aaf/auth/dao/cached/CachedRoleDAO.java | 126 +- .../aaf/auth/dao/cached/CachedUserRoleDAO.java | 148 +- .../org/onap/aaf/auth/dao/cass/ApprovalDAO.java | 374 +- .../java/org/onap/aaf/auth/dao/cass/ArtiDAO.java | 292 +- .../org/onap/aaf/auth/dao/cass/CacheInfoDAO.java | 738 +- .../org/onap/aaf/auth/dao/cass/CacheableData.java | 12 +- .../java/org/onap/aaf/auth/dao/cass/CertDAO.java | 196 +- .../java/org/onap/aaf/auth/dao/cass/ConfigDAO.java | 72 +- .../java/org/onap/aaf/auth/dao/cass/CredDAO.java | 224 +- .../org/onap/aaf/auth/dao/cass/DelegateDAO.java | 186 +- .../java/org/onap/aaf/auth/dao/cass/FutureDAO.java | 150 +- .../org/onap/aaf/auth/dao/cass/HistoryDAO.java | 342 +- .../java/org/onap/aaf/auth/dao/cass/LocateDAO.java | 230 +- .../java/org/onap/aaf/auth/dao/cass/Namespace.java | 200 +- .../java/org/onap/aaf/auth/dao/cass/NsDAO.java | 876 +-- .../java/org/onap/aaf/auth/dao/cass/NsSplit.java | 70 +- .../java/org/onap/aaf/auth/dao/cass/NsType.java | 86 +- .../org/onap/aaf/auth/dao/cass/OAuthTokenDAO.java | 184 +- .../java/org/onap/aaf/auth/dao/cass/PermDAO.java | 854 +-- .../java/org/onap/aaf/auth/dao/cass/RoleDAO.java | 628 +- .../java/org/onap/aaf/auth/dao/cass/Status.java | 78 +- .../org/onap/aaf/auth/dao/cass/UserRoleDAO.java | 470 +- .../org/onap/aaf/auth/dao/hl/CassExecutor.java | 68 +- .../java/org/onap/aaf/auth/dao/hl/Function.java | 3456 ++++----- .../java/org/onap/aaf/auth/dao/hl/PermLookup.java | 266 +- .../java/org/onap/aaf/auth/dao/hl/Question.java | 2120 +++--- .../org/onap/aaf/auth/direct/DirectAAFLocator.java | 170 +- .../org/onap/aaf/auth/direct/DirectAAFLur.java | 290 +- .../onap/aaf/auth/direct/DirectAAFUserPass.java | 74 +- .../onap/aaf/auth/direct/DirectCertIdentity.java | 46 +- .../onap/aaf/auth/direct/DirectLocatorCreator.java | 56 +- .../org/onap/aaf/auth/direct/DirectRegistrar.java | 140 +- .../test/java/org/onap/aaf/auth/dao/JU_Cached.java | 164 +- .../java/org/onap/aaf/auth/dao/JU_CachedDAO.java | 44 +- .../java/org/onap/aaf/auth/dao/JU_CassAccess.java | 52 +- .../java/org/onap/aaf/auth/dao/JU_CassDAOImpl.java | 56 +- .../org/onap/aaf/auth/dao/JU_DAOException.java | 22 +- .../org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java | 278 +- .../aaf/auth/dao/aaf/test/JU_Bytification.java | 412 +- .../org/onap/aaf/auth/dao/aaf/test/JU_NsType.java | 48 +- .../auth/direct/test/JU_DirectCertIdentity.java | 52 +- .../src/main/java/org/onap/aaf/auth/cm/AAF_CM.java | 338 +- .../org/onap/aaf/auth/cm/api/API_Artifact.java | 168 +- .../java/org/onap/aaf/auth/cm/api/API_Cert.java | 186 +- .../src/main/java/org/onap/aaf/auth/cm/ca/CA.java | 364 +- .../main/java/org/onap/aaf/auth/cm/ca/JscepCA.java | 374 +- .../main/java/org/onap/aaf/auth/cm/ca/LocalCA.java | 362 +- .../onap/aaf/auth/cm/ca/X509ChainWithIssuer.java | 108 +- .../java/org/onap/aaf/auth/cm/ca/X509andChain.java | 76 +- .../java/org/onap/aaf/auth/cm/cert/BCFactory.java | 178 +- .../java/org/onap/aaf/auth/cm/cert/CSRMeta.java | 372 +- .../main/java/org/onap/aaf/auth/cm/cert/RDN.java | 142 +- .../java/org/onap/aaf/auth/cm/data/CertReq.java | 30 +- .../java/org/onap/aaf/auth/cm/data/CertResp.java | 106 +- .../java/org/onap/aaf/auth/cm/facade/Facade.java | 270 +- .../org/onap/aaf/auth/cm/facade/Facade1_0.java | 12 +- .../org/onap/aaf/auth/cm/facade/FacadeFactory.java | 14 +- .../org/onap/aaf/auth/cm/facade/FacadeImpl.java | 1108 +-- .../java/org/onap/aaf/auth/cm/mapper/Mapper.java | 28 +- .../org/onap/aaf/auth/cm/mapper/Mapper1_0.java | 432 +- .../org/onap/aaf/auth/cm/mapper/Mapper2_0.java | 414 +- .../org/onap/aaf/auth/cm/service/CMService.java | 1256 ++-- .../java/org/onap/aaf/auth/cm/service/Code.java | 24 +- .../aaf/auth/cm/validation/CertmanValidator.java | 150 +- .../org/onap/aaf/auth/cm/api/JU_API_Artifact.java | 124 +- .../java/org/onap/aaf/auth/cm/api/JU_API_Cert.java | 124 +- .../java/org/onap/aaf/auth/cm/ca/JU_AppCA.java | 434 +- .../org/onap/aaf/auth/cm/cert/JU_BCFactory.java | 144 +- .../org/onap/aaf/auth/cm/facade/JU_FacadeImpl.java | 260 +- .../org/onap/aaf/auth/cm/test/CertmanTest.java | 192 +- .../main/java/org/onap/aaf/auth/cmd/AAFcli.java | 1166 +-- .../main/java/org/onap/aaf/auth/cmd/BaseCmd.java | 66 +- .../src/main/java/org/onap/aaf/auth/cmd/Cmd.java | 914 +-- .../java/org/onap/aaf/auth/cmd/DeprecatedCMD.java | 22 +- .../src/main/java/org/onap/aaf/auth/cmd/Help.java | 168 +- .../org/onap/aaf/auth/cmd/MessageException.java | 20 +- .../src/main/java/org/onap/aaf/auth/cmd/Param.java | 24 +- .../main/java/org/onap/aaf/auth/cmd/Version.java | 20 +- .../java/org/onap/aaf/auth/cmd/mgmt/Cache.java | 8 +- .../java/org/onap/aaf/auth/cmd/mgmt/Clear.java | 80 +- .../main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java | 116 +- .../main/java/org/onap/aaf/auth/cmd/mgmt/Log.java | 134 +- .../main/java/org/onap/aaf/auth/cmd/mgmt/Mgmt.java | 14 +- .../java/org/onap/aaf/auth/cmd/mgmt/SessClear.java | 76 +- .../java/org/onap/aaf/auth/cmd/mgmt/Session.java | 8 +- .../main/java/org/onap/aaf/auth/cmd/ns/Admin.java | 124 +- .../main/java/org/onap/aaf/auth/cmd/ns/Attrib.java | 150 +- .../main/java/org/onap/aaf/auth/cmd/ns/Create.java | 152 +- .../main/java/org/onap/aaf/auth/cmd/ns/Delete.java | 90 +- .../java/org/onap/aaf/auth/cmd/ns/Describe.java | 104 +- .../main/java/org/onap/aaf/auth/cmd/ns/List.java | 258 +- .../org/onap/aaf/auth/cmd/ns/ListActivity.java | 68 +- .../onap/aaf/auth/cmd/ns/ListAdminResponsible.java | 74 +- .../java/org/onap/aaf/auth/cmd/ns/ListByName.java | 110 +- .../org/onap/aaf/auth/cmd/ns/ListChildren.java | 68 +- .../onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java | 76 +- .../java/org/onap/aaf/auth/cmd/ns/ListUsers.java | 70 +- .../org/onap/aaf/auth/cmd/ns/ListUsersContact.java | 148 +- .../org/onap/aaf/auth/cmd/ns/ListUsersInRole.java | 148 +- .../onap/aaf/auth/cmd/ns/ListUsersWithPerm.java | 148 +- .../src/main/java/org/onap/aaf/auth/cmd/ns/NS.java | 28 +- .../main/java/org/onap/aaf/auth/cmd/ns/Owner.java | 130 +- .../java/org/onap/aaf/auth/cmd/perm/Create.java | 232 +- .../java/org/onap/aaf/auth/cmd/perm/Delete.java | 86 +- .../java/org/onap/aaf/auth/cmd/perm/Describe.java | 116 +- .../java/org/onap/aaf/auth/cmd/perm/Grant.java | 202 +- .../main/java/org/onap/aaf/auth/cmd/perm/List.java | 150 +- .../org/onap/aaf/auth/cmd/perm/ListActivity.java | 62 +- .../java/org/onap/aaf/auth/cmd/perm/ListByNS.java | 50 +- .../org/onap/aaf/auth/cmd/perm/ListByName.java | 50 +- .../org/onap/aaf/auth/cmd/perm/ListByRole.java | 50 +- .../org/onap/aaf/auth/cmd/perm/ListByUser.java | 76 +- .../main/java/org/onap/aaf/auth/cmd/perm/Perm.java | 22 +- .../java/org/onap/aaf/auth/cmd/perm/Rename.java | 126 +- .../org/onap/aaf/auth/cmd/role/CreateDelete.java | 174 +- .../java/org/onap/aaf/auth/cmd/role/Describe.java | 104 +- .../main/java/org/onap/aaf/auth/cmd/role/List.java | 314 +- .../org/onap/aaf/auth/cmd/role/ListActivity.java | 60 +- .../java/org/onap/aaf/auth/cmd/role/ListByNS.java | 52 +- .../org/onap/aaf/auth/cmd/role/ListByNameOnly.java | 52 +- .../org/onap/aaf/auth/cmd/role/ListByPerm.java | 62 +- .../org/onap/aaf/auth/cmd/role/ListByRole.java | 52 +- .../org/onap/aaf/auth/cmd/role/ListByUser.java | 104 +- .../main/java/org/onap/aaf/auth/cmd/role/Role.java | 18 +- .../main/java/org/onap/aaf/auth/cmd/role/User.java | 242 +- .../main/java/org/onap/aaf/auth/cmd/user/Cred.java | 232 +- .../main/java/org/onap/aaf/auth/cmd/user/Delg.java | 166 +- .../main/java/org/onap/aaf/auth/cmd/user/List.java | 154 +- .../org/onap/aaf/auth/cmd/user/ListActivity.java | 64 +- .../org/onap/aaf/auth/cmd/user/ListApprovals.java | 110 +- .../org/onap/aaf/auth/cmd/user/ListDelegates.java | 92 +- .../org/onap/aaf/auth/cmd/user/ListForCreds.java | 100 +- .../onap/aaf/auth/cmd/user/ListForPermission.java | 110 +- .../org/onap/aaf/auth/cmd/user/ListForRoles.java | 86 +- .../main/java/org/onap/aaf/auth/cmd/user/Role.java | 208 +- .../main/java/org/onap/aaf/auth/cmd/user/User.java | 14 +- .../org/onap/aaf/auth/cmd/test/HMangrStub.java | 40 +- .../java/org/onap/aaf/auth/cmd/test/JU_AAFCli.java | 372 +- .../org/onap/aaf/auth/cmd/test/JU_BaseCmd.java | 132 +- .../org/onap/aaf/auth/cmd/test/JU_BasicAuth.java | 36 +- .../java/org/onap/aaf/auth/cmd/test/JU_Cmd.java | 242 +- .../onap/aaf/auth/cmd/test/JU_DeprecatedCMD.java | 50 +- .../java/org/onap/aaf/auth/cmd/test/JU_Help.java | 142 +- .../org/onap/aaf/auth/cmd/test/JU_Version.java | 38 +- .../org/onap/aaf/auth/cmd/test/mgmt/JU_Clear.java | 92 +- .../org/onap/aaf/auth/cmd/test/mgmt/JU_Deny.java | 82 +- .../org/onap/aaf/auth/cmd/test/mgmt/JU_Log.java | 94 +- .../onap/aaf/auth/cmd/test/mgmt/JU_SessClear.java | 90 +- .../org/onap/aaf/auth/cmd/test/ns/JU_Admin.java | 100 +- .../org/onap/aaf/auth/cmd/test/ns/JU_Attrib.java | 98 +- .../org/onap/aaf/auth/cmd/test/ns/JU_Create.java | 92 +- .../org/onap/aaf/auth/cmd/test/ns/JU_Delete.java | 88 +- .../org/onap/aaf/auth/cmd/test/ns/JU_Describe.java | 84 +- .../org/onap/aaf/auth/cmd/test/ns/JU_List.java | 172 +- .../onap/aaf/auth/cmd/test/ns/JU_ListActivity.java | 86 +- .../auth/cmd/test/ns/JU_ListAdminResponsible.java | 86 +- .../onap/aaf/auth/cmd/test/ns/JU_ListByName.java | 86 +- .../onap/aaf/auth/cmd/test/ns/JU_ListChildren.java | 64 +- .../auth/cmd/test/ns/JU_ListNsKeysByAttrib.java | 64 +- .../onap/aaf/auth/cmd/test/ns/JU_ListUsers.java | 48 +- .../aaf/auth/cmd/test/ns/JU_ListUsersContact.java | 92 +- .../aaf/auth/cmd/test/ns/JU_ListUsersInRole.java | 54 +- .../aaf/auth/cmd/test/ns/JU_ListUsersWithPerm.java | 64 +- .../org/onap/aaf/auth/cmd/test/ns/JU_Owner.java | 48 +- .../onap/aaf/auth/cmd/test/ns/JU_Responsible.java | 60 +- .../org/onap/aaf/auth/cmd/test/perm/JU_Create.java | 104 +- .../org/onap/aaf/auth/cmd/test/perm/JU_Delete.java | 100 +- .../onap/aaf/auth/cmd/test/perm/JU_Describe.java | 98 +- .../org/onap/aaf/auth/cmd/test/perm/JU_Grant.java | 130 +- .../aaf/auth/cmd/test/perm/JU_ListActivity.java | 86 +- .../onap/aaf/auth/cmd/test/perm/JU_ListByNS.java | 66 +- .../onap/aaf/auth/cmd/test/perm/JU_ListByName.java | 86 +- .../onap/aaf/auth/cmd/test/perm/JU_ListByRole.java | 66 +- .../onap/aaf/auth/cmd/test/perm/JU_ListByUser.java | 66 +- .../org/onap/aaf/auth/cmd/test/perm/JU_Rename.java | 86 +- .../aaf/auth/cmd/test/role/JU_CreateDelete.java | 100 +- .../onap/aaf/auth/cmd/test/role/JU_Describe.java | 94 +- .../org/onap/aaf/auth/cmd/test/role/JU_List.java | 178 +- .../aaf/auth/cmd/test/role/JU_ListActivity.java | 96 +- .../onap/aaf/auth/cmd/test/role/JU_ListByNS.java | 74 +- .../aaf/auth/cmd/test/role/JU_ListByNameOnly.java | 96 +- .../onap/aaf/auth/cmd/test/role/JU_ListByPerm.java | 74 +- .../onap/aaf/auth/cmd/test/role/JU_ListByRole.java | 76 +- .../onap/aaf/auth/cmd/test/role/JU_ListByUser.java | 98 +- .../org/onap/aaf/auth/cmd/test/role/JU_User.java | 112 +- .../org/onap/aaf/auth/cmd/test/user/JU_Cred.java | 98 +- .../org/onap/aaf/auth/cmd/test/user/JU_Delg.java | 98 +- .../aaf/auth/cmd/test/user/JU_ListActivity.java | 66 +- .../aaf/auth/cmd/test/user/JU_ListApprovals.java | 88 +- .../aaf/auth/cmd/test/user/JU_ListDelegates.java | 66 +- .../aaf/auth/cmd/test/user/JU_ListForCreds.java | 88 +- .../auth/cmd/test/user/JU_ListForPermission.java | 66 +- .../aaf/auth/cmd/test/user/JU_ListForRoles.java | 66 +- .../org/onap/aaf/auth/cmd/test/user/JU_Role.java | 104 +- .../main/java/org/onap/aaf/auth/cache/Cache.java | 302 +- .../main/java/org/onap/aaf/auth/common/Define.java | 102 +- .../main/java/org/onap/aaf/auth/env/AuthzEnv.java | 438 +- .../java/org/onap/aaf/auth/env/AuthzTrans.java | 60 +- .../org/onap/aaf/auth/env/AuthzTransFilter.java | 264 +- .../java/org/onap/aaf/auth/env/AuthzTransImpl.java | 358 +- .../onap/aaf/auth/env/AuthzTransOnlyFilter.java | 92 +- .../main/java/org/onap/aaf/auth/env/NullTrans.java | 380 +- .../java/org/onap/aaf/auth/layer/FacadeImpl.java | 18 +- .../main/java/org/onap/aaf/auth/layer/Result.java | 194 +- .../main/java/org/onap/aaf/auth/local/AbsData.java | 336 +- .../java/org/onap/aaf/auth/local/DataFile.java | 294 +- .../java/org/onap/aaf/auth/local/TextIndex.java | 422 +- .../main/java/org/onap/aaf/auth/org/Executor.java | 18 +- .../main/java/org/onap/aaf/auth/org/Mailer.java | 18 +- .../java/org/onap/aaf/auth/org/Organization.java | 926 +-- .../onap/aaf/auth/org/OrganizationException.java | 50 +- .../org/onap/aaf/auth/org/OrganizationFactory.java | 180 +- .../java/org/onap/aaf/auth/rserv/Acceptor.java | 256 +- .../org/onap/aaf/auth/rserv/CachingFileAccess.java | 940 +-- .../java/org/onap/aaf/auth/rserv/CodeSetter.java | 36 +- .../main/java/org/onap/aaf/auth/rserv/Content.java | 136 +- .../java/org/onap/aaf/auth/rserv/HttpCode.java | 152 +- .../java/org/onap/aaf/auth/rserv/HttpMethods.java | 8 +- .../main/java/org/onap/aaf/auth/rserv/Match.java | 342 +- .../main/java/org/onap/aaf/auth/rserv/Pair.java | 22 +- .../java/org/onap/aaf/auth/rserv/RServlet.java | 212 +- .../main/java/org/onap/aaf/auth/rserv/Route.java | 196 +- .../java/org/onap/aaf/auth/rserv/RouteReport.java | 8 +- .../main/java/org/onap/aaf/auth/rserv/Routes.java | 106 +- .../java/org/onap/aaf/auth/rserv/TransFilter.java | 176 +- .../org/onap/aaf/auth/rserv/TransOnlyFilter.java | 50 +- .../java/org/onap/aaf/auth/rserv/TypedCode.java | 416 +- .../main/java/org/onap/aaf/auth/rserv/Version.java | 116 +- .../java/org/onap/aaf/auth/rserv/doc/ApiDoc.java | 16 +- .../java/org/onap/aaf/auth/server/AbsService.java | 222 +- .../onap/aaf/auth/server/AbsServiceStarter.java | 112 +- .../onap/aaf/auth/server/JettyServiceStarter.java | 406 +- .../java/org/onap/aaf/auth/server/Log4JLogIt.java | 184 +- .../org/onap/aaf/auth/server/ServiceStarter.java | 4 +- .../org/onap/aaf/auth/validation/Validator.java | 352 +- .../org/onap/aaf/auth/common/test/JU_Define.java | 78 +- .../org/onap/aaf/auth/env/test/JU_AuthzEnv.java | 264 +- .../aaf/auth/env/test/JU_AuthzTransFilter.java | 104 +- .../onap/aaf/auth/env/test/JU_AuthzTransImpl.java | 232 +- .../aaf/auth/env/test/JU_AuthzTransOnlyFilter.java | 120 +- .../org/onap/aaf/auth/env/test/JU_NullTrans.java | 438 +- .../org/onap/aaf/auth/layer/test/JU_Result.java | 288 +- .../org/onap/aaf/auth/local/test/JU_AbsData.java | 112 +- .../org/onap/aaf/auth/local/test/JU_DataFile.java | 64 +- .../org/onap/aaf/auth/local/test/JU_TextIndex.java | 144 +- .../onap/aaf/auth/org/test/JU_Organization.java | 82 +- .../auth/org/test/JU_OrganizationException.java | 28 +- .../aaf/auth/org/test/JU_OrganizationFactory.java | 56 +- .../onap/aaf/auth/request/test/CredCompare.java | 58 +- .../aaf/auth/request/test/JU_RequestCheck.java | 26 +- .../onap/aaf/auth/request/test/MultiCompare.java | 72 +- .../aaf/auth/request/test/NSAttribCompare.java | 112 +- .../org/onap/aaf/auth/request/test/NSCompare.java | 78 +- .../onap/aaf/auth/request/test/PermCompare.java | 62 +- .../onap/aaf/auth/request/test/RoleCompare.java | 58 +- .../aaf/auth/request/test/RolePermCompare.java | 66 +- .../onap/aaf/auth/request/test/RosettaCompare.java | 68 +- .../aaf/auth/request/test/UserRoleCompare.java | 58 +- .../onap/aaf/auth/rserv/test/JU_BetterMatch.java | 252 +- .../onap/aaf/auth/rserv/test/JU_BetterMatch1.java | 240 +- .../onap/aaf/auth/rserv/test/JU_BetterRoute.java | 8 +- .../aaf/auth/rserv/test/JU_CachingFileAccess.java | 234 +- .../org/onap/aaf/auth/rserv/test/JU_Content.java | 1204 +-- .../org/onap/aaf/auth/rserv/test/JU_Content1.java | 170 +- .../java/org/onap/aaf/auth/rserv/test/JU_Pair.java | 26 +- .../org/onap/aaf/auth/rserv/test/JU_Route.java | 46 +- .../onap/aaf/auth/rserv/test/JU_RouteReport.java | 12 +- .../org/onap/aaf/auth/rserv/test/JU_Routes.java | 52 +- .../org/onap/aaf/auth/rserv/test/JU_TypedCode.java | 112 +- .../org/onap/aaf/auth/rserv/test/JU_Version.java | 62 +- .../onap/aaf/auth/server/test/JU_AbsService.java | 84 +- .../aaf/auth/server/test/JU_AbsServiceStarter.java | 152 +- .../auth/server/test/JU_JettyServiceStarter.java | 76 +- .../java/org/onap/aaf/auth/util/test/JU_Mask.java | 66 +- .../aaf/auth/validation/test/JU_Validator.java | 550 +- .../src/main/java/org/onap/aaf/org/DefaultOrg.java | 1158 +-- .../java/org/onap/aaf/org/DefaultOrgIdentity.java | 268 +- .../java/org/onap/aaf/org/DefaultOrgWarnings.java | 68 +- .../src/main/java/org/onap/aaf/org/Identities.java | 170 +- .../java/org/onap/aaf/org/test/JU_DefaultOrg.java | 328 +- .../onap/aaf/org/test/JU_DefaultOrgIdentity.java | 146 +- .../onap/aaf/org/test/JU_DefaultOrgWarnings.java | 64 +- .../java/org/onap/aaf/org/test/JU_Identities.java | 110 +- .../java/org/onap/aaf/org/test/JU_Passwords.java | 112 +- .../src/main/java/org/onap/aaf/auth/fs/AAF_FS.java | 122 +- .../java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java | 152 +- .../src/main/java/org/onap/aaf/auth/cui/CUI.java | 96 +- .../main/java/org/onap/aaf/auth/gui/AAF_GUI.java | 314 +- .../java/org/onap/aaf/auth/gui/BreadCrumbs.java | 98 +- .../java/org/onap/aaf/auth/gui/ContentCode.java | 6 +- .../main/java/org/onap/aaf/auth/gui/Controls.java | 26 +- .../main/java/org/onap/aaf/auth/gui/Display.java | 204 +- .../src/main/java/org/onap/aaf/auth/gui/Form.java | 68 +- .../main/java/org/onap/aaf/auth/gui/NamedCode.java | 80 +- .../org/onap/aaf/auth/gui/OrgLookupFilter.java | 66 +- .../src/main/java/org/onap/aaf/auth/gui/Page.java | 646 +- .../main/java/org/onap/aaf/auth/gui/SlotCode.java | 36 +- .../src/main/java/org/onap/aaf/auth/gui/Table.java | 352 +- .../java/org/onap/aaf/auth/gui/XFrameFilter.java | 70 +- .../java/org/onap/aaf/auth/gui/pages/ApiDocs.java | 536 +- .../org/onap/aaf/auth/gui/pages/ApiExample.java | 162 +- .../onap/aaf/auth/gui/pages/ApprovalAction.java | 146 +- .../org/onap/aaf/auth/gui/pages/ApprovalForm.java | 458 +- .../aaf/auth/gui/pages/CMArtiChangeAction.java | 326 +- .../onap/aaf/auth/gui/pages/CMArtiChangeForm.java | 372 +- .../onap/aaf/auth/gui/pages/CMArtifactShow.java | 352 +- .../org/onap/aaf/auth/gui/pages/CredDetail.java | 536 +- .../java/org/onap/aaf/auth/gui/pages/Home.java | 74 +- .../org/onap/aaf/auth/gui/pages/LoginLanding.java | 146 +- .../aaf/auth/gui/pages/LoginLandingAction.java | 52 +- .../java/org/onap/aaf/auth/gui/pages/NsDetail.java | 366 +- .../org/onap/aaf/auth/gui/pages/NsHistory.java | 332 +- .../org/onap/aaf/auth/gui/pages/NsInfoAction.java | 216 +- .../org/onap/aaf/auth/gui/pages/NsInfoForm.java | 208 +- .../java/org/onap/aaf/auth/gui/pages/NssShow.java | 166 +- .../onap/aaf/auth/gui/pages/PassChangeAction.java | 302 +- .../onap/aaf/auth/gui/pages/PassChangeForm.java | 286 +- .../onap/aaf/auth/gui/pages/PassDeleteAction.java | 84 +- .../aaf/auth/gui/pages/PendingRequestsShow.java | 244 +- .../org/onap/aaf/auth/gui/pages/PermDetail.java | 192 +- .../onap/aaf/auth/gui/pages/PermGrantAction.java | 168 +- .../org/onap/aaf/auth/gui/pages/PermGrantForm.java | 204 +- .../org/onap/aaf/auth/gui/pages/PermHistory.java | 354 +- .../org/onap/aaf/auth/gui/pages/PermsShow.java | 126 +- .../org/onap/aaf/auth/gui/pages/RequestDetail.java | 232 +- .../org/onap/aaf/auth/gui/pages/RoleDetail.java | 434 +- .../onap/aaf/auth/gui/pages/RoleDetailAction.java | 258 +- .../org/onap/aaf/auth/gui/pages/RoleHistory.java | 326 +- .../org/onap/aaf/auth/gui/pages/RolesShow.java | 156 +- .../onap/aaf/auth/gui/pages/UserRoleExtend.java | 102 +- .../onap/aaf/auth/gui/pages/UserRoleRemove.java | 100 +- .../org/onap/aaf/auth/gui/pages/WebCommand.java | 152 +- .../java/org/onap/aaf/auth/gui/table/AbsCell.java | 40 +- .../org/onap/aaf/auth/gui/table/ButtonCell.java | 34 +- .../org/onap/aaf/auth/gui/table/CheckBoxCell.java | 72 +- .../org/onap/aaf/auth/gui/table/RadioCell.java | 38 +- .../java/org/onap/aaf/auth/gui/table/RefCell.java | 38 +- .../org/onap/aaf/auth/gui/table/TableData.java | 40 +- .../onap/aaf/auth/gui/table/TextAndRefCell.java | 22 +- .../java/org/onap/aaf/auth/gui/table/TextCell.java | 34 +- .../org/onap/aaf/auth/gui/table/TextInputCell.java | 44 +- .../java/org/onap/aaf/auth/hello/AAF_Hello.java | 152 +- .../java/org/onap/aaf/auth/hello/API_Hello.java | 262 +- .../org/onap/aaf/auth/hello/test/HelloTester.java | 76 +- .../java/org/onap/aaf/auth/locate/AAF_Locate.java | 358 +- .../org/onap/aaf/auth/locate/BasicAuthCode.java | 74 +- .../java/org/onap/aaf/auth/locate/LocateCode.java | 28 +- .../onap/aaf/auth/locate/api/API_AAFAccess.java | 444 +- .../java/org/onap/aaf/auth/locate/api/API_Api.java | 98 +- .../org/onap/aaf/auth/locate/api/API_Find.java | 158 +- .../org/onap/aaf/auth/locate/api/API_Proxy.java | 216 +- .../onap/aaf/auth/locate/facade/LocateFacade.java | 132 +- .../auth/locate/facade/LocateFacadeFactory.java | 18 +- .../aaf/auth/locate/facade/LocateFacadeImpl.java | 638 +- .../aaf/auth/locate/facade/LocateFacade_1_1.java | 6 +- .../org/onap/aaf/auth/locate/mapper/Mapper.java | 12 +- .../onap/aaf/auth/locate/mapper/Mapper_1_1.java | 214 +- .../aaf/auth/locate/service/LocateService.java | 10 +- .../aaf/auth/locate/service/LocateServiceImpl.java | 202 +- .../auth/locate/validation/LocateValidator.java | 184 +- .../onap/aaf/auth/locate/JU_BasicAuthCodeTest.java | 96 +- .../aaf/auth/locate/mapper/JU_Mapper_1_0Test.java | 46 +- .../locate/service/JU_LocateServiceImplTest.java | 132 +- .../java/org/onap/aaf/auth/oauth/AAF_OAuth.java | 272 +- .../org/onap/aaf/auth/oauth/DirectOAuthTAF.java | 316 +- .../main/java/org/onap/aaf/auth/oauth/OACode.java | 28 +- .../java/org/onap/aaf/auth/oauth/OAuth2Filter.java | 42 +- .../onap/aaf/auth/oauth/OAuth2FormHttpTafResp.java | 54 +- .../org/onap/aaf/auth/oauth/api/API_Token.java | 76 +- .../aaf/auth/oauth/facade/DirectIntrospect.java | 2 +- .../auth/oauth/facade/DirectIntrospectImpl.java | 44 +- .../org/onap/aaf/auth/oauth/facade/OAFacade.java | 34 +- .../onap/aaf/auth/oauth/facade/OAFacade1_0.java | 12 +- .../aaf/auth/oauth/facade/OAFacadeFactory.java | 20 +- .../onap/aaf/auth/oauth/facade/OAFacadeImpl.java | 482 +- .../org/onap/aaf/auth/oauth/mapper/Mapper.java | 24 +- .../org/onap/aaf/auth/oauth/mapper/Mapper1_0.java | 348 +- .../aaf/auth/oauth/mapper/MapperIntrospect.java | 2 +- .../aaf/auth/oauth/mapper/MapperIntrospect1_0.java | 78 +- .../aaf/auth/oauth/service/JSONPermLoader.java | 2 +- .../auth/oauth/service/JSONPermLoaderFactory.java | 154 +- .../onap/aaf/auth/oauth/service/OAuthService.java | 466 +- .../org/onap/aaf/auth/oauth/service/OCreds.java | 16 +- .../org/onap/aaf/auth/oauth/JU_DirectOAuthTAF.java | 146 +- .../org/onap/aaf/auth/oauth/JU_OACodeTest.java | 42 +- .../onap/aaf/auth/oauth/JU_OAuth2FilterTest.java | 94 +- .../auth/oauth/JU_OAuth2FormHttpTafRespTest.java | 36 +- .../oauth/facade/JU_DirectOAFacadeImplTest.java | 10 +- .../aaf/auth/oauth/facade/JU_OAFacadeFactory.java | 70 +- .../aaf/auth/oauth/mapper/JU_Mapper1_0Test.java | 266 +- .../oauth/mapper/JU_MapperIntrospect1_0Test.java | 70 +- .../service/JU_JSONPermLoaderFactoryTest.java | 208 +- .../onap/aaf/auth/oauth/service/JU_OCredsTest.java | 38 +- .../org/onap/aaf/auth/service/AAF_Service.java | 328 +- .../aaf/auth/service/AuthzCassServiceImpl.java | 7872 ++++++++++---------- .../org/onap/aaf/auth/service/AuthzService.java | 1394 ++-- .../main/java/org/onap/aaf/auth/service/Code.java | 28 +- .../java/org/onap/aaf/auth/service/MayChange.java | 2 +- .../org/onap/aaf/auth/service/api/API_Api.java | 94 +- .../onap/aaf/auth/service/api/API_Approval.java | 124 +- .../org/onap/aaf/auth/service/api/API_Creds.java | 456 +- .../onap/aaf/auth/service/api/API_Delegate.java | 204 +- .../org/onap/aaf/auth/service/api/API_History.java | 350 +- .../org/onap/aaf/auth/service/api/API_Mgmt.java | 428 +- .../org/onap/aaf/auth/service/api/API_Multi.java | 46 +- .../java/org/onap/aaf/auth/service/api/API_NS.java | 678 +- .../org/onap/aaf/auth/service/api/API_Perms.java | 470 +- .../org/onap/aaf/auth/service/api/API_Roles.java | 566 +- .../org/onap/aaf/auth/service/api/API_User.java | 166 +- .../onap/aaf/auth/service/api/API_UserRole.java | 264 +- .../onap/aaf/auth/service/facade/AuthzFacade.java | 320 +- .../auth/service/facade/AuthzFacadeFactory.java | 40 +- .../aaf/auth/service/facade/AuthzFacadeImpl.java | 5072 ++++++------- .../aaf/auth/service/facade/AuthzFacade_2_0.java | 36 +- .../org/onap/aaf/auth/service/mapper/Mapper.java | 142 +- .../onap/aaf/auth/service/mapper/Mapper_2_0.java | 1532 ++-- .../auth/service/validation/ServiceValidator.java | 410 +- .../aaf/auth/service/api/test/JU_API_Approval.java | 46 +- .../aaf/auth/service/api/test/JU_API_Creds.java | 66 +- .../aaf/auth/service/api/test/JU_API_Delegate.java | 42 +- .../aaf/auth/service/api/test/JU_API_History.java | 44 +- .../onap/aaf/auth/service/api/test/JU_API_NS.java | 42 +- .../aaf/auth/service/api/test/JU_API_Perms.java | 62 +- .../aaf/auth/service/api/test/JU_API_Roles.java | 44 +- .../aaf/auth/service/api/test/JU_API_User.java | 44 +- .../aaf/auth/service/api/test/JU_API_UserRole.java | 42 +- .../validation/test/JU_ServiceValidator.java | 110 +- .../aaf/authz/service/mapper/JU_Mapper_2_0.java | 990 +-- .../java/org/onap/aaf/cadi/aaf/AAFPermission.java | 282 +- .../main/java/org/onap/aaf/cadi/aaf/Defaults.java | 18 +- .../main/java/org/onap/aaf/cadi/aaf/PermEval.java | 210 +- .../org/onap/aaf/cadi/aaf/TestConnectivity.java | 464 +- .../aaf/cadi/aaf/cert/AAFListedCertIdentity.java | 226 +- .../org/onap/aaf/cadi/aaf/client/ErrMessage.java | 116 +- .../org/onap/aaf/cadi/aaf/client/Examples.java | 698 +- .../org/onap/aaf/cadi/aaf/marshal/CertMarshal.java | 54 +- .../onap/aaf/cadi/aaf/marshal/CertsMarshal.java | 16 +- .../java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java | 250 +- .../java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java | 590 +- .../org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java | 338 +- .../org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java | 176 +- .../org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java | 370 +- .../java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java | 268 +- .../onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java | 160 +- .../org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java | 912 +-- .../java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java | 504 +- .../java/org/onap/aaf/cadi/configure/Agent.java | 1954 ++--- .../org/onap/aaf/cadi/configure/ArtifactDir.java | 448 +- .../org/onap/aaf/cadi/configure/CertException.java | 30 +- .../java/org/onap/aaf/cadi/configure/Factory.java | 862 +-- .../org/onap/aaf/cadi/configure/PlaceArtifact.java | 2 +- .../aaf/cadi/configure/PlaceArtifactInFiles.java | 34 +- .../cadi/configure/PlaceArtifactInKeystore.java | 196 +- .../aaf/cadi/configure/PlaceArtifactOnStream.java | 42 +- .../aaf/cadi/configure/PlaceArtifactScripts.java | 234 +- .../java/org/onap/aaf/cadi/oauth/AAFToken.java | 102 +- .../java/org/onap/aaf/cadi/oauth/AbsOTafLur.java | 178 +- .../org/onap/aaf/cadi/oauth/HRenewingTokenSS.java | 124 +- .../org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java | 70 +- .../org/onap/aaf/cadi/oauth/OAuth2HttpTafResp.java | 54 +- .../java/org/onap/aaf/cadi/oauth/OAuth2Lur.java | 134 +- .../org/onap/aaf/cadi/oauth/OAuth2Principal.java | 50 +- .../java/org/onap/aaf/cadi/oauth/TimedToken.java | 168 +- .../java/org/onap/aaf/cadi/oauth/TokenClient.java | 844 +-- .../onap/aaf/cadi/oauth/TokenClientFactory.java | 246 +- .../java/org/onap/aaf/cadi/oauth/TokenMgr.java | 272 +- .../java/org/onap/aaf/cadi/oauth/TokenPerm.java | 254 +- .../java/org/onap/aaf/cadi/oauth/TzClient.java | 4 +- .../java/org/onap/aaf/cadi/oauth/TzHClient.java | 64 +- .../org/onap/aaf/cadi/obasic/OBasicHttpTaf.java | 246 +- .../src/main/java/org/onap/aaf/cadi/olur/OLur.java | 244 +- .../java/org/onap/aaf/cadi/persist/Persist.java | 472 +- .../org/onap/aaf/cadi/persist/PersistFile.java | 386 +- .../org/onap/aaf/cadi/persist/Persistable.java | 24 +- .../java/org/onap/aaf/cadi/persist/Persisting.java | 258 +- .../org/onap/aaf/cadi/register/Registrant.java | 4 +- .../java/org/onap/aaf/cadi/register/Registrar.java | 128 +- .../onap/aaf/cadi/register/RemoteRegistrant.java | 256 +- .../main/java/org/onap/aaf/cadi/sso/AAFSSO.java | 836 +-- .../aaf/cert/test/JU_AAFListedCertIdentity.java | 228 +- .../cadi/aaf/client/test/JU_ErrMessageTest.java | 156 +- .../aaf/cadi/aaf/marshal/test/JU_CertMarshal.java | 106 +- .../aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java | 144 +- .../onap/aaf/cadi/aaf/test/JU_AAFPermission.java | 228 +- .../org/onap/aaf/cadi/aaf/test/JU_PermEval.java | 360 +- .../org/onap/aaf/cadi/aaf/test/TestHClient.java | 80 +- .../onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java | 118 +- .../aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java | 158 +- .../aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java | 290 +- .../org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java | 214 +- .../onap/aaf/cadi/cm/test/JU_CertException.java | 24 +- .../java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java | 188 +- .../java/org/onap/aaf/cadi/cm/test/JU_Factory.java | 588 +- .../aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java | 112 +- .../cadi/cm/test/JU_PlaceArtifactInKeystore.java | 192 +- .../aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java | 110 +- .../aaf/cadi/cm/test/JU_PlaceArtifactScripts.java | 100 +- .../org/onap/aaf/cadi/oauth/test/JU_AAFToken.java | 66 +- .../onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java | 46 +- .../aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java | 38 +- .../org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java | 98 +- .../aaf/cadi/oauth/test/JU_OAuth2Principal.java | 42 +- .../org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java | 442 +- .../onap/aaf/cadi/oauth/test/JU_TimedToken.java | 60 +- .../cadi/oauth/test/JU_TokenClientFactoryTest.java | 64 +- .../org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java | 286 +- .../org/onap/aaf/cadi/oauth/test/JU_TzHClient.java | 116 +- .../org/onap/aaf/cadi/persist/test/JU_Persist.java | 180 +- .../onap/aaf/cadi/persist/test/JU_PersistFile.java | 130 +- .../onap/aaf/cadi/persist/test/JU_Persisting.java | 112 +- .../java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java | 150 +- .../java/org/onap/aaf/client/sample/Sample.java | 260 +- .../test/java/org/onap/aaf/content/JU_Content.java | 76 +- .../onap/aaf/cadi/client/AbsAuthentication.java | 156 +- .../org/onap/aaf/cadi/client/AbsTransferSS.java | 62 +- .../java/org/onap/aaf/cadi/client/EClient.java | 32 +- .../main/java/org/onap/aaf/cadi/client/Future.java | 12 +- .../main/java/org/onap/aaf/cadi/client/Holder.java | 30 +- .../main/java/org/onap/aaf/cadi/client/Rcli.java | 1448 ++-- .../main/java/org/onap/aaf/cadi/client/Result.java | 62 +- .../java/org/onap/aaf/cadi/client/Retryable.java | 60 +- .../onap/aaf/cadi/http/HAuthorizationHeader.java | 36 +- .../java/org/onap/aaf/cadi/http/HBasicAuthSS.java | 60 +- .../main/java/org/onap/aaf/cadi/http/HClient.java | 724 +- .../main/java/org/onap/aaf/cadi/http/HMangr.java | 378 +- .../java/org/onap/aaf/cadi/http/HNoAuthSS.java | 18 +- .../main/java/org/onap/aaf/cadi/http/HRcli.java | 148 +- .../org/onap/aaf/cadi/http/HSecurityInfoInit.java | 28 +- .../main/java/org/onap/aaf/cadi/http/HTokenSS.java | 6 +- .../java/org/onap/aaf/cadi/http/HTransferSS.java | 50 +- .../main/java/org/onap/aaf/cadi/http/HX509SS.java | 202 +- .../java/org/onap/aaf/cadi/locator/DNSLocator.java | 356 +- .../aaf/cadi/locator/HClientHotPeerLocator.java | 54 +- .../org/onap/aaf/cadi/locator/HotPeerLocator.java | 462 +- .../org/onap/aaf/cadi/locator/PropertyLocator.java | 488 +- .../aaf/cadi/locator/SingleEndpointLocator.java | 106 +- .../org/onap/aaf/cadi/routing/GreatCircle.java | 252 +- .../aaf/cadi/client/test/JU_AbsAuthentication.java | 118 +- .../aaf/cadi/client/test/JU_AbsTransferSS.java | 66 +- .../org/onap/aaf/cadi/client/test/JU_Future.java | 24 +- .../org/onap/aaf/cadi/client/test/JU_Holder.java | 24 +- .../org/onap/aaf/cadi/client/test/JU_Rcli.java | 448 +- .../org/onap/aaf/cadi/client/test/JU_Result.java | 36 +- .../onap/aaf/cadi/client/test/JU_Retryable.java | 40 +- .../cadi/http/test/JU_HAuthorizationHeader.java | 70 +- .../onap/aaf/cadi/http/test/JU_HBasicAuthSS.java | 92 +- .../org/onap/aaf/cadi/http/test/JU_HClient.java | 530 +- .../org/onap/aaf/cadi/http/test/JU_HMangr.java | 424 +- .../org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java | 44 +- .../java/org/onap/aaf/cadi/http/test/JU_HRcli.java | 134 +- .../org/onap/aaf/cadi/http/test/JU_HTokenSS.java | 26 +- .../onap/aaf/cadi/http/test/JU_HTransferSS.java | 82 +- .../org/onap/aaf/cadi/http/test/JU_HX509SS.java | 126 +- .../onap/aaf/cadi/locator/test/JU_DNSLocator.java | 172 +- .../locator/test/JU_HClientHotPeerLocator.java | 216 +- .../aaf/cadi/locator/test/JU_PropertyLocator.java | 114 +- .../onap/aaf/cadi/routing/test/JU_GreatCircle.java | 78 +- .../org/onap/aaf/client/test/JU_ResultTest.java | 140 +- cadi/core/src/main/java/org/onap/aaf/cadi/AES.java | 146 +- .../main/java/org/onap/aaf/cadi/AbsUserCache.java | 798 +- .../src/main/java/org/onap/aaf/cadi/Access.java | 280 +- .../src/main/java/org/onap/aaf/cadi/BasicCred.java | 6 +- .../onap/aaf/cadi/BufferedServletInputStream.java | 298 +- .../java/org/onap/aaf/cadi/CachedPrincipal.java | 28 +- .../main/java/org/onap/aaf/cadi/CachingLur.java | 8 +- .../main/java/org/onap/aaf/cadi/CadiException.java | 32 +- .../src/main/java/org/onap/aaf/cadi/CadiWrap.java | 292 +- .../src/main/java/org/onap/aaf/cadi/Capacitor.java | 398 +- .../src/main/java/org/onap/aaf/cadi/CmdLine.java | 608 +- .../src/main/java/org/onap/aaf/cadi/Connector.java | 2 +- .../src/main/java/org/onap/aaf/cadi/CredVal.java | 16 +- .../main/java/org/onap/aaf/cadi/CredValDomain.java | 2 +- .../src/main/java/org/onap/aaf/cadi/GetCred.java | 2 +- .../core/src/main/java/org/onap/aaf/cadi/Hash.java | 420 +- .../src/main/java/org/onap/aaf/cadi/Locator.java | 20 +- .../java/org/onap/aaf/cadi/LocatorException.java | 32 +- cadi/core/src/main/java/org/onap/aaf/cadi/Lur.java | 94 +- .../main/java/org/onap/aaf/cadi/Permission.java | 6 +- .../main/java/org/onap/aaf/cadi/PropAccess.java | 682 +- .../main/java/org/onap/aaf/cadi/Revalidator.java | 14 +- .../java/org/onap/aaf/cadi/SecuritySetter.java | 20 +- .../org/onap/aaf/cadi/ServletContextAccess.java | 62 +- .../core/src/main/java/org/onap/aaf/cadi/Symm.java | 1222 +-- cadi/core/src/main/java/org/onap/aaf/cadi/Taf.java | 36 +- .../main/java/org/onap/aaf/cadi/Transmutate.java | 14 +- .../main/java/org/onap/aaf/cadi/TrustChecker.java | 30 +- .../core/src/main/java/org/onap/aaf/cadi/User.java | 274 +- .../src/main/java/org/onap/aaf/cadi/UserChain.java | 4 +- .../main/java/org/onap/aaf/cadi/config/Config.java | 1456 ++-- .../main/java/org/onap/aaf/cadi/config/Get.java | 128 +- .../java/org/onap/aaf/cadi/config/GetAccess.java | 58 +- .../org/onap/aaf/cadi/config/SecurityInfo.java | 406 +- .../org/onap/aaf/cadi/config/SecurityInfoC.java | 108 +- .../org/onap/aaf/cadi/config/SecurityInfoInit.java | 2 +- .../java/org/onap/aaf/cadi/config/UsersDump.java | 236 +- .../main/java/org/onap/aaf/cadi/filter/AUTHZ.java | 2 +- .../org/onap/aaf/cadi/filter/AUTHZServlet.java | 102 +- .../org/onap/aaf/cadi/filter/AccessGetter.java | 14 +- .../java/org/onap/aaf/cadi/filter/CadiFilter.java | 526 +- .../org/onap/aaf/cadi/filter/CadiHTTPManip.java | 296 +- .../main/java/org/onap/aaf/cadi/filter/FCGet.java | 76 +- .../org/onap/aaf/cadi/filter/MapPermConverter.java | 44 +- .../onap/aaf/cadi/filter/NullPermConverter.java | 12 +- .../java/org/onap/aaf/cadi/filter/PathFilter.java | 256 +- .../org/onap/aaf/cadi/filter/PermConverter.java | 2 +- .../org/onap/aaf/cadi/filter/RolesAllowed.java | 12 +- .../java/org/onap/aaf/cadi/filter/ServletImpl.java | 12 +- .../org/onap/aaf/cadi/lur/ConfigPrincipal.java | 68 +- .../main/java/org/onap/aaf/cadi/lur/EpiLur.java | 222 +- .../main/java/org/onap/aaf/cadi/lur/LocalLur.java | 344 +- .../org/onap/aaf/cadi/lur/LocalPermission.java | 40 +- .../main/java/org/onap/aaf/cadi/lur/NullLur.java | 94 +- .../onap/aaf/cadi/principal/BasicPrincipal.java | 180 +- .../onap/aaf/cadi/principal/BearerPrincipal.java | 16 +- .../aaf/cadi/principal/CachedBasicPrincipal.java | 48 +- .../java/org/onap/aaf/cadi/principal/Kind.java | 52 +- .../aaf/cadi/principal/OAuth2FormPrincipal.java | 68 +- .../onap/aaf/cadi/principal/StringTagLookup.java | 16 +- .../onap/aaf/cadi/principal/TaggedPrincipal.java | 60 +- .../onap/aaf/cadi/principal/TrustPrincipal.java | 78 +- .../onap/aaf/cadi/principal/UnAuthPrincipal.java | 18 +- .../org/onap/aaf/cadi/principal/X509Principal.java | 140 +- .../java/org/onap/aaf/cadi/taf/AbsTafResp.java | 176 +- .../main/java/org/onap/aaf/cadi/taf/EpiTaf.java | 84 +- .../java/org/onap/aaf/cadi/taf/HttpEpiTaf.java | 328 +- .../main/java/org/onap/aaf/cadi/taf/HttpTaf.java | 38 +- .../org/onap/aaf/cadi/taf/LoginPageTafResp.java | 116 +- .../main/java/org/onap/aaf/cadi/taf/NullTaf.java | 42 +- .../java/org/onap/aaf/cadi/taf/NullTafResp.java | 94 +- .../java/org/onap/aaf/cadi/taf/PuntTafResp.java | 90 +- .../java/org/onap/aaf/cadi/taf/Redirectable.java | 12 +- .../main/java/org/onap/aaf/cadi/taf/TafResp.java | 140 +- .../org/onap/aaf/cadi/taf/TrustNotTafResp.java | 110 +- .../java/org/onap/aaf/cadi/taf/TrustTafResp.java | 112 +- .../org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java | 262 +- .../onap/aaf/cadi/taf/basic/BasicHttpTafResp.java | 54 +- .../org/onap/aaf/cadi/taf/cert/CertIdentity.java | 28 +- .../onap/aaf/cadi/taf/cert/X509HttpTafResp.java | 40 +- .../java/org/onap/aaf/cadi/taf/cert/X509Taf.java | 418 +- .../onap/aaf/cadi/taf/dos/DenialOfServiceTaf.java | 616 +- .../aaf/cadi/taf/dos/DenialOfServiceTafResp.java | 48 +- .../main/java/org/onap/aaf/cadi/util/Chmod.java | 64 +- .../src/main/java/org/onap/aaf/cadi/util/FQI.java | 48 +- .../org/onap/aaf/cadi/util/JsonOutputStream.java | 112 +- .../onap/aaf/cadi/util/MaskFormatException.java | 6 +- .../java/org/onap/aaf/cadi/util/MyConsole.java | 6 +- .../main/java/org/onap/aaf/cadi/util/NetMask.java | 128 +- .../src/main/java/org/onap/aaf/cadi/util/Pool.java | 582 +- .../main/java/org/onap/aaf/cadi/util/Split.java | 144 +- .../org/onap/aaf/cadi/util/SubStandardConsole.java | 72 +- .../java/org/onap/aaf/cadi/util/TheConsole.java | 40 +- .../main/java/org/onap/aaf/cadi/util/Timing.java | 6 +- .../org/onap/aaf/cadi/util/UserChainManip.java | 100 +- .../src/main/java/org/onap/aaf/cadi/util/Vars.java | 182 +- .../main/java/org/onap/aaf/cadi/wsse/Action.java | 2 +- .../main/java/org/onap/aaf/cadi/wsse/Match.java | 160 +- .../java/org/onap/aaf/cadi/wsse/WSSEParser.java | 74 +- .../main/java/org/onap/aaf/cadi/wsse/XEvent.java | 174 +- .../main/java/org/onap/aaf/cadi/wsse/XReader.java | 732 +- .../java/org/onap/aaf/cadi/config/test/JU_Get.java | 120 +- .../onap/aaf/cadi/config/test/JU_GetAccess.java | 74 +- .../org/onap/aaf/cadi/config/test/JU_MultiGet.java | 42 +- .../onap/aaf/cadi/config/test/JU_SecurityInfo.java | 174 +- .../aaf/cadi/config/test/JU_SecurityInfoC.java | 118 +- .../onap/aaf/cadi/config/test/JU_UsersDump.java | 196 +- .../onap/aaf/cadi/filter/test/JU_AUTHZServlet.java | 118 +- .../onap/aaf/cadi/filter/test/JU_AccessGetter.java | 32 +- .../aaf/cadi/filter/test/JU_MapPermConverter.java | 22 +- .../aaf/cadi/filter/test/JU_NullPermConverter.java | 10 +- .../onap/aaf/cadi/filter/test/JU_PathFilter.java | 96 +- .../onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java | 76 +- .../java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java | 118 +- .../org/onap/aaf/cadi/lur/test/JU_LocalLur.java | 240 +- .../onap/aaf/cadi/lur/test/JU_LocalPermission.java | 52 +- .../org/onap/aaf/cadi/lur/test/JU_NullLur.java | 60 +- .../aaf/cadi/principal/test/JU_BasicPrincipal.java | 160 +- .../principal/test/JU_CachedBasicPrincipal.java | 154 +- .../org/onap/aaf/cadi/principal/test/JU_Kind.java | 48 +- .../principal/test/JU_OAuth2FormPrincipal.java | 44 +- .../cadi/principal/test/JU_StringTagLookup.java | 12 +- .../cadi/principal/test/JU_TaggedPrincipal.java | 52 +- .../aaf/cadi/principal/test/JU_TrustPrincipal.java | 94 +- .../cadi/principal/test/JU_UnAuthPrincipal.java | 12 +- .../aaf/cadi/principal/test/JU_X509Principal.java | 196 +- .../aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java | 234 +- .../cadi/taf/basic/test/JU_BasicHttpTafResp.java | 34 +- .../aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java | 40 +- .../cadi/taf/dos/test/JU_DenialOfServiceTaf.java | 638 +- .../taf/dos/test/JU_DenialOfServiceTafResp.java | 32 +- .../org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java | 86 +- .../java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java | 116 +- .../org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java | 174 +- .../aaf/cadi/taf/test/JU_LoginPageTafResp.java | 68 +- .../org/onap/aaf/cadi/taf/test/JU_NullTaf.java | 48 +- .../org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java | 32 +- .../onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java | 50 +- .../onap/aaf/cadi/taf/test/JU_TrustTafResp.java | 66 +- .../test/java/org/onap/aaf/cadi/test/JU_AES.java | 288 +- .../org/onap/aaf/cadi/test/JU_AbsUserCache.java | 610 +- .../java/org/onap/aaf/cadi/test/JU_Access.java | 56 +- .../java/org/onap/aaf/cadi/test/JU_Base64.java | 96 +- .../onap/aaf/cadi/test/JU_BufferedCadiWrap.java | 24 +- .../cadi/test/JU_BufferedServletInputStream.java | 382 +- .../org/onap/aaf/cadi/test/JU_CadiException.java | 172 +- .../java/org/onap/aaf/cadi/test/JU_CadiWrap.java | 200 +- .../java/org/onap/aaf/cadi/test/JU_Capacitor.java | 160 +- .../java/org/onap/aaf/cadi/test/JU_CmdLine.java | 442 +- .../test/java/org/onap/aaf/cadi/test/JU_Hash.java | 214 +- .../onap/aaf/cadi/test/JU_LocatorException.java | 50 +- .../java/org/onap/aaf/cadi/test/JU_PropAccess.java | 220 +- .../aaf/cadi/test/JU_ServletContextAccess.java | 94 +- .../test/java/org/onap/aaf/cadi/test/JU_Symm.java | 344 +- .../org/onap/aaf/cadi/test/JU_TrustChecker.java | 10 +- .../test/java/org/onap/aaf/cadi/test/JU_User.java | 274 +- .../java/org/onap/aaf/cadi/util/test/JU_Chmod.java | 58 +- .../java/org/onap/aaf/cadi/util/test/JU_FQI.java | 18 +- .../aaf/cadi/util/test/JU_JsonOutputStream.java | 106 +- .../aaf/cadi/util/test/JU_MaskFormatException.java | 20 +- .../org/onap/aaf/cadi/util/test/JU_NetMask.java | 68 +- .../java/org/onap/aaf/cadi/util/test/JU_Pool.java | 244 +- .../java/org/onap/aaf/cadi/util/test/JU_Split.java | 146 +- .../aaf/cadi/util/test/JU_SubStandardConsole.java | 168 +- .../org/onap/aaf/cadi/util/test/JU_TheConsole.java | 8 +- .../onap/aaf/cadi/util/test/JU_UserChainManip.java | 60 +- .../java/org/onap/aaf/cadi/util/test/JU_Vars.java | 210 +- .../org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java | 244 +- .../org/onap/aaf/cadi/wsse/test/JU_XReader.java | 218 +- .../org/onap/aaf/cadi/enduser/ClientFactory.java | 36 +- .../org/onap/aaf/cadi/enduser/RESTException.java | 70 +- .../onap/aaf/cadi/enduser/SimpleRESTClient.java | 494 +- .../onap/aaf/cadi/enduser/test/OAuthExample.java | 354 +- .../aaf/cadi/enduser/test/OnapClientExample.java | 302 +- .../cadi/enduser/test/SimpleRestClientExample.java | 362 +- .../java/org/onap/aaf/sample/cadi/MyServlet.java | 174 +- .../org/onap/aaf/sample/cadi/jetty/Config.java | 20 +- .../aaf/sample/cadi/jetty/JettyServletServer.java | 96 +- .../aaf/sample/cadi/jetty/JettyStandalone.java | 24 +- .../onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java | 96 +- .../aaf/sample/cadi/tomcate/TomcatEmbedded.java | 62 +- .../java/org/onap/aaf/misc/env/APIException.java | 94 +- .../org/onap/aaf/misc/env/BaseDataFactory.java | 806 +- .../main/java/org/onap/aaf/misc/env/Creatable.java | 30 +- .../src/main/java/org/onap/aaf/misc/env/Data.java | 108 +- .../java/org/onap/aaf/misc/env/DataFactory.java | 6 +- .../main/java/org/onap/aaf/misc/env/Decryptor.java | 16 +- .../main/java/org/onap/aaf/misc/env/Encryptor.java | 14 +- .../src/main/java/org/onap/aaf/misc/env/Env.java | 156 +- .../main/java/org/onap/aaf/misc/env/EnvJAXB.java | 42 +- .../main/java/org/onap/aaf/misc/env/EnvProps.java | 96 +- .../java/org/onap/aaf/misc/env/IOObjectifier.java | 50 +- .../java/org/onap/aaf/misc/env/IOStringifier.java | 78 +- .../main/java/org/onap/aaf/misc/env/LifeCycle.java | 146 +- .../main/java/org/onap/aaf/misc/env/LogTarget.java | 196 +- .../java/org/onap/aaf/misc/env/Objectifier.java | 40 +- .../src/main/java/org/onap/aaf/misc/env/Slot.java | 114 +- .../java/org/onap/aaf/misc/env/StaticSlot.java | 78 +- .../src/main/java/org/onap/aaf/misc/env/Store.java | 148 +- .../main/java/org/onap/aaf/misc/env/StoreImpl.java | 400 +- .../java/org/onap/aaf/misc/env/Stringifier.java | 28 +- .../main/java/org/onap/aaf/misc/env/TimeTaken.java | 154 +- .../src/main/java/org/onap/aaf/misc/env/Trans.java | 56 +- .../java/org/onap/aaf/misc/env/TransCreate.java | 2 +- .../java/org/onap/aaf/misc/env/TransStore.java | 60 +- .../java/org/onap/aaf/misc/env/impl/AbsTrans.java | 350 +- .../org/onap/aaf/misc/env/impl/AbsTransJAXB.java | 46 +- .../java/org/onap/aaf/misc/env/impl/BasicEnv.java | 580 +- .../org/onap/aaf/misc/env/impl/BasicTrans.java | 78 +- .../org/onap/aaf/misc/env/impl/EnvFactory.java | 58 +- .../onap/aaf/misc/env/impl/JavaUtilLogTarget.java | 94 +- .../org/onap/aaf/misc/env/impl/Log4JLogTarget.java | 126 +- .../org/onap/aaf/misc/env/impl/NullLifeCycle.java | 10 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBDF.java | 526 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBData.java | 478 +- .../onap/aaf/misc/env/jaxb/JAXBObjectifier.java | 186 +- .../onap/aaf/misc/env/jaxb/JAXBStringifier.java | 198 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBmar.java | 374 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBumar.java | 346 +- .../org/onap/aaf/misc/env/old/IOObjectifier.java | 50 +- .../org/onap/aaf/misc/env/old/IOStringifier.java | 78 +- .../org/onap/aaf/misc/env/old/Objectifier.java | 40 +- .../org/onap/aaf/misc/env/old/OldDataFactory.java | 22 +- .../org/onap/aaf/misc/env/old/Stringifier.java | 28 +- .../java/org/onap/aaf/misc/env/util/Chrono.java | 524 +- .../onap/aaf/misc/env/util/DoubleOutputStream.java | 70 +- .../org/onap/aaf/misc/env/util/IPValidator.java | 54 +- .../main/java/org/onap/aaf/misc/env/util/Pool.java | 618 +- .../aaf/misc/env/util/RefreshableThreadObject.java | 134 +- .../java/org/onap/aaf/misc/env/util/Split.java | 128 +- .../misc/env/util/StringBuilderOutputStream.java | 70 +- .../aaf/misc/env/util/StringBuilderWriter.java | 62 +- .../org/onap/aaf/misc/env/JU_APIExceptionTest.java | 60 +- .../org/onap/aaf/misc/env/JU_BasicTransTest.java | 146 +- .../org/onap/aaf/misc/env/JU_LogTargetTest.java | 70 +- .../onap/aaf/misc/env/impl/JU_BasicEnvTest.java | 202 +- .../onap/aaf/misc/env/impl/JU_EnvFactoryTest.java | 64 +- .../aaf/misc/env/impl/JU_Log4JLogTargetTest.java | 30 +- .../onap/aaf/misc/env/jaxb/JU_JAXBDataTest.java | 192 +- .../org/onap/aaf/misc/env/util/JU_ChronoTest.java | 302 +- .../misc/env/util/JU_DoubleOutputStreamTest.java | 94 +- .../misc/env/util/JU_IndentPrintWriterTest.java | 108 +- .../org/onap/aaf/misc/env/util/JU_SplitTest.java | 52 +- .../env/util/JU_StringBuilderOutputStreamTest.java | 202 +- .../misc/env/util/JU_StringBuilderWriterTest.java | 202 +- .../aaf/misc/env/util/test/JU_IPValidator.java | 64 +- .../onap/aaf/misc/env/util/test/JU_PoolTest.java | 90 +- .../org/onap/aaf/misc/env/log4j/LogFileNamer.java | 102 +- .../aaf/misc/env/log4j/JU_LogFileNamerTest.java | 92 +- .../java/org/onap/aaf/misc/rosetta/InJson.java | 240 +- .../main/java/org/onap/aaf/misc/rosetta/InXML.java | 866 +-- .../java/org/onap/aaf/misc/rosetta/JaxEval.java | 2 +- .../java/org/onap/aaf/misc/rosetta/JaxInfo.java | 408 +- .../java/org/onap/aaf/misc/rosetta/JaxSet.java | 94 +- .../java/org/onap/aaf/misc/rosetta/Ladder.java | 148 +- .../java/org/onap/aaf/misc/rosetta/Marshal.java | 92 +- .../main/java/org/onap/aaf/misc/rosetta/Nulls.java | 56 +- .../main/java/org/onap/aaf/misc/rosetta/Out.java | 26 +- .../java/org/onap/aaf/misc/rosetta/OutJax.java | 42 +- .../java/org/onap/aaf/misc/rosetta/OutJson.java | 384 +- .../java/org/onap/aaf/misc/rosetta/OutRaw.java | 28 +- .../java/org/onap/aaf/misc/rosetta/OutXML.java | 368 +- .../main/java/org/onap/aaf/misc/rosetta/Parse.java | 34 +- .../org/onap/aaf/misc/rosetta/ParseException.java | 24 +- .../java/org/onap/aaf/misc/rosetta/Parsed.java | 112 +- .../main/java/org/onap/aaf/misc/rosetta/Prop.java | 34 +- .../main/java/org/onap/aaf/misc/rosetta/Saved.java | 288 +- .../java/org/onap/aaf/misc/rosetta/XmlEscape.java | 676 +- .../org/onap/aaf/misc/rosetta/env/RosettaDF.java | 378 +- .../org/onap/aaf/misc/rosetta/env/RosettaData.java | 506 +- .../org/onap/aaf/misc/rosetta/env/RosettaEnv.java | 78 +- .../onap/aaf/misc/rosetta/marshal/DataWriter.java | 188 +- .../onap/aaf/misc/rosetta/marshal/DocMarshal.java | 94 +- .../onap/aaf/misc/rosetta/marshal/FieldArray.java | 110 +- .../onap/aaf/misc/rosetta/marshal/FieldBlob.java | 20 +- .../onap/aaf/misc/rosetta/marshal/FieldDate.java | 16 +- .../aaf/misc/rosetta/marshal/FieldDateTime.java | 16 +- .../aaf/misc/rosetta/marshal/FieldHexBinary.java | 16 +- .../aaf/misc/rosetta/marshal/FieldMarshal.java | 54 +- .../aaf/misc/rosetta/marshal/FieldNumeric.java | 18 +- .../onap/aaf/misc/rosetta/marshal/FieldString.java | 16 +- .../aaf/misc/rosetta/marshal/ListIterator.java | 46 +- .../onap/aaf/misc/rosetta/marshal/ObjArray.java | 100 +- .../onap/aaf/misc/rosetta/marshal/ObjMarshal.java | 168 +- .../onap/aaf/misc/rosetta/test/JU_FromJSON.java | 416 +- .../org/onap/aaf/misc/rosetta/test/JU_FromXML.java | 408 +- .../org/onap/aaf/misc/rosetta/test/JU_JSON.java | 190 +- .../org/onap/aaf/misc/rosetta/test/JU_Ladder.java | 84 +- .../org/onap/aaf/misc/rosetta/test/JU_Nulls.java | 60 +- .../onap/aaf/misc/rosetta/test/JU_RosettaDF.java | 236 +- .../org/onap/aaf/misc/rosetta/test/JU_Saved.java | 118 +- .../onap/aaf/misc/rosetta/test/JU_Stream2Obj.java | 146 +- .../org/onap/aaf/misc/rosetta/test/JU_Struct.java | 80 +- .../org/onap/aaf/misc/rosetta/test/JU_Types.java | 454 +- .../org/onap/aaf/misc/rosetta/test/OutDump.java | 106 +- .../org/onap/aaf/misc/rosetta/test/Report.java | 70 +- .../aaf/misc/rosetta/test/obj/MultiMarshal.java | 16 +- .../aaf/misc/rosetta/test/obj/SingleMarshal.java | 96 +- .../src/main/java/org/onap/aaf/misc/xgen/Back.java | 18 +- .../main/java/org/onap/aaf/misc/xgen/Cache.java | 18 +- .../main/java/org/onap/aaf/misc/xgen/CacheGen.java | 174 +- .../src/main/java/org/onap/aaf/misc/xgen/Code.java | 2 +- .../java/org/onap/aaf/misc/xgen/DynamicCode.java | 12 +- .../src/main/java/org/onap/aaf/misc/xgen/Mark.java | 28 +- .../main/java/org/onap/aaf/misc/xgen/Section.java | 52 +- .../src/main/java/org/onap/aaf/misc/xgen/XGen.java | 524 +- .../main/java/org/onap/aaf/misc/xgen/XGenBuff.java | 98 +- .../java/org/onap/aaf/misc/xgen/html/HTML4Gen.java | 206 +- .../java/org/onap/aaf/misc/xgen/html/HTML5Gen.java | 246 +- .../org/onap/aaf/misc/xgen/html/HTMLCacheGen.java | 54 +- .../java/org/onap/aaf/misc/xgen/html/HTMLGen.java | 418 +- .../java/org/onap/aaf/misc/xgen/html/Imports.java | 128 +- .../java/org/onap/aaf/misc/xgen/html/JSGen.java | 326 +- .../java/org/onap/aaf/misc/xgen/html/Thematic.java | 4 +- .../org/onap/aaf/misc/xgen/xml/XMLCacheGen.java | 20 +- .../java/org/onap/aaf/misc/xgen/xml/XMLGen.java | 28 +- .../java/org/onap/aaf/misc/xgen/JU_BackTest.java | 14 +- .../org/onap/aaf/misc/xgen/JU_DynamicCodeTest.java | 40 +- .../java/org/onap/aaf/misc/xgen/JU_MarkTest.java | 20 +- .../org/onap/aaf/misc/xgen/JU_NullCacheTest.java | 10 +- .../org/onap/aaf/misc/xgen/JU_SectionTest.java | 42 +- .../onap/aaf/misc/xgen/html/JU_HTML4GenTest.java | 396 +- .../onap/aaf/misc/xgen/html/JU_HTML5GenTest.java | 134 +- .../onap/aaf/misc/xgen/html/JU_ImportsTest.java | 46 +- .../org/onap/aaf/misc/xgen/html/JU_JSGenTest.java | 342 +- .../onap/aaf/misc/xgen/xml/JU_XMLCacheGenTest.java | 38 +- .../org/onap/aaf/misc/xgen/xml/JU_XMLGenTest.java | 40 +- 982 files changed, 93287 insertions(+), 93287 deletions(-) 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 index 7826eb68..559e3c51 100644 --- 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 @@ -68,11 +68,11 @@ import com.datastax.driver.core.Statement; public abstract class Batch { - private static String rootNs; + private static String rootNs; - private static StaticSlot ssargs; + private static StaticSlot ssargs; - protected static final String STARS = "*****"; + protected static final String STARS = "*****"; protected final Cluster cluster; protected static AuthzEnv env; @@ -80,58 +80,58 @@ public abstract class Batch { protected static Logger aspr; protected static Set specialNames; protected static boolean dryRun; - protected static String batchEnv; + protected static String batchEnv; - public static final String CASS_ENV = "CASS_ENV"; - public static final String LOG_DIR = "LOG_DIR"; + 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 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 + // 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 = false; + } else { dryRun = true; env.info().log("dryRun set to TRUE"); } - org = OrganizationFactory.init(env); - org.setTestMode(dryRun); + org = OrganizationFactory.init(env); + org.setTestMode(dryRun); - // Special names to allow behaviors beyond normal rules + // Special names to allow behaviors beyond normal rules specialNames = new HashSet<>(); String names = env.getProperty( "SPECIAL_NAMES" ); if ( names != null ) @@ -145,171 +145,171 @@ public abstract class Batch { } } - protected abstract void run(AuthzTrans trans); + protected abstract void run(AuthzTrans trans); protected abstract void _close(AuthzTrans trans); public String[] args() { - return env.get(ssargs); + 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); - } - } - - public boolean isMechID(String user) { - if (user.matches("m[0-9][0-9][0-9][0-9][0-9]")) { - 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 boolean isSpecial(String user) { + if (specialNames != null && specialNames.contains(user)) { + env.info().log("specialName: " + user); + + return (true); + } else { + return (false); + } + } + + public boolean isMechID(String user) { + if (user.matches("m[0-9][0-9][0-9][0-9][0-9]")) { + 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); - } - + 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]")) { @@ -318,204 +318,204 @@ public abstract class Batch { } 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 + 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()); - } - } - } - } + 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; + 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(); + + File f = new File("etc/authzBatch.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 etc dir, or in Classpath"); + System.exit(1); + } + is.close(); + } + + 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); + if (filename != null) { + env.init().log("Instantiated properties from", filename); + } + + // Log where Config found + env.info().log("Configuring from", propLoc); + 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); + } } - 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(); - - File f = new File("etc/authzBatch.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 etc dir, or in Classpath"); - System.exit(1); - } - is.close(); - } - - 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); - if (filename != null) { - env.init().log("Instantiated properties from", filename); - } - - // Log where Config found - env.info().log("Configuring from", propLoc); - 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 index 4ed0940a..15bec4e4 100644 --- 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 @@ -23,29 +23,29 @@ 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); - } + /** + * + */ + 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 index 5403e3a5..66431c8a 100644 --- 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 @@ -23,19 +23,19 @@ 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; - } + private final String name; + + public BatchPrincipal(final String name) { + this.name = "batch:"+name; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public String tag() { - return "Btch"; - } + @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 index 32e8f85d..cb2b158f 100644 --- 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 @@ -35,44 +35,44 @@ 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(); - } - } + 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"); - } + @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) { + 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; - } + 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 index ad3a447d..54e2ee2d 100644 --- 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 @@ -25,5 +25,5 @@ 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); + 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 index 90400015..af636d65 100644 --- 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 @@ -33,41 +33,41 @@ 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; + 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 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); - } - } + 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 index 332d2509..95b35fdb 100644 --- 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 @@ -31,42 +31,42 @@ import org.onap.aaf.misc.env.APIException; import com.datastax.driver.core.Cluster; public abstract class ActionPuntDAO extends ActionDAO { -// private static final SecureRandom random = new SecureRandom(); - private int months; -// private int range; - protected static final Date now = new Date(); +// private static final SecureRandom random = new SecureRandom(); + private int months; +// private int range; + 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; -// this.range = range; - } + public ActionPuntDAO(AuthzTrans trans, Cluster cluster, int months, int range, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + this.months = months; +// this.range = range; + } - public ActionPuntDAO(AuthzTrans trans, ActionDAO predecessor, int months, int range) { - super(trans, predecessor); - this.months = months; -// this.range = range; - } - + public ActionPuntDAO(AuthzTrans trans, ActionDAO predecessor, int months, int range) { + super(trans, predecessor); + this.months = months; +// this.range = range; + } + - protected Date puntDate(Date current) { - GregorianCalendar temp = new GregorianCalendar(); - temp.setTime(current); - temp.add(GregorianCalendar.MONTH, 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.setTime(now); - 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(); - } + /* + * This method Randomized date. This is no longer needed. Just add the Punt Months. + temp.setTime(now); + 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 index 8261c477..e0fa4be5 100644 --- 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 @@ -30,24 +30,24 @@ 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, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } - public CacheTouch(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } + 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; - } - } + @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 index 700aaaea..b4b7d0b3 100644 --- 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 @@ -32,24 +32,24 @@ 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, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } - public CredDelete(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } + 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; - } - } + @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 index 10407ce4..658ef8b5 100644 --- 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 @@ -27,30 +27,30 @@ import org.onap.aaf.auth.layer.Result; import org.onap.aaf.misc.env.util.Chrono; public class CredPrint implements Action { - private String info; + private String info; - public CredPrint(String text) { - this.info = text; - } + 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"; - } - } + @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 index 78c1f892..a2c9ecf6 100644 --- 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 @@ -34,37 +34,37 @@ 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, 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 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; - } + 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 index 15dfed38..0ac8f61d 100644 --- 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 @@ -34,184 +34,184 @@ 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); - } + 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 index dba02426..5fdc15b1 100644 --- 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 @@ -29,70 +29,70 @@ import org.onap.aaf.auth.org.Organization; public class EmailPrint extends Email { - private static final int LINE_LENGTH = 100; + private static final int LINE_LENGTH = 100; - public EmailPrint(String... defaultCC) { - super(defaultCC); - } + 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(); + /* (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 && retstart && ret { - private String info; + private String info; - public FuturePrint(String text) { - this.info = text; - } + 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(); - } + @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 index 8c39e47d..ee2e8c3b 100644 --- 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 @@ -22,5 +22,5 @@ package org.onap.aaf.auth.actions; public interface Key { - public String key(HELPER H); + 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 index a4122d61..ac594a47 100644 --- 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 @@ -25,29 +25,29 @@ import java.util.ArrayList; import java.util.List; public class Message { - public final List lines; - - public Message() { - lines = new ArrayList<>(); - } + 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 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'); - } - } - } + 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 index 3d215871..5e531269 100644 --- 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 @@ -31,28 +31,28 @@ 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); - } + 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; - } - } - + @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 index 4b976822..4bed8687 100644 --- 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 @@ -31,28 +31,28 @@ 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); - } + 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; - } - } - + @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 index 368c8452..98fad0ab 100644 --- 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 @@ -31,28 +31,28 @@ 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); - } + 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; - } - } - + @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 index 5f3ab202..c32234d7 100644 --- 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 @@ -34,36 +34,36 @@ 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); - } + 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; - } - } - + @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 index 02fd3c6c..c5b79185 100644 --- 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 @@ -32,33 +32,33 @@ 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); - } + 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; - } - } - + @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 index 9b60cee1..bc6f70ca 100644 --- 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 @@ -37,105 +37,105 @@ 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); - } + 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(); - } + @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); - } - } - + 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 index 50d163ab..5353166c 100644 --- 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 @@ -33,34 +33,34 @@ 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); - } + 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; - } - } - + @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 index cbe3c1c5..1a663c99 100644 --- 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 @@ -32,31 +32,31 @@ 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); - } + 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; - } - } - + @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 index c72a9d8f..87e2e027 100644 --- 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 @@ -37,116 +37,116 @@ 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); - } + 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); - } - } + @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 index 50a5a8f0..b6baea6c 100644 --- 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 @@ -34,24 +34,24 @@ 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); - } + 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; - } - } - + @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 index 9bc7da49..d54b7805 100644 --- 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 @@ -32,28 +32,28 @@ 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); - } + 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; - } - } - + @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 index 17d9cc01..8590714f 100644 --- 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 @@ -41,71 +41,71 @@ 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, expires; + private final Date start, 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(); - } + 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()); - } - } + @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 index acbadca7..fcba2364 100644 --- 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 @@ -42,67 +42,67 @@ 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); - } + 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; - } - } + @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 index 83a24c21..b749c648 100644 --- 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 @@ -28,14 +28,14 @@ import org.onap.aaf.misc.env.util.Chrono; public class URFuturePrint implements Action { - private String info; + private String info; - public URFuturePrint(String text) { - this.info = text; - } + 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 + @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 index 3f65a6a4..a7d420e3 100644 --- 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 @@ -35,46 +35,46 @@ 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); - } + 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); - } - + @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 index a9bdf9ca..be464d42 100644 --- 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 @@ -27,16 +27,16 @@ import org.onap.aaf.auth.layer.Result; import org.onap.aaf.misc.env.util.Chrono; public class URPrint implements Action { - private String info; + private String info; - public URPrint(String text) { - this.info = text; - } + 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(); - } + @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 index 8676ef33..856c89dc 100644 --- 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 @@ -36,35 +36,35 @@ 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, 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 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); - } - } - } + 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/helpers/Approval.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java index 58aa206e..94c709b3 100644 --- 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 @@ -41,269 +41,269 @@ 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 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 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() ); + 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); + try { + Statement stmt = new SimpleStatement(creator.select()); + results = session.execute(stmt); } finally { - tt.done(); + tt.done(); } - int count = 0; + 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(); - } - } + 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"); + 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); + } } - } - - @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 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); - } + 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"; - } - }; + @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(); - } + /** + * @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 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 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 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); - } + 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 index 127daac5..977964f1 100644 --- 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 @@ -28,35 +28,35 @@ 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()); - } - } + 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/CacheChange.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java index 0c82184b..1adc3d08 100644 --- 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 @@ -25,39 +25,39 @@ 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(); - } + 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 int cacheSize() { + return removed.size(); + } - public boolean contains(T t) { - return removed.contains(t); - } + 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 index da6d558c..11580b80 100644 --- 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 @@ -24,18 +24,18 @@ 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(); - } + 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 index 56fbbbae..4013f193 100644 --- 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 @@ -46,261 +46,261 @@ 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 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 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 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 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 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 + "';"); - } + 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) { + 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); + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); } finally { - tt.done(); + tt.done(); } - int count = 0; + int count = 0; try { - Iterator iter = results.iterator(); - Row row; - int type; // for filtering - String id; - tt = trans.start("Load Credentials", Env.SUB); - try { - while(iter.hasNext()) { - ++count; - row = iter.next(); - id = row.getString(0); - type = row.getInt(1); - if(types.length>0) { // filter by types, if requested - boolean quit = true; - for(int t : types) { - if(t==type) { - quit=false; - break; - } - } - if(quit) { - continue; - } - } - Cred cred = data.get(id); - if(cred==null) { - cred = new Cred(id); - data.put(id, cred); - } - cred.instances.add(new Instance(type, row.getTimestamp(2), row.getInt(3), row.getLong(4)/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); - } - } - } finally { - tt.done(); - } + Iterator iter = results.iterator(); + Row row; + int type; // for filtering + String id; + tt = trans.start("Load Credentials", Env.SUB); + try { + while(iter.hasNext()) { + ++count; + row = iter.next(); + id = row.getString(0); + type = row.getInt(1); + if(types.length>0) { // filter by types, if requested + boolean quit = true; + for(int t : types) { + if(t==type) { + quit=false; + break; + } + } + if(quit) { + continue; + } + } + Cred cred = data.get(id); + if(cred==null) { + cred = new Cred(id); + data.put(id, cred); + } + cred.instances.add(new Instance(type, row.getTimestamp(2), row.getInt(3), row.getLong(4)/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); + } + } + } finally { + tt.done(); + } } finally { - trans.info().log("Found",count,"creds"); + trans.info().log("Found",count,"creds"); + } + } + + /** + * 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); + } } - } - - /** - * 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; -// String query = "select count(*) from authz.cred LIMIT 1000000;"; + return cc; +// String query = "select count(*) from authz.cred LIMIT 1000000;"; // trans.info().log( "query: " + query ); // TimeTaken tt = trans.start("Count Credentials", Env.REMOTE); // ResultSet results; // try { -// Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); -// results = session.execute(stmt); -// return results.one().getLong(0); +// Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); +// results = session.execute(stmt); +// return results.one().getLong(0); // } finally { -// tt.done(); +// tt.done(); // } - } + } - 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 { - 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); - } + 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 index f153c06b..c0841590 100644 --- 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 @@ -36,143 +36,143 @@ 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 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) { + 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); + try { + Statement stmt = new SimpleStatement( creator.select() ).setReadTimeoutMillis(240000); + results = session.execute(stmt); } finally { - tt.done(); + tt.done(); } - int count = 0; + 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(); - } + 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"); + 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); - } + } + + 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#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)); - } + /* (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 "; - } - }; + @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)); - } + 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 "; - } - }; + @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 index 0afcac27..60b34af9 100644 --- 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 @@ -28,46 +28,46 @@ 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; - } + 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 String next() { + if(!hasNext()) { + throw new NoSuchElementException(); + } + return input; + } - @Override - public void remove() { - } - }; - } + @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 index 6d27f648..1ec64b7b 100644 --- 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 @@ -22,5 +22,5 @@ package org.onap.aaf.auth.helpers; public interface Loader { - public void exec(T t); + 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 index d92a448a..afa68c08 100644 --- 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 @@ -36,153 +36,153 @@ 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) { + 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); + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); } finally { - tt.done(); + tt.done(); } - int count = 0; + 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(); - } + 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"); + 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); } - } - - /* (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; - } - - + 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 index d633770e..e9321f5f 100644 --- 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 @@ -37,84 +37,84 @@ import java.util.TreeMap; public class MonthData { public final Map> data = new TreeMap<>(); - private File f; + 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(); - } - } + 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)); - } + 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; + 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; - } + 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; - } + @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(); - } + 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 index 172768cb..a2833e55 100644 --- 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 @@ -36,133 +36,133 @@ 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) { + 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); + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); } finally { - tt.done(); + 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(); - } + 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"); + trans.info().log("Found",data.size(),"Namespaces"); } - } + } - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.ns LIMIT 1000000;"; + 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); + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); } finally { - tt.done(); + 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 "; + } + }; + - 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 index 57ff5c61..abfd1ca4 100644 --- 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 @@ -41,169 +41,169 @@ 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 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 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() ); + 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); + try { + Statement stmt = new SimpleStatement(creator.select()); + results = session.execute(stmt); } finally { - tt.done(); + tt.done(); } - int count = 0; + 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(); - } - } + 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"); + 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 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)); - } + 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"; - } - }; + @Override + public String select() { + return "SELECT user,type,last,checksum FROM authz.notify LIMIT 100000"; + } + }; - - public void set(Message msg) { - this.msg = msg; - } + + 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 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; - } + 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 index eafbe909..d980bcc2 100644 --- 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 @@ -37,72 +37,72 @@ 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 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)); - } + 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() ); + @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); + try { + Statement stmt = new SimpleStatement(creator.select()); + results = session.execute(stmt); } finally { - tt.done(); + tt.done(); } - int count = 0; + 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); - } + 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"); + tt.done(); + trans.info().log("Found",count,"NS Attributes"); } - } + } - public String toString() { - return '"' + ns + "\",\"" + key + "\",\"" + value +'"'; - } + 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 index acfb3390..799ce4df 100644 --- 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 @@ -40,135 +40,135 @@ 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) { + 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) { + } + + 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) { + 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); + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); } finally { - tt.done(); + 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(); - } + 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"); + trans.info().log("Found",data.size(),"perms"); } - } + } - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.perm LIMIT 1000000;"; + 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); + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); } finally { - tt.done(); + 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); } - } - - 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(); - } + 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 index a173c4fa..46d3cced 100644 --- 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 @@ -42,134 +42,134 @@ 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) { + 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); + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); } finally { - tt.done(); + 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(); - } + 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"); + trans.info().log("Found",data.size(),"roles"); } - } - - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.role LIMIT 1000000;"; + } + + 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); + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); } finally { - tt.done(); + 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); } - } - - 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(); - } + 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 index 288211e6..fab9233d 100644 --- 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 @@ -46,254 +46,254 @@ 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); - } - - public static void loadOneRole(Trans trans, Session session, Creator creator, String role) { - load(trans,session,creator,"role='" + role +"' ALLOW FILTERING;"); - } - - public static void loadOneUser(Trans trans, Session session, Creator creator, String user ) { - load(trans,session,creator,"role='"+ user +"';"); - } - - private static void load(Trans trans, Session session, Creator creator, String where) { - 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); + 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); + } + + public static void loadOneRole(Trans trans, Session session, Creator creator, String role) { + load(trans,session,creator,"role='" + role +"' ALLOW FILTERING;"); + } + + public static void loadOneUser(Trans trans, Session session, Creator creator, String user ) { + load(trans,session,creator,"role='"+ user +"';"); + } + + private static void load(Trans trans, Session session, Creator creator, String where) { + 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(); + tt.done(); } try { - tt = trans.start("Load UserRole", Env.SUB); - try { - iterateResults(creator, results.iterator()); - } finally { - tt.done(); - } + tt = trans.start("Load UserRole", Env.SUB); + try { + iterateResults(creator, results.iterator()); + } finally { + tt.done(); + } } finally { - trans.info().log("Loaded",totalLoaded,"UserRoles"); + trans.info().log("Loaded",totalLoaded,"UserRoles"); } - } - - private static void iterateResults(Creator creator, Iterator iter ) { - Row row; - while(iter.hasNext()) { - ++totalLoaded; - row = iter.next(); - UserRole ur = creator.create(row); - 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;"; + } + + private static void iterateResults(Creator creator, Iterator iter ) { + Row row; + while(iter.hasNext()) { + ++totalLoaded; + row = iter.next(); + UserRole ur = creator.create(row); + 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); + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); } finally { - tt.done(); + 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"); } - } - - 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(); - } + cache.getRemoved().clear(); + cache.resetLocalData(); + } } \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java index 17921c8a..4555857a 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java @@ -36,125 +36,125 @@ import org.onap.aaf.auth.org.Mailer; import org.onap.aaf.auth.org.OrganizationException; public class JavaxMailer implements Mailer { - private Session session; - - public JavaxMailer() { - - // Get the default Session object. - session = Session.getDefaultInstance(System.getProperties()); - - } - - @Override - public int sendEmail(AuthzTrans trans, boolean testMode, String mailFrom, List to, List cc, String subject, String body, - Boolean urgent) throws OrganizationException { - - int status = 1; - - - try { - // Create a default MimeMessage object. - MimeMessage message = new MimeMessage(session); - - // Set From: header field of the header. - message.setFrom(new InternetAddress(mailFrom)); - - if (!testMode) { - // Set To: header field of the header. This is a required field - // and calling module should make sure that it is not null or - // blank - message.addRecipients(Message.RecipientType.TO,getAddresses(to)); - - // Set CC: header field of the header. - if ((cc != null) && (cc.size() > 0)) { - message.addRecipients(Message.RecipientType.CC,getAddresses(cc)); - } - - // Set Subject: header field - message.setSubject(subject); - - if (urgent) { - message.addHeader("X-Priority", "1"); - } - - // Now set the actual message - message.setText(body); - } else { - - // override recipients - message.addRecipients(Message.RecipientType.TO, - InternetAddress.parse(mailFrom)); - - // Set Subject: header field - message.setSubject("[TESTMODE] " + subject); - - if (urgent) { - message.addHeader("X-Priority", "1"); - } - - ArrayList newBody = new ArrayList<>(); - - Address temp[] = getAddresses(to); - String headerString = "TO:\t" + InternetAddress.toString(temp) + "\n"; - - temp = getAddresses(cc); - headerString += "CC:\t" + InternetAddress.toString(temp) + "\n"; - - newBody.add(headerString); - - newBody.add("Text: \n"); - - newBody.add(body); - String outString = ""; - for (String s : newBody) { - outString += s + "\n"; - } - - message.setText(outString); - } - // Send message - Transport.send(message); - status = 0; - - } catch (MessagingException mex) { - System.out.println("Error messaging: "+ mex.getMessage()); - System.out.println("Error messaging: "+ mex.toString()); - throw new OrganizationException("Exception send email message " - + mex.getMessage()); - } - - return status; - } - - /** - * Convert the delimiter String into Internet addresses with the default - * delimiter of ";" - * @param strAddress - * @return - */ - private Address[] getAddresses(List strAddress) throws OrganizationException { - return this.getAddresses(strAddress,";"); - } - /** - * Convert the delimiter String into Internet addresses with the - * delimiter of provided - * @param strAddresses - * @param delimiter - * @return - */ - private Address[] getAddresses(List strAddresses, String delimiter) throws OrganizationException { - Address[] addressArray = new Address[strAddresses.size()]; - int count = 0; - for (String addr : strAddresses) - { - try{ - addressArray[count] = new InternetAddress(addr); - count++; - }catch(Exception e){ - throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage()); - } - } - return addressArray; - } + private Session session; + + public JavaxMailer() { + + // Get the default Session object. + session = Session.getDefaultInstance(System.getProperties()); + + } + + @Override + public int sendEmail(AuthzTrans trans, boolean testMode, String mailFrom, List to, List cc, String subject, String body, + Boolean urgent) throws OrganizationException { + + int status = 1; + + + try { + // Create a default MimeMessage object. + MimeMessage message = new MimeMessage(session); + + // Set From: header field of the header. + message.setFrom(new InternetAddress(mailFrom)); + + if (!testMode) { + // Set To: header field of the header. This is a required field + // and calling module should make sure that it is not null or + // blank + message.addRecipients(Message.RecipientType.TO,getAddresses(to)); + + // Set CC: header field of the header. + if ((cc != null) && (cc.size() > 0)) { + message.addRecipients(Message.RecipientType.CC,getAddresses(cc)); + } + + // Set Subject: header field + message.setSubject(subject); + + if (urgent) { + message.addHeader("X-Priority", "1"); + } + + // Now set the actual message + message.setText(body); + } else { + + // override recipients + message.addRecipients(Message.RecipientType.TO, + InternetAddress.parse(mailFrom)); + + // Set Subject: header field + message.setSubject("[TESTMODE] " + subject); + + if (urgent) { + message.addHeader("X-Priority", "1"); + } + + ArrayList newBody = new ArrayList<>(); + + Address temp[] = getAddresses(to); + String headerString = "TO:\t" + InternetAddress.toString(temp) + "\n"; + + temp = getAddresses(cc); + headerString += "CC:\t" + InternetAddress.toString(temp) + "\n"; + + newBody.add(headerString); + + newBody.add("Text: \n"); + + newBody.add(body); + String outString = ""; + for (String s : newBody) { + outString += s + "\n"; + } + + message.setText(outString); + } + // Send message + Transport.send(message); + status = 0; + + } catch (MessagingException mex) { + System.out.println("Error messaging: "+ mex.getMessage()); + System.out.println("Error messaging: "+ mex.toString()); + throw new OrganizationException("Exception send email message " + + mex.getMessage()); + } + + return status; + } + + /** + * Convert the delimiter String into Internet addresses with the default + * delimiter of ";" + * @param strAddress + * @return + */ + private Address[] getAddresses(List strAddress) throws OrganizationException { + return this.getAddresses(strAddress,";"); + } + /** + * Convert the delimiter String into Internet addresses with the + * delimiter of provided + * @param strAddresses + * @param delimiter + * @return + */ + private Address[] getAddresses(List strAddresses, String delimiter) throws OrganizationException { + Address[] addressArray = new Address[strAddresses.size()]; + int count = 0; + for (String addr : strAddresses) + { + try{ + addressArray[count] = new InternetAddress(addr); + count++; + }catch(Exception e){ + throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage()); + } + } + return addressArray; + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java index 67282915..886bd56a 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java @@ -41,29 +41,29 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.util.Chrono; public class ExpiringNext extends Batch { - - public ExpiringNext(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(); - } + + public ExpiringNext(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(); + } - UserRole.load(trans, session, UserRole.v2_0_11); - Cred.load(trans, session); - } finally { - tt0.done(); - } - } + UserRole.load(trans, session, UserRole.v2_0_11); + Cred.load(trans, session); + } finally { + tt0.done(); + } + } - @Override - protected void run(AuthzTrans trans) { + @Override + protected void run(AuthzTrans trans) { GregorianCalendar gc = new GregorianCalendar(); Date now = gc.getTime(); gc.add(GregorianCalendar.WEEK_OF_MONTH, 2); @@ -76,68 +76,68 @@ public class ExpiringNext extends Batch { List expiring = new ArrayList<>(); trans.info().log("Checking for Expired UserRoles"); - for(UserRole ur : UserRole.getData()) { - if(ur.expires().after(now)) { - if(ur.expires().before(twoWeeks)) { - expiring.add(Chrono.dateOnlyStamp(ur.expires()) + ":\t" + ur.user() + '\t' + ur.role()); - } - if(ur.expires().before(earliestUR)) { - earliestUR = ur.expires(); - } - } - } + for(UserRole ur : UserRole.getData()) { + if(ur.expires().after(now)) { + if(ur.expires().before(twoWeeks)) { + expiring.add(Chrono.dateOnlyStamp(ur.expires()) + ":\t" + ur.user() + '\t' + ur.role()); + } + if(ur.expires().before(earliestUR)) { + earliestUR = ur.expires(); + } + } + } - if(expiring.size()>0) { - Collections.sort(expiring,Collections.reverseOrder()); - for(String s : expiring) { - System.err.print('\t'); - System.err.println(s); - } - trans.info().printf("Earliest Expiring UR is %s\n\n", Chrono.dateOnlyStamp(earliestUR)); - } else { - trans.info().printf("No Expiring UserRoles within 2 weeks"); - } - - expiring.clear(); - + if(expiring.size()>0) { + Collections.sort(expiring,Collections.reverseOrder()); + for(String s : expiring) { + System.err.print('\t'); + System.err.println(s); + } + trans.info().printf("Earliest Expiring UR is %s\n\n", Chrono.dateOnlyStamp(earliestUR)); + } else { + trans.info().printf("No Expiring UserRoles within 2 weeks"); + } + + expiring.clear(); + trans.info().log("Checking for Expired Credentials"); - for( Cred creds : Cred.data.values()) { - Instance lastInstance=null; - for(Instance inst : creds.instances) { - if(inst.type==CredDAO.BASIC_AUTH || inst.type==CredDAO.BASIC_AUTH_SHA256) { - if(lastInstance == null || inst.expires.after(lastInstance.expires)) { - lastInstance = inst; - } - } - } - if(lastInstance!=null) { - if(lastInstance.expires.after(now)) { - if(lastInstance.expires.before(twoWeeks)) { - expiring.add(Chrono.dateOnlyStamp(lastInstance.expires) + ": \t" + creds.id); - } - } - if(lastInstance.expires.before(earliestCred)) { - earliestCred = lastInstance.expires; - } - } - } - - if(expiring.size()>0) { - Collections.sort(expiring,Collections.reverseOrder()); - for(String s : expiring) { - System.err.print('\t'); - System.err.println(s); - } - trans.info().printf("Earliest Expiring Cred is %s\n\n", Chrono.dateOnlyStamp(earliestCred)); - } else { - trans.info().printf("No Expiring Creds within 2 weeks"); - } + for( Cred creds : Cred.data.values()) { + Instance lastInstance=null; + for(Instance inst : creds.instances) { + if(inst.type==CredDAO.BASIC_AUTH || inst.type==CredDAO.BASIC_AUTH_SHA256) { + if(lastInstance == null || inst.expires.after(lastInstance.expires)) { + lastInstance = inst; + } + } + } + if(lastInstance!=null) { + if(lastInstance.expires.after(now)) { + if(lastInstance.expires.before(twoWeeks)) { + expiring.add(Chrono.dateOnlyStamp(lastInstance.expires) + ": \t" + creds.id); + } + } + if(lastInstance.expires.before(earliestCred)) { + earliestCred = lastInstance.expires; + } + } + } + + if(expiring.size()>0) { + Collections.sort(expiring,Collections.reverseOrder()); + for(String s : expiring) { + System.err.print('\t'); + System.err.println(s); + } + trans.info().printf("Earliest Expiring Cred is %s\n\n", Chrono.dateOnlyStamp(earliestCred)); + } else { + trans.info().printf("No Expiring Creds within 2 weeks"); + } - } - - @Override - protected void _close(AuthzTrans trans) { + } + + @Override + protected void _close(AuthzTrans trans) { session.close(); - } + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java index e12a452a..868811a3 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java @@ -67,98 +67,98 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.util.Chrono; public class Expiring extends Batch { - private CredPrint crPrint; - private URFutureApprove urFutureApprove; - private URFutureApproveExec urFutureApproveExec; - private CredDelete crDelete; - private URDelete urDelete; - private final CacheTouch cacheTouch; - private final AuthzTrans noAvg; - private final ApprovalDAO apprDAO; - private final FutureDAO futureDAO; - private final PrintStream urDeleteF,urRecoverF; - private final URPrint urPrint; - private Email email; - private File deletesFile; + private CredPrint crPrint; + private URFutureApprove urFutureApprove; + private URFutureApproveExec urFutureApproveExec; + private CredDelete crDelete; + private URDelete urDelete; + private final CacheTouch cacheTouch; + private final AuthzTrans noAvg; + private final ApprovalDAO apprDAO; + private final FutureDAO futureDAO; + private final PrintStream urDeleteF,urRecoverF; + private final URPrint urPrint; + private Email email; + private File deletesFile; - public Expiring(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); - - noAvg = env.newTransNoAvg(); - noAvg.setUser(new BatchPrincipal("batch:Expiring")); - - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - crPrint = new CredPrint("Expired:"); + public Expiring(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); + + noAvg = env.newTransNoAvg(); + noAvg.setUser(new BatchPrincipal("batch:Expiring")); + + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + crPrint = new CredPrint("Expired:"); - TimeTaken tt = trans.start("Connect to Cluster with DAOs", Env.REMOTE); - try { - urFutureApprove = new URFutureApprove(trans, cluster,isDryRun()); - checkOrganizationAcccess(trans, urFutureApprove.question()); - urFutureApproveExec = new URFutureApproveExec(trans, urFutureApprove); - urPrint = new URPrint("User Roles:"); - crDelete = new CredDelete(trans, urFutureApprove); - urDelete = new URDelete(trans,urFutureApprove); - cacheTouch = new CacheTouch(trans, urFutureApprove); - - // Reusing... don't destroy - apprDAO = urFutureApprove.question().approvalDAO; - futureDAO = urFutureApprove.question().futureDAO; + TimeTaken tt = trans.start("Connect to Cluster with DAOs", Env.REMOTE); + try { + urFutureApprove = new URFutureApprove(trans, cluster,isDryRun()); + checkOrganizationAcccess(trans, urFutureApprove.question()); + urFutureApproveExec = new URFutureApproveExec(trans, urFutureApprove); + urPrint = new URPrint("User Roles:"); + crDelete = new CredDelete(trans, urFutureApprove); + urDelete = new URDelete(trans,urFutureApprove); + cacheTouch = new CacheTouch(trans, urFutureApprove); + + // Reusing... don't destroy + apprDAO = urFutureApprove.question().approvalDAO; + futureDAO = urFutureApprove.question().futureDAO; - TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = urFutureApprove.getSession(trans); - } finally { - tt2.done(); - } - } finally { - tt.done(); - } - - 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!!!"); - } - UserRole.setDeleteStream( - urDeleteF = new PrintStream(new FileOutputStream(deletesFile = new File(data_dir,"UserRoleDeletes.dat"),false))); - UserRole.setRecoverStream( - urRecoverF = new PrintStream(new FileOutputStream(new File(data_dir,"UserRoleRecover.dat"),false))); - UserRole.load(trans, session, UserRole.v2_0_11); - - Cred.load(trans, session); - NS.load(trans, session,NS.v2_0_11); - Future.load(trans,session,Future.withConstruct); - Approval.load(trans,session,Approval.v2_0_17); - Role.load(trans, session); - - email = new Email(); - email.subject("AAF Expiring Process Alert (ENV: %s)",batchEnv); - email.preamble("Expiring Process Alert for %s",batchEnv); - email.signature("Sincerely,\nAAF Expiring Batch Process\n"); - String address = env.getProperty("ALERT_TO_ADDRESS"); - if(address==null) { - throw new APIException("ALERT_TO_ADDRESS property is required"); - } - email.addTo(address); - - } catch (OrganizationException e) { - throw new APIException("Error getting valid Organization",e); - } finally { - tt0.done(); - } - } + TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = urFutureApprove.getSession(trans); + } finally { + tt2.done(); + } + } finally { + tt.done(); + } + + 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!!!"); + } + UserRole.setDeleteStream( + urDeleteF = new PrintStream(new FileOutputStream(deletesFile = new File(data_dir,"UserRoleDeletes.dat"),false))); + UserRole.setRecoverStream( + urRecoverF = new PrintStream(new FileOutputStream(new File(data_dir,"UserRoleRecover.dat"),false))); + UserRole.load(trans, session, UserRole.v2_0_11); + + Cred.load(trans, session); + NS.load(trans, session,NS.v2_0_11); + Future.load(trans,session,Future.withConstruct); + Approval.load(trans,session,Approval.v2_0_17); + Role.load(trans, session); + + email = new Email(); + email.subject("AAF Expiring Process Alert (ENV: %s)",batchEnv); + email.preamble("Expiring Process Alert for %s",batchEnv); + email.signature("Sincerely,\nAAF Expiring Batch Process\n"); + String address = env.getProperty("ALERT_TO_ADDRESS"); + if(address==null) { + throw new APIException("ALERT_TO_ADDRESS property is required"); + } + email.addTo(address); + + } catch (OrganizationException e) { + throw new APIException("Error getting valid Organization",e); + } finally { + tt0.done(); + } + } - @Override - protected void run(AuthzTrans trans) { - // Setup Date boundaries - + @Override + protected void run(AuthzTrans trans) { + // Setup Date boundaries + final GregorianCalendar gc = new GregorianCalendar(); final Date now = gc.getTime(); gc.add(GregorianCalendar.MONTH, 1); Date future = gc.getTime(); -// Date earliest = null; +// Date earliest = null; // reset gc.setTime(now); @@ -167,290 +167,290 @@ public class Expiring extends Batch { TimeTaken tt; - // Clean out Approvals UserRoles are fixed up. - String memo; - for(List 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(); - } - + // Clean out Approvals UserRoles are fixed up. + String memo; + for(List 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("### 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; + + 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(); - } + 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(); + tt.done(); } - trans.info().log("### Checking Approvals valid (",Approval.byApprover.size(),"Items)"); + 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; - } - } + 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(); - } + 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); + 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(); + 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(((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); + String str = String.format("%d UserRoles modified or deleted", count); + cacheTouch.exec(trans, "user_role", str); } // Run for Creds @@ -458,49 +458,49 @@ public class Expiring extends Batch { 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; - } - } - } - } + 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); - } + 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) { + } + + @Override + protected void _close(AuthzTrans trans) { aspr.info("End " + this.getClass().getSimpleName() + " processing" ); for(Action action : new Action[] {crDelete}) { - if(action instanceof ActionDAO) { - ((ActionDAO)action).close(trans); - } + 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 index 79e127da..f9797c86 100644 --- 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 @@ -46,113 +46,113 @@ 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; + 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")); + 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(); - } - } + 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) { + @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) { aspr.info("End " + this.getClass().getSimpleName() + " processing" ); for(Action action : new Action[] {urDelete,cacheTouch}) { - if(action instanceof ActionDAO) { - ((ActionDAO)action).close(trans); - } + if(action instanceof ActionDAO) { + ((ActionDAO)action).close(trans); + } } session.close(); try { - urDeleteF.close(); - } catch (IOException e) { - trans.error().log(e); - } - } + 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 index 9653662c..8b12399d 100644 --- 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 @@ -50,187 +50,187 @@ 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; + 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")); + 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)')"); + 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":""); - } + 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; + @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(); - } + 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("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((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"); + 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(); - } + 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 index fe8f16d9..ab386c56 100644 --- 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 @@ -61,261 +61,261 @@ import java.util.TreeMap; 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 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; - 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((supportEmailAddr = env.getProperty("mailFromUserId"))==null) { - throw new APIException("mailFromUserId property must be set"); - } - 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)')"); + 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((supportEmailAddr = env.getProperty("mailFromUserId"))==null) { + throw new APIException("mailFromUserId property must be set"); + } + 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)')"); - Cred.load(trans, session,CredDAO.BASIC_AUTH, CredDAO.BASIC_AUTH_SHA256); - Notification.load(trans, session, Notification.v2_0_18); - UserRole.load(trans, session, UserRole.v2_0_11); - - 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) { - - EmailWarnings ewp = org.emailWarningPolicy(); - long now = System.currentTimeMillis(); - Date early = new Date(now+(ewp.credExpirationWarning()*2)); // 2 months back - Date must = new Date(now+ewp.credExpirationWarning()); // 1 months back - Date critical = new Date(now+ewp.emailUrgentWarning()); // 1 week - Date within2Weeks = new Date(now+604800000 * 2); - Date withinLastWeek = new Date(now-604800000); - Date tooLate = new Date(now); - - // Temp structures - Map lastCred = new HashMap<>(); - Map> ownerCreds = new TreeMap<>(); - Date last; - + Cred.load(trans, session,CredDAO.BASIC_AUTH, CredDAO.BASIC_AUTH_SHA256); + Notification.load(trans, session, Notification.v2_0_18); + UserRole.load(trans, session, UserRole.v2_0_11); + + 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) { + + EmailWarnings ewp = org.emailWarningPolicy(); + long now = System.currentTimeMillis(); + Date early = new Date(now+(ewp.credExpirationWarning()*2)); // 2 months back + Date must = new Date(now+ewp.credExpirationWarning()); // 1 months back + Date critical = new Date(now+ewp.emailUrgentWarning()); // 1 week + Date within2Weeks = new Date(now+604800000 * 2); + Date withinLastWeek = new Date(now-604800000); + Date tooLate = new Date(now); + + // Temp structures + Map lastCred = new HashMap<>(); + Map> ownerCreds = new TreeMap<>(); + Date last; + - List noOwner = new ArrayList<>(); - ownerCreds.put(UNKNOWN_ID,noOwner); + List noOwner = new ArrayList<>(); + ownerCreds.put(UNKNOWN_ID,noOwner); - // Get a list of ONLY the ones needing email by Owner - for(Entry> es : Cred.byNS.entrySet()) { - lastCred.clear(); - for(Cred c : es.getValue()) { - last = c.last(CredDAO.BASIC_AUTH,CredDAO.BASIC_AUTH_SHA256); - if(last!=null && last.after(tooLate) && last.before(early)) { - 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; - int emailCount=0; - 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()); + // Get a list of ONLY the ones needing email by Owner + for(Entry> es : Cred.byNS.entrySet()) { + lastCred.clear(); + for(Cred c : es.getValue()) { + last = c.last(CredDAO.BASIC_AUTH,CredDAO.BASIC_AUTH_SHA256); + if(last!=null && last.after(tooLate) && last.before(early)) { + 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; + int emailCount=0; + 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"; + 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 LastCred { - public Cred cred; - public Date last; - - public LastCred(Cred cred, Date last) { - this.cred = cred; - this.last = last; - } - - // Reverse Sort (Oldest on top) - public static Comparator COMPARE = new Comparator() { - @Override - public int compare(LastCred o1, LastCred o2) { - return o2.last.compareTo(o1.last); - } - }; - - public String toString() { - return Chrono.dateTime(last) + cred.toString(); - } - } - - @Override - protected void _close(AuthzTrans trans) { - session.close(); - ps.close(); - } + 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 LastCred { + public Cred cred; + public Date last; + + public LastCred(Cred cred, Date last) { + this.cred = cred; + this.last = last; + } + + // Reverse Sort (Oldest on top) + public static Comparator COMPARE = new Comparator() { + @Override + public int compare(LastCred o1, LastCred o2) { + return o2.last.compareTo(o1.last); + } + }; + + public String toString() { + return Chrono.dateTime(last) + cred.toString(); + } + } + + @Override + protected void _close(AuthzTrans trans) { + session.close(); + ps.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 index 80ce0ca4..254a6adf 100644 --- 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 @@ -47,49 +47,49 @@ import java.util.List; import org.junit.Test; public class JU_ActionDAO { - - AuthzTrans aTrans; - Cluster cluster; - ActionDAOStub actionDAOStub; - ActionDAOStub actionDAOStub1; + + AuthzTrans aTrans; + Cluster cluster; + ActionDAOStub actionDAOStub; + ActionDAOStub actionDAOStub1; - private class ActionDAOStub extends ActionDAO { + private class ActionDAOStub extends ActionDAO { - public ActionDAOStub(AuthzTrans trans, ActionDAO predecessor) { - super(trans, predecessor); - // TODO Auto-generated constructor stub - } + 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 - } + 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(); - + @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); - } + +// 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_Email.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Email.java index 70cd08a8..d3d4719e 100644 --- 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 @@ -47,105 +47,105 @@ 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(); - } + + 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); - } + @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 index fb5d2bd5..fe87219b 100644 --- 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 @@ -43,50 +43,50 @@ 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"); - - } + + 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); - } + @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_Message.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Message.java index fa7409ea..ada1dbae 100644 --- 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 @@ -33,30 +33,30 @@ import static org.mockito.Mockito.*; import org.junit.Test; public class JU_Message { - - Message msg; - - @Before - public void setUp() { - msg = new 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"); - } + @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/helpers/test/JU_Approval.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approval.java index a0ade9ea..288e929b 100644 --- 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 @@ -42,116 +42,116 @@ import java.util.UUID; import org.junit.Test; 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); - } + + 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 testSizeForDeletion() { - Assert.assertEquals(0, approval.sizeForDeletion()); - } - - @Test - public void testPendingDelete() { - Assert.assertFalse(approval.pendingDelete(approval)); - } - - @Test - public void testDelayDelete() { - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - List list = null; - approval.delayDelete(trans, dao, true, list, "text"); - } + @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 testSizeForDeletion() { + Assert.assertEquals(0, approval.sizeForDeletion()); + } + + @Test + public void testPendingDelete() { + Assert.assertFalse(approval.pendingDelete(approval)); + } + + @Test + public void testDelayDelete() { + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + List list = null; + approval.delayDelete(trans, dao, true, list, "text"); + } } 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 index 37882527..b4ae1213 100644 --- 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 @@ -36,30 +36,30 @@ 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); - } + 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 index c029be13..fc934e6c 100644 --- 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 @@ -39,42 +39,42 @@ import org.junit.Test; public class JU_CacheChange { - CacheChange cc; - - - @Before - public void setUp() { - cc = new CacheChange(); - } - - @Test - public void testDelayedDelete() { - cc.delayedDelete(null); - } + 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); - } + @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 index f07aa820..ad4d2022 100644 --- 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 @@ -38,35 +38,35 @@ import static org.mockito.Mockito.*; import org.junit.Test; public class JU_Creator { - - CreatorStub creatorStub; + + CreatorStub creatorStub; - private class CreatorStub extends Creator{ + private class CreatorStub extends Creator{ - @Override - public Object create(Row row) { - // TODO Auto-generated method stub - return null; - } + @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)); - } + @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 index ad7fbe0c..35a63059 100644 --- 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 @@ -50,93 +50,93 @@ 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; + + 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); - } + @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 index 9d47c138..a3aef1c9 100644 --- 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 @@ -39,70 +39,70 @@ import java.util.UUID; import org.junit.Test; 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); - } + + 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 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)); + } + } 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 index f617af9a..3346f229 100644 --- 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 @@ -38,31 +38,31 @@ 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); - } + + 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)); - } - + @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 index fbb0d23a..c0a9a3cd 100644 --- 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 @@ -44,33 +44,33 @@ 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"); - } + + 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(); - } - } + @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 index 816cda80..6f44b391 100644 --- 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 @@ -38,60 +38,60 @@ 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); + + 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()); - } + 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 index 1fb9b248..cef81ded 100644 --- 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 @@ -42,64 +42,64 @@ 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"); - } + + 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(); - } - } + @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 index 32c8a122..ec158c41 100644 --- 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 @@ -36,44 +36,44 @@ import static org.mockito.Mockito.*; import org.junit.Test; 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); - } + + 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 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"); + } } 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 index b9c09dd9..a566f8d1 100644 --- 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 @@ -39,17 +39,17 @@ import static org.mockito.Mockito.*; import org.junit.Test; 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()); - } + + NsAttrib nsAttrib; + + @Before + public void setUp() { + nsAttrib = new NsAttrib("ns", "key", "value"); + } + + @Test + public void testToString() { + Assert.assertEquals("\"ns\",\"key\",\"value\"", nsAttrib.toString()); + } } 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 index 313eb978..0ccc77a2 100644 --- 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 @@ -39,60 +39,60 @@ 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); - } + + 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); - } + @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 index fcfbec11..3fd9f870 100644 --- 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 @@ -40,55 +40,55 @@ 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); - } + + 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); - } + @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 index ec94d7fc..b6ba7d48 100644 --- 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 @@ -42,105 +42,105 @@ import java.util.Date; import org.junit.Test; 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); - } + + 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 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); + } } 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 index 752b98b7..5394c323 100644 --- 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 @@ -46,47 +46,47 @@ import org.junit.Test; public class JU_Batch { - AuthzEnv env; - Batch batch; - - private class BatchStub extends 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 - } + 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 run(AuthzTrans trans) { + // TODO Auto-generated method stub + + } - @Override - protected void _close(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"); - } + } + + @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 index 9b2f2db0..c56a76c8 100644 --- 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 @@ -35,25 +35,25 @@ 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); - } + 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 index e3cd359f..6186df95 100644 --- 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 @@ -36,13 +36,13 @@ 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()); - } + 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 index 0e7a4244..d1934a42 100644 --- 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 @@ -39,29 +39,29 @@ import java.io.IOException; import org.junit.Test; public class JU_CassBatch { - - AuthzTrans aTrans; - - private class CassBatchStub extends 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 - } + 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 - } + @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-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java index b5a950d4..f24c7c9f 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java @@ -45,459 +45,459 @@ import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.DriverException; public abstract class AbsCassDAO { - protected static final char DOT = '.'; - protected static final char DOT_PLUS_ONE = '.'+1; - protected static final String FIRST_CHAR = Character.toString((char)0); - protected static final String LAST_CHAR = Character.toString((char)Character.MAX_VALUE); - protected static final int FIELD_COMMAS = 0; - protected static final int QUESTION_COMMAS = 1; - protected static final int ASSIGNMENT_COMMAS = 2; - protected static final int WHERE_ANDS = 3; + protected static final char DOT = '.'; + protected static final char DOT_PLUS_ONE = '.'+1; + protected static final String FIRST_CHAR = Character.toString((char)0); + protected static final String LAST_CHAR = Character.toString((char)Character.MAX_VALUE); + protected static final int FIELD_COMMAS = 0; + protected static final int QUESTION_COMMAS = 1; + protected static final int ASSIGNMENT_COMMAS = 2; + protected static final int WHERE_ANDS = 3; - private Cluster cluster; - /* - * From DataStax - * com.datastax.driver.core.Session - A session holds connections to a Cassandra cluster, allowing it to be queried. Each session maintains multiple connections to the cluster nodes, - provides policies to choose which node to use for each query (round-robin on all nodes of the cluster by default), and handles retries for - failed query (when it makes sense), etc... - Session instances are thread-safe and usually a single instance is enough per application. However, a given session can only be set to one - keyspace at a time, so one instance per keyspace is necessary. - */ - private Session session; - private final String keyspace; - // If this is null, then we own session - private final AbsCassDAO owningDAO; - protected Class dataClass; - private final String name; -// private static Slot sessionSlot; // not used since 2015 - private static final ArrayList.PSInfo> psinfos = new ArrayList<>(); - private static final List EMPTY = new ArrayList<>(0); - private static final Deque resetDeque = new ConcurrentLinkedDeque(); - private static boolean resetTrigger = false; - private static long nextAvailableReset = 0; - - public AbsCassDAO(TRANS trans, String name, Cluster cluster, String keyspace, Class dataClass) { - this.name = name; - this.cluster = cluster; - this.keyspace = keyspace; - owningDAO = null; // we own session - session = null; - this.dataClass = dataClass; - } + private Cluster cluster; + /* + * From DataStax + * com.datastax.driver.core.Session + A session holds connections to a Cassandra cluster, allowing it to be queried. Each session maintains multiple connections to the cluster nodes, + provides policies to choose which node to use for each query (round-robin on all nodes of the cluster by default), and handles retries for + failed query (when it makes sense), etc... + Session instances are thread-safe and usually a single instance is enough per application. However, a given session can only be set to one + keyspace at a time, so one instance per keyspace is necessary. + */ + private Session session; + private final String keyspace; + // If this is null, then we own session + private final AbsCassDAO owningDAO; + protected Class dataClass; + private final String name; +// private static Slot sessionSlot; // not used since 2015 + private static final ArrayList.PSInfo> psinfos = new ArrayList<>(); + private static final List EMPTY = new ArrayList<>(0); + private static final Deque resetDeque = new ConcurrentLinkedDeque(); + private static boolean resetTrigger = false; + private static long nextAvailableReset = 0; + + public AbsCassDAO(TRANS trans, String name, Cluster cluster, String keyspace, Class dataClass) { + this.name = name; + this.cluster = cluster; + this.keyspace = keyspace; + owningDAO = null; // we own session + session = null; + this.dataClass = dataClass; + } - public AbsCassDAO(TRANS trans, String name, AbsCassDAO aDao, Class dataClass) { - this.name = name; - cluster = aDao.cluster; - keyspace = aDao.keyspace; - session = null; - // We do not own session - owningDAO = aDao; - this.dataClass = dataClass; - } - + public AbsCassDAO(TRANS trans, String name, AbsCassDAO aDao, Class dataClass) { + this.name = name; + cluster = aDao.cluster; + keyspace = aDao.keyspace; + session = null; + // We do not own session + owningDAO = aDao; + this.dataClass = dataClass; + } + // Not used since 2015 -// public static void setSessionSlot(Slot slot) { -// sessionSlot = slot; -// } +// public static void setSessionSlot(Slot slot) { +// sessionSlot = slot; +// } - //Note: Lower case ON PURPOSE. These names used to create History Messages - public enum CRUD { - create,read,update,delete; - } + //Note: Lower case ON PURPOSE. These names used to create History Messages + public enum CRUD { + create,read,update,delete; + } - public class PSInfo { - private PreparedStatement ps; - private final int size; - private final Loader loader; - private final CRUD crud; // Store CRUD, because it makes a difference in Object Order, see Loader - private final String cql; - private final ConsistencyLevel consistency; + public class PSInfo { + private PreparedStatement ps; + private final int size; + private final Loader loader; + private final CRUD crud; // Store CRUD, because it makes a difference in Object Order, see Loader + private final String cql; + private final ConsistencyLevel consistency; - /** - * Create a PSInfo and create Prepared Statement - * - * @param trans - * @param theCQL - * @param loader - */ - public PSInfo(TRANS trans, String theCQL, Loader loader, ConsistencyLevel consistency) { - this.loader = loader; - this.consistency=consistency; - psinfos.add(this); + /** + * Create a PSInfo and create Prepared Statement + * + * @param trans + * @param theCQL + * @param loader + */ + public PSInfo(TRANS trans, String theCQL, Loader loader, ConsistencyLevel consistency) { + this.loader = loader; + this.consistency=consistency; + psinfos.add(this); - cql = theCQL.trim().toUpperCase(); - if(cql.startsWith("INSERT")) { - crud = CRUD.create; - } else if(cql.startsWith("UPDATE")) { - crud = CRUD.update; - } else if(cql.startsWith("DELETE")) { - crud = CRUD.delete; - } else { - crud = CRUD.read; - } - - int idx = 0, count=0; - while((idx=cql.indexOf('?',idx))>=0) { - ++idx; - ++count; - } - size=count; - } - - public synchronized void reset() { - ps = null; - } - - private synchronized BoundStatement ps(TransStore trans) throws APIException, IOException { - /* From Datastax - You should prepare only once, and cache the PreparedStatement in your application (it is thread-safe). - If you call prepare multiple times with the same query string, the driver will log a warning. - */ - if(ps==null) { - TimeTaken tt = trans.start("Preparing PSInfo " + crud.toString().toUpperCase() + " on " + name,Env.SUB); - try { - ps = getSession(trans).prepare(cql); - ps.setConsistencyLevel(consistency); - } catch (DriverException e) { - reportPerhapsReset(trans,e); - throw e; - } finally { - tt.done(); - } - } - // BoundStatements are NOT threadsafe... need a new one each time. - return new BoundStatement(ps); - } + cql = theCQL.trim().toUpperCase(); + if(cql.startsWith("INSERT")) { + crud = CRUD.create; + } else if(cql.startsWith("UPDATE")) { + crud = CRUD.update; + } else if(cql.startsWith("DELETE")) { + crud = CRUD.delete; + } else { + crud = CRUD.read; + } + + int idx = 0, count=0; + while((idx=cql.indexOf('?',idx))>=0) { + ++idx; + ++count; + } + size=count; + } + + public synchronized void reset() { + ps = null; + } + + private synchronized BoundStatement ps(TransStore trans) throws APIException, IOException { + /* From Datastax + You should prepare only once, and cache the PreparedStatement in your application (it is thread-safe). + If you call prepare multiple times with the same query string, the driver will log a warning. + */ + if(ps==null) { + TimeTaken tt = trans.start("Preparing PSInfo " + crud.toString().toUpperCase() + " on " + name,Env.SUB); + try { + ps = getSession(trans).prepare(cql); + ps.setConsistencyLevel(consistency); + } catch (DriverException e) { + reportPerhapsReset(trans,e); + throw e; + } finally { + tt.done(); + } + } + // BoundStatements are NOT threadsafe... need a new one each time. + return new BoundStatement(ps); + } - /** - * Execute a Prepared Statement by extracting from DATA object - * - * @param trans - * @param text - * @param data - * @return - */ - public Result execAsync(TRANS trans, String text, DATA data) { - TimeTaken tt = trans.start(text, Env.REMOTE); - try { - return Result.ok(getSession(trans).executeAsync( - ps(trans).bind(loader.extract(data, size, crud)))); - } catch (DriverException | APIException | IOException e) { - AbsCassDAO.this.reportPerhapsReset(trans,e); - return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); - } finally { - tt.done(); - } - } + /** + * Execute a Prepared Statement by extracting from DATA object + * + * @param trans + * @param text + * @param data + * @return + */ + public Result execAsync(TRANS trans, String text, DATA data) { + TimeTaken tt = trans.start(text, Env.REMOTE); + try { + return Result.ok(getSession(trans).executeAsync( + ps(trans).bind(loader.extract(data, size, crud)))); + } catch (DriverException | APIException | IOException e) { + AbsCassDAO.this.reportPerhapsReset(trans,e); + return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); + } finally { + tt.done(); + } + } - /** - * Execute a Prepared Statement on Object[] key - * - * @param trans - * @param text - * @param objs - * @return - */ - public Result execAsync(TRANS trans, String text, Object ... objs) { - TimeTaken tt = trans.start(text, Env.REMOTE); - try { - return Result.ok(getSession(trans).executeAsync(ps(trans).bind(objs))); - } catch (DriverException | APIException | IOException e) { - AbsCassDAO.this.reportPerhapsReset(trans,e); - return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); - } finally { - tt.done(); - } - } - - /* - * Note: - * - */ + /** + * Execute a Prepared Statement on Object[] key + * + * @param trans + * @param text + * @param objs + * @return + */ + public Result execAsync(TRANS trans, String text, Object ... objs) { + TimeTaken tt = trans.start(text, Env.REMOTE); + try { + return Result.ok(getSession(trans).executeAsync(ps(trans).bind(objs))); + } catch (DriverException | APIException | IOException e) { + AbsCassDAO.this.reportPerhapsReset(trans,e); + return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); + } finally { + tt.done(); + } + } + + /* + * Note: + * + */ - /** - * Execute a Prepared Statement by extracting from DATA object - * - * @param trans - * @param text - * @param data - * @return - */ - public Result exec(TRANS trans, String text, DATA data) { - TimeTaken tt = trans.start(text, Env.REMOTE); - try { - /* - * "execute" (and executeAsync) - * Executes the provided query. - This method blocks until at least some result has been received from the database. However, - for SELECT queries, it does not guarantee that the result has been received in full. But it - does guarantee that some response has been received from the database, and in particular - guarantee that if the request is invalid, an exception will be thrown by this method. + /** + * Execute a Prepared Statement by extracting from DATA object + * + * @param trans + * @param text + * @param data + * @return + */ + public Result exec(TRANS trans, String text, DATA data) { + TimeTaken tt = trans.start(text, Env.REMOTE); + try { + /* + * "execute" (and executeAsync) + * Executes the provided query. + This method blocks until at least some result has been received from the database. However, + for SELECT queries, it does not guarantee that the result has been received in full. But it + does guarantee that some response has been received from the database, and in particular + guarantee that if the request is invalid, an exception will be thrown by this method. - Parameters: - statement - the CQL query to execute (that can be any Statement). - Returns: - the result of the query. That result will never be null but can be empty (and will - be for any non SELECT query). - */ - return Result.ok(getSession(trans).execute( - ps(trans).bind(loader.extract(data, size, crud)))); - } catch (DriverException | APIException | IOException e) { - AbsCassDAO.this.reportPerhapsReset(trans,e); - return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); - } finally { - tt.done(); - } - } + Parameters: + statement - the CQL query to execute (that can be any Statement). + Returns: + the result of the query. That result will never be null but can be empty (and will + be for any non SELECT query). + */ + return Result.ok(getSession(trans).execute( + ps(trans).bind(loader.extract(data, size, crud)))); + } catch (DriverException | APIException | IOException e) { + AbsCassDAO.this.reportPerhapsReset(trans,e); + return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); + } finally { + tt.done(); + } + } - /** - * Execute a Prepared Statement on Object[] key - * - * @param trans - * @param text - * @param objs - * @return - */ - public Result exec(TRANS trans, String text, Object ... objs) { - TimeTaken tt = trans.start(text, Env.REMOTE); - try { - return Result.ok(getSession(trans).execute(ps(trans).bind(objs))); - } catch (DriverException | APIException | IOException e) { - AbsCassDAO.this.reportPerhapsReset(trans,e); - return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); - } finally { - tt.done(); - } - } + /** + * Execute a Prepared Statement on Object[] key + * + * @param trans + * @param text + * @param objs + * @return + */ + public Result exec(TRANS trans, String text, Object ... objs) { + TimeTaken tt = trans.start(text, Env.REMOTE); + try { + return Result.ok(getSession(trans).execute(ps(trans).bind(objs))); + } catch (DriverException | APIException | IOException e) { + AbsCassDAO.this.reportPerhapsReset(trans,e); + return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); + } finally { + tt.done(); + } + } - /** - * Read the Data from Cassandra given a Prepared Statement (defined by the - * DAO Instance) - * - * This is common behavior among all DAOs. - * @throws DAOException - */ - public Result> read(TRANS trans, String text, Object[] key) { - TimeTaken tt = trans.start(text,Env.REMOTE); - - ResultSet rs; - try { - rs = getSession(trans).execute(key==null?ps(trans):ps(trans).bind(key)); -/// TEST CODE for Exception -// boolean force = true; -// if(force) { -// Map misa = new HashMap<>(); -// //misa.put(new InetSocketAddress(444),new Exception("no host was tried")); -// misa.put(new InetSocketAddress(444),new Exception("Connection has been closed")); -// throw new com.datastax.driver.core.exceptions.NoHostAvailableException(misa); -//// throw new com.datastax.driver.core.exceptions.AuthenticationException(new InetSocketAddress(9999),"no host was tried"); -// } + /** + * Read the Data from Cassandra given a Prepared Statement (defined by the + * DAO Instance) + * + * This is common behavior among all DAOs. + * @throws DAOException + */ + public Result> read(TRANS trans, String text, Object[] key) { + TimeTaken tt = trans.start(text,Env.REMOTE); + + ResultSet rs; + try { + rs = getSession(trans).execute(key==null?ps(trans):ps(trans).bind(key)); +/// TEST CODE for Exception +// boolean force = true; +// if(force) { +// Map misa = new HashMap<>(); +// //misa.put(new InetSocketAddress(444),new Exception("no host was tried")); +// misa.put(new InetSocketAddress(444),new Exception("Connection has been closed")); +// throw new com.datastax.driver.core.exceptions.NoHostAvailableException(misa); +//// throw new com.datastax.driver.core.exceptions.AuthenticationException(new InetSocketAddress(9999),"no host was tried"); +// } //// END TEST CODE - } catch (DriverException | APIException | IOException e) { - AbsCassDAO.this.reportPerhapsReset(trans,e); - return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); - } finally { - tt.done(); - } - - return extract(loader,rs,null /*let Array be created if necessary*/,dflt); - } - - public Result> read(TRANS trans, String text, DATA data) { - return read(trans,text, loader.extract(data, size, crud)); - } - - public Object[] keyFrom(DATA data) { - return loader.extract(data, size, CRUD.delete); // Delete is key only - } + } catch (DriverException | APIException | IOException e) { + AbsCassDAO.this.reportPerhapsReset(trans,e); + return Result.err(Status.ERR_Backend,"%s-%s executing %s",e.getClass().getName(),e.getMessage(), cql); + } finally { + tt.done(); + } + + return extract(loader,rs,null /*let Array be created if necessary*/,dflt); + } + + public Result> read(TRANS trans, String text, DATA data) { + return read(trans,text, loader.extract(data, size, crud)); + } + + public Object[] keyFrom(DATA data) { + return loader.extract(data, size, CRUD.delete); // Delete is key only + } - /* - * Note: in case PSInfos are deleted, we want to remove them from list. This is not expected, - * but we don't want a data leak if it does. Finalize doesn't have to happen quickly - */ - @Override - protected void finalize() throws Throwable { - psinfos.remove(this); - } - } + /* + * Note: in case PSInfos are deleted, we want to remove them from list. This is not expected, + * but we don't want a data leak if it does. Finalize doesn't have to happen quickly + */ + @Override + protected void finalize() throws Throwable { + psinfos.remove(this); + } + } - protected final Accept dflt = new Accept() { - @Override - public boolean ok(DATA data) { - return true; - } - }; + protected final Accept dflt = new Accept() { + @Override + public boolean ok(DATA data) { + return true; + } + }; - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") protected final Result> extract(Loader loader, ResultSet rs, List indata, Accept accept) { - List rows = rs.all(); - if(rows.isEmpty()) { - return Result.ok((List)EMPTY); // Result sets now .emptyList(true); - } else { - DATA d; - List data = indata==null?new ArrayList<>(rows.size()):indata; - - for(Row row : rows) { - try { - d = loader.load(dataClass.newInstance(),row); - if(accept.ok(d)) { - data.add(d); - } - } catch(Exception e) { - return Result.err(e); - } - } - return Result.ok(data); - } + List rows = rs.all(); + if(rows.isEmpty()) { + return Result.ok((List)EMPTY); // Result sets now .emptyList(true); + } else { + DATA d; + List data = indata==null?new ArrayList<>(rows.size()):indata; + + for(Row row : rows) { + try { + d = loader.load(dataClass.newInstance(),row); + if(accept.ok(d)) { + data.add(d); + } + } catch(Exception e) { + return Result.err(e); + } + } + return Result.ok(data); + } } - private static final String NEW_CASSANDRA_SESSION_CREATED = "New Cassandra Session Created"; - private static final String NEW_CASSANDRA_CLUSTER_OBJECT_CREATED = "New Cassandra Cluster Object Created"; - private static final String NEW_CASSANDRA_SESSION = "New Cassandra Session"; - private static final Object LOCK = new Object(); + private static final String NEW_CASSANDRA_SESSION_CREATED = "New Cassandra Session Created"; + private static final String NEW_CASSANDRA_CLUSTER_OBJECT_CREATED = "New Cassandra Cluster Object Created"; + private static final String NEW_CASSANDRA_SESSION = "New Cassandra Session"; + private static final Object LOCK = new Object(); - private static class ResetRequest { - //package on purpose - Session session; - long timestamp; - - public ResetRequest(Session session) { - this.session = session; - timestamp = System.currentTimeMillis(); - } - } + private static class ResetRequest { + //package on purpose + Session session; + long timestamp; + + public ResetRequest(Session session) { + this.session = session; + timestamp = System.currentTimeMillis(); + } + } - - public static final void primePSIs(TransStore trans) throws APIException, IOException { - for(AbsCassDAO.PSInfo psi : psinfos) { - if(psi.ps==null) { - psi.ps(trans); - } - } - } - - public final Session getSession(TransStore trans) throws APIException, IOException { - // SessionFilter unused since 2015 - // Try to use Trans' session, if exists -// if(sessionSlot!=null) { // try to get from Trans -// Session sess = trans.get(sessionSlot, null); -// if(sess!=null) { -// return sess; -// } -// } - - // If there's an owning DAO, use it's session - if(owningDAO!=null) { - return owningDAO.getSession(trans); - } - - // OK, nothing else works... get our own. - if(session==null || resetTrigger) { - Cluster tempCluster = null; - Session tempSession = null; - try { - synchronized(LOCK) { - boolean reset = false; - for(ResetRequest r : resetDeque) { - if(r.session == session) { - if(r.timestamp>nextAvailableReset) { - reset=true; - nextAvailableReset = System.currentTimeMillis() + 60000; - tempCluster = cluster; - tempSession = session; - break; - } else { - trans.warn().log("Cassandra Connection Reset Ignored: Recent Reset"); - } - } - } - - if(reset || session == null) { - TimeTaken tt = trans.start(NEW_CASSANDRA_SESSION, Env.SUB); - try { - // Note: Maitrayee recommended not closing the cluster, just - // overwrite it. Jonathan 9/30/2016 assuming same for Session - // This was a bad idea. Ran out of File Handles as I suspected, Jonathan - if(reset) { - for(AbsCassDAO.PSInfo psi : psinfos) { - psi.reset(); - } - } - if(reset || cluster==null) { - cluster = CassAccess.cluster(trans, keyspace); - trans.warn().log(NEW_CASSANDRA_CLUSTER_OBJECT_CREATED); - } - if(reset || session==null) { - session = cluster.connect(keyspace); - trans.warn().log(NEW_CASSANDRA_SESSION_CREATED); - } - } finally { - resetTrigger=false; - tt.done(); - } - } - } - } finally { - TimeTaken tt = trans.start("Clear Reset Deque", Env.SUB); - try { - resetDeque.clear(); - // Not clearing Session/Cluster appears to kill off FileHandles - if(tempSession!=null && !tempSession.isClosed()) { - tempSession.close(); - } - if(tempCluster!=null && !tempCluster.isClosed()) { - tempCluster.close(); - } - } finally { - tt.done(); - } - } - } - return session; - } - - public final boolean reportPerhapsReset(TransStore trans, Exception e) { - if(owningDAO!=null) { - return owningDAO.reportPerhapsReset(trans, e); - } else { - boolean rv = false; - if(CassAccess.isResetException(e)) { - trans.warn().printf("Session Reset called for %s by %s ",session==null?"":session,e==null?"Mgmt Command":e.getClass().getName()); - resetDeque.addFirst(new ResetRequest(session)); - rv = resetTrigger = true; - } - trans.error().log(e); - return rv; - } - } + + public static final void primePSIs(TransStore trans) throws APIException, IOException { + for(AbsCassDAO.PSInfo psi : psinfos) { + if(psi.ps==null) { + psi.ps(trans); + } + } + } + + public final Session getSession(TransStore trans) throws APIException, IOException { + // SessionFilter unused since 2015 + // Try to use Trans' session, if exists +// if(sessionSlot!=null) { // try to get from Trans +// Session sess = trans.get(sessionSlot, null); +// if(sess!=null) { +// return sess; +// } +// } + + // If there's an owning DAO, use it's session + if(owningDAO!=null) { + return owningDAO.getSession(trans); + } + + // OK, nothing else works... get our own. + if(session==null || resetTrigger) { + Cluster tempCluster = null; + Session tempSession = null; + try { + synchronized(LOCK) { + boolean reset = false; + for(ResetRequest r : resetDeque) { + if(r.session == session) { + if(r.timestamp>nextAvailableReset) { + reset=true; + nextAvailableReset = System.currentTimeMillis() + 60000; + tempCluster = cluster; + tempSession = session; + break; + } else { + trans.warn().log("Cassandra Connection Reset Ignored: Recent Reset"); + } + } + } + + if(reset || session == null) { + TimeTaken tt = trans.start(NEW_CASSANDRA_SESSION, Env.SUB); + try { + // Note: Maitrayee recommended not closing the cluster, just + // overwrite it. Jonathan 9/30/2016 assuming same for Session + // This was a bad idea. Ran out of File Handles as I suspected, Jonathan + if(reset) { + for(AbsCassDAO.PSInfo psi : psinfos) { + psi.reset(); + } + } + if(reset || cluster==null) { + cluster = CassAccess.cluster(trans, keyspace); + trans.warn().log(NEW_CASSANDRA_CLUSTER_OBJECT_CREATED); + } + if(reset || session==null) { + session = cluster.connect(keyspace); + trans.warn().log(NEW_CASSANDRA_SESSION_CREATED); + } + } finally { + resetTrigger=false; + tt.done(); + } + } + } + } finally { + TimeTaken tt = trans.start("Clear Reset Deque", Env.SUB); + try { + resetDeque.clear(); + // Not clearing Session/Cluster appears to kill off FileHandles + if(tempSession!=null && !tempSession.isClosed()) { + tempSession.close(); + } + if(tempCluster!=null && !tempCluster.isClosed()) { + tempCluster.close(); + } + } finally { + tt.done(); + } + } + } + return session; + } + + public final boolean reportPerhapsReset(TransStore trans, Exception e) { + if(owningDAO!=null) { + return owningDAO.reportPerhapsReset(trans, e); + } else { + boolean rv = false; + if(CassAccess.isResetException(e)) { + trans.warn().printf("Session Reset called for %s by %s ",session==null?"":session,e==null?"Mgmt Command":e.getClass().getName()); + resetDeque.addFirst(new ResetRequest(session)); + rv = resetTrigger = true; + } + trans.error().log(e); + return rv; + } + } - public void close(TransStore trans) { - if(owningDAO==null) { - if(session!=null) { - TimeTaken tt = trans.start("Cassandra Session Close", Env.SUB); - try { - session.close(); - } finally { - tt.done(); - } - session = null; - } else { - trans.debug().log("close called(), Session already closed"); - } - } else { - owningDAO.close(trans); - } - } + public void close(TransStore trans) { + if(owningDAO==null) { + if(session!=null) { + TimeTaken tt = trans.start("Cassandra Session Close", Env.SUB); + try { + session.close(); + } finally { + tt.done(); + } + session = null; + } else { + trans.debug().log("close called(), Session already closed"); + } + } else { + owningDAO.close(trans); + } + } - protected void wasModified(TRANS trans, CRUD modified, DATA data, String ... override) { - } - - protected interface Accept { - public boolean ok(DATA data); - } + protected void wasModified(TRANS trans, CRUD modified, DATA data, String ... override) { + } + + protected interface Accept { + public boolean ok(DATA data); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Bytification.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Bytification.java index 279f399d..965ee2c2 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Bytification.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Bytification.java @@ -25,6 +25,6 @@ import java.io.IOException; import java.nio.ByteBuffer; public interface Bytification { - public ByteBuffer bytify() throws IOException; - public void reconstitute(ByteBuffer bb) throws IOException; + public ByteBuffer bytify() throws IOException; + public void reconstitute(ByteBuffer bb) throws IOException; } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CIDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CIDAO.java index 83b13c34..b148e87a 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CIDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CIDAO.java @@ -28,23 +28,23 @@ import org.onap.aaf.misc.env.Trans; public interface CIDAO { - /** - * Touch the date field for given Table - * - * @param trans - * @param name - * @return - */ - public abstract Result touch(TRANS trans, String name, int ... seg); - - /** - * Read all Info entries, and set local Date objects - * - * This is to support regular data checks on the Database to speed up Caching behavior - * - */ - public abstract Result check(TRANS trans); - - public abstract Date get(TRANS trans, String table, int seg); + /** + * Touch the date field for given Table + * + * @param trans + * @param name + * @return + */ + public abstract Result touch(TRANS trans, String name, int ... seg); + + /** + * Read all Info entries, and set local Date objects + * + * This is to support regular data checks on the Database to speed up Caching behavior + * + */ + public abstract Result check(TRANS trans); + + public abstract Date get(TRANS trans, String table, int seg); } \ No newline at end of file diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cacheable.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cacheable.java index d697b90e..3632aa15 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cacheable.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cacheable.java @@ -30,5 +30,5 @@ package org.onap.aaf.auth.dao; * */ public interface Cacheable { - public int[] invalidate(Cached cache); + public int[] invalidate(Cached cache); } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java index 0797b041..3f4bbb20 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java @@ -36,164 +36,164 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.Trans; public class Cached extends Cache { - // Java does not allow creation of Arrays with Generics in them... - // private Map cache[]; - protected final CIDAO info; - - private static Timer infoTimer; - private Object cache[]; - public final int segSize; - - protected final String name; - - private final long expireIn; - - - - // Taken from String Hash, but coded, to ensure consistent across Java versions. Also covers negative case; - public int cacheIdx(String key) { - int h = 0; - for (int i = 0; i < key.length(); i++) { - h = 31*h + key.charAt(i); - } - if(h<0)h*=-1; - return h%segSize; - } - - public Cached(CIDAO info, String name, int segSize, long expireIn) { - this.name =name; - this.segSize = segSize; - this.info = info; - this.expireIn = expireIn; - cache = new Object[segSize]; - // Create a new Map for each Segment, and store locally - for(int i=0;i data) { - @SuppressWarnings("unchecked") - Map map = ((Map)cache[cacheIdx(key)]); - map.put(key, new Dated(data, expireIn)); - } - - - public int invalidate(String key) { - int cacheIdx = cacheIdx(key); - @SuppressWarnings("unchecked") - Map map = ((Map)cache[cacheIdx]); -// if(map.remove(key)!=null) // Not seeming to remove all the time - if(map!=null)map.clear(); -// System.err.println("Remove " + name + " " + key); - return cacheIdx; - } - - public Result invalidate(int segment) { - if(segment<0 || segment>=cache.length) return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment)); - @SuppressWarnings("unchecked") - Map map = ((Map)cache[segment]); - if(map!=null) { - map.clear(); - } - return Result.ok(); - } - - protected interface Getter { - public abstract Result> get(); - }; - - // TODO utilize Segmented Caches, and fold "get" into "reads" - @SuppressWarnings("unchecked") - public Result> get(TRANS trans, String key, Getter getter) { - List ld = null; - Result> rld = null; - - int cacheIdx = cacheIdx(key); - Map map = ((Map)cache[cacheIdx]); - - // Check for saved element in cache - Dated cached = map.get(key); - // Note: These Segment Timestamps are kept up to date with DB - Date dbStamp = info.get(trans, name,cacheIdx); - - // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax) - if(cached!=null && dbStamp.before(cached.timestamp)) { - ld = (List)cached.data; - rld = Result.ok(ld); - } else { - rld = getter.get(); - if(rld.isOK()) { // only store valid lists - map.put(key, new Dated(rld.value,expireIn)); // successful item found gets put in cache -// } else if(rld.status == Result.ERR_Backend){ -// map.remove(key); - } - } - return rld; - } - - /** - * Each Cached object has multiple Segments that need cleaning. Derive each, and add to Cleansing Thread - * @param env - * @param dao - */ - public static void startCleansing(AuthzEnv env, CachedDAO ... dao) { - for(CachedDAO d : dao) { - for(int i=0;i void startRefresh(AuthzEnv env, CIDAO cidao) { - if(infoTimer==null) { - infoTimer = new Timer("CachedDAO Info Refresh Timer"); - int minRefresh = 10*1000*60; // 10 mins Integer.parseInt(env.getProperty(CACHE_MIN_REFRESH_INTERVAL,"2000")); // 2 second minimum refresh - infoTimer.schedule(new Refresh(env,cidao, minRefresh), 1000, minRefresh); // note: Refresh from DB immediately - } - } - - public static void stopTimer() { - Cache.stopTimer(); - if(infoTimer!=null) { - infoTimer.cancel(); - infoTimer = null; - } - } - - private final static class Refresh extends TimerTask { - private static final int maxRefresh = 2*60*10000; // 20 mins - private AuthzEnv env; - private CIDAO cidao; - private int minRefresh; - private long lastRun; - - public Refresh(AuthzEnv env, CIDAO cidao, int minRefresh) { - this.env = env; - this.cidao = cidao; - this.minRefresh = minRefresh; - lastRun = System.currentTimeMillis()-maxRefresh-1000; - } - - @Override - public void run() { - // Evaluate whether to refresh based on transaction rate - long now = System.currentTimeMillis(); - long interval = now-lastRun; - - if(interval < minRefresh || interval < Math.min(env.transRate(),maxRefresh)) return; - lastRun = now; - AuthzTrans trans = env.newTransNoAvg(); - Result rv = cidao.check(trans); - if(rv.status!=Result.OK) { - env.error().log("Error in CacheInfo Refresh",rv.details); - } - if(env.debug().isLoggable()) { - StringBuilder sb = new StringBuilder("Cache Info Refresh: "); - trans.auditTrail(0, sb, Env.REMOTE); - env.debug().log(sb); - } - } - } + // Java does not allow creation of Arrays with Generics in them... + // private Map cache[]; + protected final CIDAO info; + + private static Timer infoTimer; + private Object cache[]; + public final int segSize; + + protected final String name; + + private final long expireIn; + + + + // Taken from String Hash, but coded, to ensure consistent across Java versions. Also covers negative case; + public int cacheIdx(String key) { + int h = 0; + for (int i = 0; i < key.length(); i++) { + h = 31*h + key.charAt(i); + } + if(h<0)h*=-1; + return h%segSize; + } + + public Cached(CIDAO info, String name, int segSize, long expireIn) { + this.name =name; + this.segSize = segSize; + this.info = info; + this.expireIn = expireIn; + cache = new Object[segSize]; + // Create a new Map for each Segment, and store locally + for(int i=0;i data) { + @SuppressWarnings("unchecked") + Map map = ((Map)cache[cacheIdx(key)]); + map.put(key, new Dated(data, expireIn)); + } + + + public int invalidate(String key) { + int cacheIdx = cacheIdx(key); + @SuppressWarnings("unchecked") + Map map = ((Map)cache[cacheIdx]); +// if(map.remove(key)!=null) // Not seeming to remove all the time + if(map!=null)map.clear(); +// System.err.println("Remove " + name + " " + key); + return cacheIdx; + } + + public Result invalidate(int segment) { + if(segment<0 || segment>=cache.length) return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment)); + @SuppressWarnings("unchecked") + Map map = ((Map)cache[segment]); + if(map!=null) { + map.clear(); + } + return Result.ok(); + } + + protected interface Getter { + public abstract Result> get(); + }; + + // TODO utilize Segmented Caches, and fold "get" into "reads" + @SuppressWarnings("unchecked") + public Result> get(TRANS trans, String key, Getter getter) { + List ld = null; + Result> rld = null; + + int cacheIdx = cacheIdx(key); + Map map = ((Map)cache[cacheIdx]); + + // Check for saved element in cache + Dated cached = map.get(key); + // Note: These Segment Timestamps are kept up to date with DB + Date dbStamp = info.get(trans, name,cacheIdx); + + // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax) + if(cached!=null && dbStamp.before(cached.timestamp)) { + ld = (List)cached.data; + rld = Result.ok(ld); + } else { + rld = getter.get(); + if(rld.isOK()) { // only store valid lists + map.put(key, new Dated(rld.value,expireIn)); // successful item found gets put in cache +// } else if(rld.status == Result.ERR_Backend){ +// map.remove(key); + } + } + return rld; + } + + /** + * Each Cached object has multiple Segments that need cleaning. Derive each, and add to Cleansing Thread + * @param env + * @param dao + */ + public static void startCleansing(AuthzEnv env, CachedDAO ... dao) { + for(CachedDAO d : dao) { + for(int i=0;i void startRefresh(AuthzEnv env, CIDAO cidao) { + if(infoTimer==null) { + infoTimer = new Timer("CachedDAO Info Refresh Timer"); + int minRefresh = 10*1000*60; // 10 mins Integer.parseInt(env.getProperty(CACHE_MIN_REFRESH_INTERVAL,"2000")); // 2 second minimum refresh + infoTimer.schedule(new Refresh(env,cidao, minRefresh), 1000, minRefresh); // note: Refresh from DB immediately + } + } + + public static void stopTimer() { + Cache.stopTimer(); + if(infoTimer!=null) { + infoTimer.cancel(); + infoTimer = null; + } + } + + private final static class Refresh extends TimerTask { + private static final int maxRefresh = 2*60*10000; // 20 mins + private AuthzEnv env; + private CIDAO cidao; + private int minRefresh; + private long lastRun; + + public Refresh(AuthzEnv env, CIDAO cidao, int minRefresh) { + this.env = env; + this.cidao = cidao; + this.minRefresh = minRefresh; + lastRun = System.currentTimeMillis()-maxRefresh-1000; + } + + @Override + public void run() { + // Evaluate whether to refresh based on transaction rate + long now = System.currentTimeMillis(); + long interval = now-lastRun; + + if(interval < minRefresh || interval < Math.min(env.transRate(),maxRefresh)) return; + lastRun = now; + AuthzTrans trans = env.newTransNoAvg(); + Result rv = cidao.check(trans); + if(rv.status!=Result.OK) { + env.error().log("Error in CacheInfo Refresh",rv.details); + } + if(env.debug().isLoggable()) { + StringBuilder sb = new StringBuilder("Cache Info Refresh: "); + trans.auditTrail(0, sb, Env.REMOTE); + env.debug().log(sb); + } + } + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java index f468dba4..9375502c 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java @@ -40,189 +40,189 @@ import org.onap.aaf.misc.env.Trans; * @param */ public class CachedDAO,DATA extends Cacheable> - extends Cached implements DAO_RO{ -// private final String dirty_str; - - private final D dao; + extends Cached implements DAO_RO{ +// private final String dirty_str; + + private final D dao; - public CachedDAO(D dao, CIDAO info, int segsize, long expireIn) { - super(info, dao.table(), segsize, expireIn); - - // Instantiate a new Cache per DAO name (so separate instances use the same cache) - this.dao = dao; - //read_str = "Cached READ for " + dao.table(); -// dirty_str = "Cache DIRTY on " + dao.table(); - if(dao instanceof CassDAOImpl) { - ((CassDAOImpl)dao).cache = this; - } - } - - public static, DT extends Cacheable> - CachedDAO create(DA dao, CIDAO info, int segsize, long expireIn) { - return new CachedDAO(dao,info, segsize, expireIn); - } + public CachedDAO(D dao, CIDAO info, int segsize, long expireIn) { + super(info, dao.table(), segsize, expireIn); + + // Instantiate a new Cache per DAO name (so separate instances use the same cache) + this.dao = dao; + //read_str = "Cached READ for " + dao.table(); +// dirty_str = "Cache DIRTY on " + dao.table(); + if(dao instanceof CassDAOImpl) { + ((CassDAOImpl)dao).cache = this; + } + } + + public static, DT extends Cacheable> + CachedDAO create(DA dao, CIDAO info, int segsize, long expireIn) { + return new CachedDAO(dao,info, segsize, expireIn); + } - public void add(DATA data) { - String key = keyFromObjs(dao.keyFrom(data)); - List list = new ArrayList<>(); - list.add(data); - super.add(key,list); - } - -// public void invalidate(TRANS trans, Object ... objs) { -// TimeTaken tt = trans.start(dirty_str, Env.SUB); -// try { -// super.invalidate(keyFromObjs(objs)); -// } finally { -// tt.done(); -// } -// } + public void add(DATA data) { + String key = keyFromObjs(dao.keyFrom(data)); + List list = new ArrayList<>(); + list.add(data); + super.add(key,list); + } + +// public void invalidate(TRANS trans, Object ... objs) { +// TimeTaken tt = trans.start(dirty_str, Env.SUB); +// try { +// super.invalidate(keyFromObjs(objs)); +// } finally { +// tt.done(); +// } +// } - public static String keyFromObjs(Object ... objs) { - String key; - if(objs.length==1 && objs[0] instanceof String) { - key = (String)objs[0]; - } else { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for(Object o : objs) { - if(o!=null) { - if(first) { - first =false; - } else { - sb.append('|'); - } - sb.append(o.toString()); - } - } - key = sb.toString(); - } - return key; - } + public static String keyFromObjs(Object ... objs) { + String key; + if(objs.length==1 && objs[0] instanceof String) { + key = (String)objs[0]; + } else { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for(Object o : objs) { + if(o!=null) { + if(first) { + first =false; + } else { + sb.append('|'); + } + sb.append(o.toString()); + } + } + key = sb.toString(); + } + return key; + } - public Result create(TRANS trans, DATA data) { - Result d = dao.create(trans,data); - if(d.status==Status.OK) { - add(d.value); - } else { - trans.error().log(d.errorString()); - } - // dao.create already modifies cache. Do not invalidate again. invalidate(trans,data); - return d; - } + public Result create(TRANS trans, DATA data) { + Result d = dao.create(trans,data); + if(d.status==Status.OK) { + add(d.value); + } else { + trans.error().log(d.errorString()); + } + // dao.create already modifies cache. Do not invalidate again. invalidate(trans,data); + return d; + } - protected class DAOGetter implements Getter { - protected TRANS trans; - protected Object objs[]; - protected D dao; - public Result> result; + protected class DAOGetter implements Getter { + protected TRANS trans; + protected Object objs[]; + protected D dao; + public Result> result; - public DAOGetter(TRANS trans, D dao, Object ... objs) { - this.trans = trans; - this.dao = dao; - this.objs = objs; - } - - /** - * Separated into single call for easy overloading - * @return - */ - public Result> call() { - return dao.read(trans, objs); - } - - @Override - public final Result> get() { - return call(); -// if(result.isOKhasData()) { // Note, given above logic, could exist, but stale -// return result.value; -// } else { -// return null; -// } - } - } + public DAOGetter(TRANS trans, D dao, Object ... objs) { + this.trans = trans; + this.dao = dao; + this.objs = objs; + } + + /** + * Separated into single call for easy overloading + * @return + */ + public Result> call() { + return dao.read(trans, objs); + } + + @Override + public final Result> get() { + return call(); +// if(result.isOKhasData()) { // Note, given above logic, could exist, but stale +// return result.value; +// } else { +// return null; +// } + } + } - @Override - public Result> read(final TRANS trans, final Object ... objs) { - DAOGetter getter = new DAOGetter(trans,dao,objs); - return get(trans, keyFromObjs(objs),getter); -// if(ld!=null) { -// return Result.ok(ld);//.emptyList(ld.isEmpty()); -// } -// // Result Result if exists -// if(getter.result==null) { -// return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); -// } -// return getter.result; - } + @Override + public Result> read(final TRANS trans, final Object ... objs) { + DAOGetter getter = new DAOGetter(trans,dao,objs); + return get(trans, keyFromObjs(objs),getter); +// if(ld!=null) { +// return Result.ok(ld);//.emptyList(ld.isEmpty()); +// } +// // Result Result if exists +// if(getter.result==null) { +// return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); +// } +// return getter.result; + } - // Slight Improved performance available when String and Obj versions are known. - public Result> read(final String key, final TRANS trans, final Object[] objs) { - DAOGetter getter = new DAOGetter(trans,dao,objs); - return get(trans, key, getter); -// if(ld!=null) { -// return Result.ok(ld);//.emptyList(ld.isEmpty()); -// } -// // Result Result if exists -// if(getter.result==null) { -// return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); -// } -// return getter.result; - } - - @Override - public Result> read(TRANS trans, DATA data) { - return read(trans,dao.keyFrom(data)); - } - public Result update(TRANS trans, DATA data) { - Result d = dao.update(trans, data); - if(d.status==Status.OK) { - add(data); - } else { - trans.error().log(d.errorString()); - } - return d; - } + // Slight Improved performance available when String and Obj versions are known. + public Result> read(final String key, final TRANS trans, final Object[] objs) { + DAOGetter getter = new DAOGetter(trans,dao,objs); + return get(trans, key, getter); +// if(ld!=null) { +// return Result.ok(ld);//.emptyList(ld.isEmpty()); +// } +// // Result Result if exists +// if(getter.result==null) { +// return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); +// } +// return getter.result; + } + + @Override + public Result> read(TRANS trans, DATA data) { + return read(trans,dao.keyFrom(data)); + } + public Result update(TRANS trans, DATA data) { + Result d = dao.update(trans, data); + if(d.status==Status.OK) { + add(data); + } else { + trans.error().log(d.errorString()); + } + return d; + } - public Result delete(TRANS trans, DATA data, boolean reread) { - if(reread) { // If reread, get from Cache, if possible, not DB exclusively - Result> rd = read(trans,data); - if(rd.notOK()) { - return Result.err(rd); -// } else { -// trans.error().log(rd.errorString()); - } - if(rd.isEmpty()) { - data.invalidate(this); - return Result.err(Status.ERR_NotFound,"Not Found"); - } - data = rd.value.get(0); - } - Result rv=dao.delete(trans, data, false); - data.invalidate(this); - return rv; - } - - @Override - public void close(TRANS trans) { - if(dao!=null) { - dao.close(trans); - } - } - + public Result delete(TRANS trans, DATA data, boolean reread) { + if(reread) { // If reread, get from Cache, if possible, not DB exclusively + Result> rd = read(trans,data); + if(rd.notOK()) { + return Result.err(rd); +// } else { +// trans.error().log(rd.errorString()); + } + if(rd.isEmpty()) { + data.invalidate(this); + return Result.err(Status.ERR_NotFound,"Not Found"); + } + data = rd.value.get(0); + } + Result rv=dao.delete(trans, data, false); + data.invalidate(this); + return rv; + } + + @Override + public void close(TRANS trans) { + if(dao!=null) { + dao.close(trans); + } + } + - @Override - public String table() { - return dao.table(); - } - - public D dao() { - return dao; - } - - public void invalidate(TRANS trans, DATA data) { + @Override + public String table() { + return dao.table(); + } + + public D dao() { + return dao; + } + + public void invalidate(TRANS trans, DATA data) { if(info.touch(trans, dao.table(),data.invalidate(this)).notOK()) { - trans.error().log("Cannot touch CacheInfo for Role"); - } - } + trans.error().log("Cannot touch CacheInfo for Role"); + } + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java index c213a04b..9b168a83 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java @@ -38,186 +38,186 @@ import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import com.datastax.driver.core.policies.TokenAwarePolicy; public class CassAccess { - public static final String KEYSPACE = "authz"; - public static final String CASSANDRA_CLUSTERS = "cassandra.clusters"; - public static final String CASSANDRA_CLUSTERS_PORT = "cassandra.clusters.port"; - public static final String CASSANDRA_CLUSTERS_USER_NAME = "cassandra.clusters.user"; - public static final String CASSANDRA_CLUSTERS_PASSWORD = "cassandra.clusters.password"; - public static final String CASSANDRA_RESET_EXCEPTIONS = "cassandra.reset.exceptions"; - private static final List resetExceptions = new ArrayList<>(); - public static final String ERR_ACCESS_MSG = "Accessing Backend"; - private static Builder cb = null; + public static final String KEYSPACE = "authz"; + public static final String CASSANDRA_CLUSTERS = "cassandra.clusters"; + public static final String CASSANDRA_CLUSTERS_PORT = "cassandra.clusters.port"; + public static final String CASSANDRA_CLUSTERS_USER_NAME = "cassandra.clusters.user"; + public static final String CASSANDRA_CLUSTERS_PASSWORD = "cassandra.clusters.password"; + public static final String CASSANDRA_RESET_EXCEPTIONS = "cassandra.reset.exceptions"; + private static final List resetExceptions = new ArrayList<>(); + public static final String ERR_ACCESS_MSG = "Accessing Backend"; + private static Builder cb = null; - /** - * To create DCAwareRoundRobing Policy: - * Need Properties - * LATITUDE (or AFT_LATITUDE) - * LONGITUDE (or AFT_LONGITUDE) - * CASSANDRA CLUSTERS with additional information: - * machine:DC:lat:long,machine:DC:lat:long - * @param env - * @param prefix - * @return - * @throws APIException - * @throws IOException - */ + /** + * To create DCAwareRoundRobing Policy: + * Need Properties + * LATITUDE (or AFT_LATITUDE) + * LONGITUDE (or AFT_LONGITUDE) + * CASSANDRA CLUSTERS with additional information: + * machine:DC:lat:long,machine:DC:lat:long + * @param env + * @param prefix + * @return + * @throws APIException + * @throws IOException + */ -// @SuppressWarnings("deprecation") - public static synchronized Cluster cluster(Env env, String prefix) throws APIException, IOException { - if(cb == null) { - String pre; - if(prefix==null) { - pre=""; - } else { - env.info().log("Cassandra Connection for ",prefix); - pre = prefix+'.'; - } - cb = Cluster.builder(); - String str = env.getProperty(pre+CASSANDRA_CLUSTERS_PORT,env.getProperty(CASSANDRA_CLUSTERS_PORT,"9042")); - if(str!=null) { - env.init().log("Cass Port = ",str ); - cb.withPort(Integer.parseInt(str)); - } - str = env.getProperty(pre+CASSANDRA_CLUSTERS_USER_NAME,env.getProperty(CASSANDRA_CLUSTERS_USER_NAME,null)); - if(str!=null) { - env.init().log("Cass User = ",str ); - String epass = env.getProperty(pre + CASSANDRA_CLUSTERS_PASSWORD,env.getProperty(CASSANDRA_CLUSTERS_PASSWORD,null)); - if(epass==null) { - throw new APIException("No Password configured for " + str); - } - //TODO Figure out way to ensure Decryptor setting in AuthzEnv - if(env instanceof AuthzEnv) { - cb.withCredentials(str,((AuthzEnv)env).decrypt(epass,true)); - } else { - cb.withCredentials(str, env.decryptor().decrypt(epass)); - } - } - - str = env.getProperty(pre+CASSANDRA_RESET_EXCEPTIONS,env.getProperty(CASSANDRA_RESET_EXCEPTIONS,null)); - if(str!=null) { - env.init().log("Cass ResetExceptions = ",str ); - for(String ex : Split.split(',', str)) { - resetExceptions.add(new Resettable(env,ex)); - } - } - - str = env.getProperty(Config.CADI_LATITUDE); - Double lat = str!=null?Double.parseDouble(str):null; - str = env.getProperty(Config.CADI_LONGITUDE); - Double lon = str!=null?Double.parseDouble(str):null; - if(lat == null || lon == null) { - throw new APIException(Config.CADI_LATITUDE + " and/or " + Config.CADI_LONGITUDE + " are not set"); - } - - env.init().printf("Service Latitude,Longitude = %f,%f",lat,lon); - - str = env.getProperty(pre+CASSANDRA_CLUSTERS,env.getProperty(CASSANDRA_CLUSTERS,"localhost")); - env.init().log("Cass Clusters = ",str ); - String[] machs = Split.split(',', str); - String[] cpoints = new String[machs.length]; - String bestDC = null; - int numInBestDC = 1; - double mlat, mlon,temp,distance = Double.MAX_VALUE; - for(int i=0;i0) { - cpoints[i]=minfo[0]; - } - - if(minfo.length>3) { - if(minfo[1].equals(bestDC)) { - ++numInBestDC; - } else { - // Calc closest DC with Great Circle - mlat = Double.parseDouble(minfo[2]); - mlon = Double.parseDouble(minfo[3]); - // Note: GreatCircle Distance is always >= 0.0 (not negative) - if((temp=GreatCircle.calc(lat, lon, mlat, mlon)) < distance) { - distance = temp; - if(bestDC==null || !bestDC.equals(minfo[1])) { - bestDC = minfo[1]; - numInBestDC = 1; - } - } - } - } - } - - cb.addContactPoints(cpoints); - - if(bestDC!=null) { - // 8/26/2016 Management has determined that Accuracy is preferred over speed in bad situations - // Local DC Aware Load Balancing appears to have the highest normal performance, with the best - // Degraded Accuracy - DCAwareRoundRobinPolicy dcrrPolicy = DCAwareRoundRobinPolicy.builder() - .withLocalDc(bestDC) - .withUsedHostsPerRemoteDc(numInBestDC) - .build(); -// cb.withLoadBalancingPolicy(new DCAwareRoundRobinPolicy( -// bestDC, numInBestDC, true /*allow LocalDC to look at other DCs for LOCAL_QUORUM */)); - cb.withLoadBalancingPolicy(new TokenAwarePolicy(dcrrPolicy)); - env.init().printf("Cassandra configured for DCAwareRoundRobinPolicy with best DC at %s with emergency remote of up to %d node(s)" - ,bestDC, numInBestDC); - } else { - env.init().printf("Cassandra is using Default Policy, which is not DC aware"); - } - } - return cb.build(); - } - - private static class Resettable { - private Class cls; - private List messages; - - @SuppressWarnings("unchecked") - public Resettable(Env env, String propData) throws APIException { - if(propData!=null && propData.length()>1) { - String[] split = Split.split(':', propData); - if(split.length>0) { - try { - cls = (Class)Class.forName(split[0]); - } catch (ClassNotFoundException e) { - throw new APIException("Declared Cassandra Reset Exception, " + propData + ", cannot be ClassLoaded"); - } - } - if(split.length>1) { - messages=new ArrayList<>(); - for(int i=1;i cls; + private List messages; + + @SuppressWarnings("unchecked") + public Resettable(Env env, String propData) throws APIException { + if(propData!=null && propData.length()>1) { + String[] split = Split.split(':', propData); + if(split.length>0) { + try { + cls = (Class)Class.forName(split[0]); + } catch (ClassNotFoundException e) { + throw new APIException("Declared Cassandra Reset Exception, " + propData + ", cannot be ClassLoaded"); + } + } + if(split.length>1) { + messages=new ArrayList<>(); + for(int i=1;i */ public class CassDAOImpl extends AbsCassDAO implements DAO { - public static final String USER_NAME = "__USER_NAME__"; - protected static final String CREATE_SP = "CREATE "; - protected static final String UPDATE_SP = "UPDATE "; - protected static final String DELETE_SP = "DELETE "; - protected static final String SELECT_SP = "SELECT "; + public static final String USER_NAME = "__USER_NAME__"; + protected static final String CREATE_SP = "CREATE "; + protected static final String UPDATE_SP = "UPDATE "; + protected static final String DELETE_SP = "DELETE "; + protected static final String SELECT_SP = "SELECT "; - protected final String C_TEXT = getClass().getSimpleName() + " CREATE"; - protected final String R_TEXT = getClass().getSimpleName() + " READ"; - protected final String U_TEXT = getClass().getSimpleName() + " UPDATE"; - protected final String D_TEXT = getClass().getSimpleName() + " DELETE"; - private String table; - - protected final ConsistencyLevel readConsistency,writeConsistency; - - // Setteable only by CachedDAO - protected Cached cache; + protected final String C_TEXT = getClass().getSimpleName() + " CREATE"; + protected final String R_TEXT = getClass().getSimpleName() + " READ"; + protected final String U_TEXT = getClass().getSimpleName() + " UPDATE"; + protected final String D_TEXT = getClass().getSimpleName() + " DELETE"; + private String table; + + protected final ConsistencyLevel readConsistency,writeConsistency; + + // Setteable only by CachedDAO + protected Cached cache; - /** - * A Constructor from the originating Cluster. This DAO will open the Session at need, - * and shutdown the session when "close()" is called. - * - * @param cluster - * @param keyspace - * @param dataClass - */ - public CassDAOImpl(TRANS trans, String name, Cluster cluster, String keyspace, Class dataClass, String table, ConsistencyLevel read, ConsistencyLevel write) { - super(trans, name, cluster,keyspace,dataClass); - this.table = table; - readConsistency = read; - writeConsistency = write; - } - - /** - * A Constructor to share Session with other DAOs. - * - * This method get the Session and Cluster information from the calling DAO, and won't - * touch the Session on closure. - * - * @param aDao - * @param dataClass - */ - public CassDAOImpl(TRANS trans, String name, AbsCassDAO aDao, Class dataClass, String table, ConsistencyLevel read, ConsistencyLevel write) { - super(trans, name, aDao,dataClass); - this.table = table; - readConsistency = read; - writeConsistency = write; - } + /** + * A Constructor from the originating Cluster. This DAO will open the Session at need, + * and shutdown the session when "close()" is called. + * + * @param cluster + * @param keyspace + * @param dataClass + */ + public CassDAOImpl(TRANS trans, String name, Cluster cluster, String keyspace, Class dataClass, String table, ConsistencyLevel read, ConsistencyLevel write) { + super(trans, name, cluster,keyspace,dataClass); + this.table = table; + readConsistency = read; + writeConsistency = write; + } + + /** + * A Constructor to share Session with other DAOs. + * + * This method get the Session and Cluster information from the calling DAO, and won't + * touch the Session on closure. + * + * @param aDao + * @param dataClass + */ + public CassDAOImpl(TRANS trans, String name, AbsCassDAO aDao, Class dataClass, String table, ConsistencyLevel read, ConsistencyLevel write) { + super(trans, name, aDao,dataClass); + this.table = table; + readConsistency = read; + writeConsistency = write; + } - protected PSInfo createPS; - protected PSInfo readPS; - protected PSInfo updatePS; - protected PSInfo deletePS; - protected boolean async=false; + protected PSInfo createPS; + protected PSInfo readPS; + protected PSInfo updatePS; + protected PSInfo deletePS; + protected boolean async=false; - public void async(boolean bool) { - async = bool; - } + public void async(boolean bool) { + async = bool; + } - public final String[] setCRUD(TRANS trans, String table, Class dc,Loader loader) { - return setCRUD(trans, table, dc, loader, -1); - } - - public final String[] setCRUD(TRANS trans, String table, Class dc,Loader loader, int max) { - Field[] fields = dc.getDeclaredFields(); - int end = max>=0 & max0) { - for(int i=0;i0) { - sbfc.append(','); - sbq.append(','); - if(i=keylimit) { - if(i>keylimit) { - sbup.append(','); - } - sbup.append(fields[i].getName()); - sbup.append("=?"); - } - if(i dc,Loader loader) { + return setCRUD(trans, table, dc, loader, -1); + } + + public final String[] setCRUD(TRANS trans, String table, Class dc,Loader loader, int max) { + Field[] fields = dc.getDeclaredFields(); + int end = max>=0 & max0) { + for(int i=0;i0) { + sbfc.append(','); + sbq.append(','); + if(i=keylimit) { + if(i>keylimit) { + sbup.append(','); + } + sbup.append(fields[i].getName()); + sbup.append("=?"); + } + if(i create(TRANS trans, DATA data) { - if(createPS==null) { - return Result.err(Result.ERR_NotImplemented,"Create is disabled for %s",getClass().getSimpleName()); - } - if(async) /*ResultSetFuture */ { - Result rs = createPS.execAsync(trans, C_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - } else { - Result rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - } - wasModified(trans, CRUD.create, data); - return Result.ok(data); - } + + /** + * Given a DATA object, extract the individual elements from the Data into an Object Array for the + * execute element. + */ + public Result create(TRANS trans, DATA data) { + if(createPS==null) { + return Result.err(Result.ERR_NotImplemented,"Create is disabled for %s",getClass().getSimpleName()); + } + if(async) /*ResultSetFuture */ { + Result rs = createPS.execAsync(trans, C_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + } else { + Result rs = createPS.exec(trans, C_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + } + wasModified(trans, CRUD.create, data); + return Result.ok(data); + } - /** - * Read the Unique Row associated with Full Keys - */ - public Result> read(TRANS trans, DATA data) { - if(readPS==null) { - return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); - } - return readPS.read(trans, R_TEXT, data); - } + /** + * Read the Unique Row associated with Full Keys + */ + public Result> read(TRANS trans, DATA data) { + if(readPS==null) { + return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); + } + return readPS.read(trans, R_TEXT, data); + } - public Result> read(TRANS trans, Object ... key) { - if(readPS==null) { - return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); - } - return readPS.read(trans, R_TEXT, key); - } - - public Result readPrimKey(TRANS trans, Object ... key) { - if(readPS==null) { - return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); - } - Result> rld = readPS.read(trans, R_TEXT, key); - if(rld.isOK()) { - if(rld.isEmpty()) { - return Result.err(Result.ERR_NotFound,rld.details); - } else { - return Result.ok(rld.value.get(0)); - } - } else { - return Result.err(rld); - } - } + public Result> read(TRANS trans, Object ... key) { + if(readPS==null) { + return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); + } + return readPS.read(trans, R_TEXT, key); + } + + public Result readPrimKey(TRANS trans, Object ... key) { + if(readPS==null) { + return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); + } + Result> rld = readPS.read(trans, R_TEXT, key); + if(rld.isOK()) { + if(rld.isEmpty()) { + return Result.err(Result.ERR_NotFound,rld.details); + } else { + return Result.ok(rld.value.get(0)); + } + } else { + return Result.err(rld); + } + } - public Result update(TRANS trans, DATA data) { - return update(trans, data, async); - } + public Result update(TRANS trans, DATA data) { + return update(trans, data, async); + } - public Result update(TRANS trans, DATA data, boolean async) { - if(updatePS==null) { - return Result.err(Result.ERR_NotImplemented,"Update is disabled for %s",getClass().getSimpleName()); - } - if(async)/* ResultSet rs =*/ { - Result rs = updatePS.execAsync(trans, U_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - } else { - Result rs = updatePS.exec(trans, U_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - } - - wasModified(trans, CRUD.update, data); - return Result.ok(); - } + public Result update(TRANS trans, DATA data, boolean async) { + if(updatePS==null) { + return Result.err(Result.ERR_NotImplemented,"Update is disabled for %s",getClass().getSimpleName()); + } + if(async)/* ResultSet rs =*/ { + Result rs = updatePS.execAsync(trans, U_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + } else { + Result rs = updatePS.exec(trans, U_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + } + + wasModified(trans, CRUD.update, data); + return Result.ok(); + } - // This method Sig for Cached... - public Result delete(TRANS trans, DATA data, boolean reread) { - if(deletePS==null) { - return Result.err(Result.ERR_NotImplemented,"Delete is disabled for %s",getClass().getSimpleName()); - } - // Since Deleting will be stored off, for possible re-constitution, need the whole thing - if(reread) { - Result> rd = read(trans,data); - if(rd.notOK()) { - return Result.err(rd); - } - if(rd.isEmpty()) { - return Result.err(Status.ERR_NotFound,"Not Found"); - } - for(DATA d : rd.value) { - if(async) { - Result rs = deletePS.execAsync(trans, D_TEXT, d); - if(rs.notOK()) { - return Result.err(rs); - } - } else { - Result rs = deletePS.exec(trans, D_TEXT, d); - if(rs.notOK()) { - return Result.err(rs); - } - } - wasModified(trans, CRUD.delete, d); - } - } else { - if(async)/* ResultSet rs =*/ { - Result rs = deletePS.execAsync(trans, D_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - } else { - Result rs = deletePS.exec(trans, D_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - } - wasModified(trans, CRUD.delete, data); - } - return Result.ok(); - } - - public final Object[] keyFrom(DATA data) { - return createPS.keyFrom(data); - } + // This method Sig for Cached... + public Result delete(TRANS trans, DATA data, boolean reread) { + if(deletePS==null) { + return Result.err(Result.ERR_NotImplemented,"Delete is disabled for %s",getClass().getSimpleName()); + } + // Since Deleting will be stored off, for possible re-constitution, need the whole thing + if(reread) { + Result> rd = read(trans,data); + if(rd.notOK()) { + return Result.err(rd); + } + if(rd.isEmpty()) { + return Result.err(Status.ERR_NotFound,"Not Found"); + } + for(DATA d : rd.value) { + if(async) { + Result rs = deletePS.execAsync(trans, D_TEXT, d); + if(rs.notOK()) { + return Result.err(rs); + } + } else { + Result rs = deletePS.exec(trans, D_TEXT, d); + if(rs.notOK()) { + return Result.err(rs); + } + } + wasModified(trans, CRUD.delete, d); + } + } else { + if(async)/* ResultSet rs =*/ { + Result rs = deletePS.execAsync(trans, D_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + } else { + Result rs = deletePS.exec(trans, D_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + } + wasModified(trans, CRUD.delete, data); + } + return Result.ok(); + } + + public final Object[] keyFrom(DATA data) { + return createPS.keyFrom(data); + } - @Override - public String table() { - return table; - } - - public static final String CASS_READ_CONSISTENCY="cassandra.readConsistency"; - public static final String CASS_WRITE_CONSISTENCY="cassandra.writeConsistency"; - protected static ConsistencyLevel readConsistency(AuthzTrans trans, String table) { - String prop = trans.getProperty(CASS_READ_CONSISTENCY+'.'+table); - if(prop==null) { - prop = trans.getProperty(CASS_READ_CONSISTENCY); - if(prop==null) { - return ConsistencyLevel.ONE; // this is Cassandra Default - } - } - return ConsistencyLevel.valueOf(prop); - } + @Override + public String table() { + return table; + } + + public static final String CASS_READ_CONSISTENCY="cassandra.readConsistency"; + public static final String CASS_WRITE_CONSISTENCY="cassandra.writeConsistency"; + protected static ConsistencyLevel readConsistency(AuthzTrans trans, String table) { + String prop = trans.getProperty(CASS_READ_CONSISTENCY+'.'+table); + if(prop==null) { + prop = trans.getProperty(CASS_READ_CONSISTENCY); + if(prop==null) { + return ConsistencyLevel.ONE; // this is Cassandra Default + } + } + return ConsistencyLevel.valueOf(prop); + } - protected static ConsistencyLevel writeConsistency(AuthzTrans trans, String table) { - String prop = trans.getProperty(CASS_WRITE_CONSISTENCY+'.'+table); - if(prop==null) { - prop = trans.getProperty(CASS_WRITE_CONSISTENCY); - if(prop==null) { - return ConsistencyLevel.ONE; // this is Cassandra Default\ - } - } - return ConsistencyLevel.valueOf(prop); - } + protected static ConsistencyLevel writeConsistency(AuthzTrans trans, String table) { + String prop = trans.getProperty(CASS_WRITE_CONSISTENCY+'.'+table); + if(prop==null) { + prop = trans.getProperty(CASS_WRITE_CONSISTENCY); + if(prop==null) { + return ConsistencyLevel.ONE; // this is Cassandra Default\ + } + } + return ConsistencyLevel.valueOf(prop); + } - public static DataInputStream toDIS(ByteBuffer bb) { - byte[] b = bb.array(); - return new DataInputStream( - new ByteArrayInputStream(b,bb.position(),bb.limit()) - ); - } + public static DataInputStream toDIS(ByteBuffer bb) { + byte[] b = bb.array(); + return new DataInputStream( + new ByteArrayInputStream(b,bb.position(),bb.limit()) + ); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO.java index 70db430e..38759075 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO.java @@ -35,10 +35,10 @@ import org.onap.aaf.misc.env.Trans; * @param */ public interface DAO extends DAO_RO { - public Result create(TRANS trans, DATA data); - public Result update(TRANS trans, DATA data); - // In many cases, the data has been correctly read first, so we shouldn't read again - // Use reread=true if you are using DATA with only a Key - public Result delete(TRANS trans, DATA data, boolean reread); - public Object[] keyFrom(DATA data); + public Result create(TRANS trans, DATA data); + public Result update(TRANS trans, DATA data); + // In many cases, the data has been correctly read first, so we shouldn't read again + // Use reread=true if you are using DATA with only a Key + public Result delete(TRANS trans, DATA data, boolean reread); + public Object[] keyFrom(DATA data); } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAOException.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAOException.java index 207576e4..b6c35f20 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAOException.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAOException.java @@ -23,10 +23,10 @@ package org.onap.aaf.auth.dao; public class DAOException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1527904125585539823L; + /** + * + */ + private static final long serialVersionUID = 1527904125585539823L; // // TODO - enum in result class == is our intended design, currently the DAO layer does not use Result so we still use these for now // public final static DAOException RoleNotFoundDAOException = new DAOException("RoleNotFound"); @@ -34,18 +34,18 @@ public class DAOException extends Exception { // public final static DAOException UserNotFoundDAOException = new DAOException("UserNotFound"); public DAOException() { - } + } - public DAOException(String message) { - super(message); - } + public DAOException(String message) { + super(message); + } - public DAOException(Throwable cause) { - super(cause); - } + public DAOException(Throwable cause) { + super(cause); + } - public DAOException(String message, Throwable cause) { - super(message, cause); - } + public DAOException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO_RO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO_RO.java index 4bffb5f3..ca4277e1 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO_RO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/DAO_RO.java @@ -38,33 +38,33 @@ import org.onap.aaf.misc.env.Trans; * @param */ public interface DAO_RO { - /** - * Get a List of Data given Key of Object Array - * @param objs - * @return - * @throws DAOException - */ - public Result> read(TRANS trans, Object ... key); + /** + * Get a List of Data given Key of Object Array + * @param objs + * @return + * @throws DAOException + */ + public Result> read(TRANS trans, Object ... key); - /** - * Get a List of Data given Key of DATA Object - * @param trans - * @param key - * @return - * @throws DAOException - */ - public Result> read(TRANS trans, DATA key); + /** + * Get a List of Data given Key of DATA Object + * @param trans + * @param key + * @return + * @throws DAOException + */ + public Result> read(TRANS trans, DATA key); - /** - * close DAO - */ - public void close(TRANS trans); + /** + * close DAO + */ + public void close(TRANS trans); - /** - * Return name of referenced Data - * @return - */ - public String table(); + /** + * Return name of referenced Data + * @return + */ + public String table(); } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java index 00423161..cdfd0697 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java @@ -36,179 +36,179 @@ import java.util.Set; import com.datastax.driver.core.Row; public abstract class Loader { - private int keylimit; - public Loader(int keylimit) { - this.keylimit = keylimit; - } - - public int keylimit() { - return keylimit; - } - - protected abstract DATA load(DATA data, Row row); - protected abstract void key(DATA data, int idx, Object[] obj); - protected abstract void body(DATA data, int idx, Object[] obj); + private int keylimit; + public Loader(int keylimit) { + this.keylimit = keylimit; + } + + public int keylimit() { + return keylimit; + } + + protected abstract DATA load(DATA data, Row row); + protected abstract void key(DATA data, int idx, Object[] obj); + protected abstract void body(DATA data, int idx, Object[] obj); - public final Object[] extract(DATA data, int size, CassDAOImpl.CRUD type) { - Object[] rv=null; - switch(type) { - case delete: - rv = new Object[keylimit()]; - key(data,0,rv); - break; - case update: - rv = new Object[size]; - body(data,0,rv); - int body = size-keylimit(); - if(body>0) { - key(data,body,rv); - } - break; - default: - rv = new Object[size]; - key(data,0,rv); - if(size>keylimit()) { - body(data,keylimit(),rv); - } - break; - } - return rv; - } - - public static void writeString(DataOutputStream os, String s) throws IOException { - if(s==null) { - os.writeInt(-1); - } else { - switch(s.length()) { - case 0: - os.writeInt(0); - break; - default: - byte[] bytes = s.getBytes(); - os.writeInt(bytes.length); - os.write(bytes); - } - } - } - - - /** - * We use bytes here to set a Maximum - * - * @param is - * @param MAX - * @return - * @throws IOException - */ - public static String readString(DataInputStream is, byte[] _buff) throws IOException { - int l = is.readInt(); - byte[] buff = _buff; - switch(l) { - case -1: return null; - case 0: return ""; - default: - // Cover case where there is a large string, without always allocating a large buffer. - if(l>buff.length) { - buff = new byte[l]; - } - is.read(buff,0,l); - return new String(buff,0,l); - } - } + public final Object[] extract(DATA data, int size, CassDAOImpl.CRUD type) { + Object[] rv=null; + switch(type) { + case delete: + rv = new Object[keylimit()]; + key(data,0,rv); + break; + case update: + rv = new Object[size]; + body(data,0,rv); + int body = size-keylimit(); + if(body>0) { + key(data,body,rv); + } + break; + default: + rv = new Object[size]; + key(data,0,rv); + if(size>keylimit()) { + body(data,keylimit(),rv); + } + break; + } + return rv; + } + + public static void writeString(DataOutputStream os, String s) throws IOException { + if(s==null) { + os.writeInt(-1); + } else { + switch(s.length()) { + case 0: + os.writeInt(0); + break; + default: + byte[] bytes = s.getBytes(); + os.writeInt(bytes.length); + os.write(bytes); + } + } + } + + + /** + * We use bytes here to set a Maximum + * + * @param is + * @param MAX + * @return + * @throws IOException + */ + public static String readString(DataInputStream is, byte[] _buff) throws IOException { + int l = is.readInt(); + byte[] buff = _buff; + switch(l) { + case -1: return null; + case 0: return ""; + default: + // Cover case where there is a large string, without always allocating a large buffer. + if(l>buff.length) { + buff = new byte[l]; + } + is.read(buff,0,l); + return new String(buff,0,l); + } + } - /** - * Write a set with proper sizing - * - * Note: at the moment, this is just String. Probably can develop system where types - * are supported too... but not now. - * - * @param os - * @param set - * @throws IOException - */ - public static void writeStringSet(DataOutputStream os, Collection set) throws IOException { - if(set==null) { - os.writeInt(-1); - } else { - os.writeInt(set.size()); - for(String s : set) { - writeString(os, s); - } - } + /** + * Write a set with proper sizing + * + * Note: at the moment, this is just String. Probably can develop system where types + * are supported too... but not now. + * + * @param os + * @param set + * @throws IOException + */ + public static void writeStringSet(DataOutputStream os, Collection set) throws IOException { + if(set==null) { + os.writeInt(-1); + } else { + os.writeInt(set.size()); + for(String s : set) { + writeString(os, s); + } + } - } - - public static Set readStringSet(DataInputStream is, byte[] buff) throws IOException { - int l = is.readInt(); - if(l<0) { - return null; - } - Set set = new HashSet<>(l); - for(int i=0;i readStringList(DataInputStream is, byte[] buff) throws IOException { - int l = is.readInt(); - if(l<0) { - return null; - } - List list = new ArrayList<>(l); - for(int i=0;i readStringSet(DataInputStream is, byte[] buff) throws IOException { + int l = is.readInt(); + if(l<0) { + return null; + } + Set set = new HashSet<>(l); + for(int i=0;i readStringList(DataInputStream is, byte[] buff) throws IOException { + int l = is.readInt(); + if(l<0) { + return null; + } + List list = new ArrayList<>(l); + for(int i=0;i map) throws IOException { - if(map==null) { - os.writeInt(-1); - } else { - Set> es = map.entrySet(); - os.writeInt(es.size()); - for(Entry e : es) { - writeString(os, e.getKey()); - writeString(os, e.getValue()); - } - } + /** + * Write a map + * @param os + * @param map + * @throws IOException + */ + public static void writeStringMap(DataOutputStream os, Map map) throws IOException { + if(map==null) { + os.writeInt(-1); + } else { + Set> es = map.entrySet(); + os.writeInt(es.size()); + for(Entry e : es) { + writeString(os, e.getKey()); + writeString(os, e.getValue()); + } + } - } + } - public static Map readStringMap(DataInputStream is, byte[] buff) throws IOException { - int l = is.readInt(); - if(l<0) { - return null; - } - Map map = new HashMap<>(l); - for(int i=0;iversion) { - throw new IOException("Unsupported Data Version: " + v); - } - return v; - } + public static Map readStringMap(DataInputStream is, byte[] buff) throws IOException { + int l = is.readInt(); + if(l<0) { + return null; + } + Map map = new HashMap<>(l); + for(int i=0;iversion) { + throw new IOException("Unsupported Data Version: " + v); + } + return v; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Streamer.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Streamer.java index c40d74fa..af3567eb 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Streamer.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Streamer.java @@ -26,6 +26,6 @@ import java.io.DataOutputStream; import java.io.IOException; public interface Streamer { - public abstract void marshal(DATA data, DataOutputStream os) throws IOException; - public abstract void unmarshal(DATA data, DataInputStream is) throws IOException; + public abstract void marshal(DATA data, DataOutputStream os) throws IOException; + public abstract void unmarshal(DATA data, DataInputStream is) throws IOException; } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Touchable.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Touchable.java index c00c1048..0fcda19c 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Touchable.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Touchable.java @@ -22,5 +22,5 @@ package org.onap.aaf.auth.dao; public interface Touchable { - // Or make all DAOs accept list of CIDAOs... + // Or make all DAOs accept list of CIDAOs... } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCertDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCertDAO.java index 9526bf28..c0a2c49c 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCertDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCertDAO.java @@ -30,25 +30,25 @@ import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.layer.Result; public class CachedCertDAO extends CachedDAO { - public CachedCertDAO(CertDAO dao, CIDAO info, long expiresIn) { - super(dao, info, CertDAO.CACHE_SEG, expiresIn); - } - - /** - * Pass through Cert ID Lookup - * - * @param trans - * @param ns - * @return - */ - - public Result> readID(AuthzTrans trans, final String id) { - return dao().readID(trans, id); - } - - public Result> readX500(AuthzTrans trans, final String x500) { - return dao().readX500(trans, x500); - } + public CachedCertDAO(CertDAO dao, CIDAO info, long expiresIn) { + super(dao, info, CertDAO.CACHE_SEG, expiresIn); + } + + /** + * Pass through Cert ID Lookup + * + * @param trans + * @param ns + * @return + */ + + public Result> readID(AuthzTrans trans, final String id) { + return dao().readID(trans, id); + } + + public Result> readX500(AuthzTrans trans, final String x500) { + return dao().readX500(trans, x500); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java index 76fd5530..eb5885f0 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java @@ -31,36 +31,36 @@ import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.layer.Result; public class CachedCredDAO extends CachedDAO { - public CachedCredDAO(CredDAO dao, CIDAO info, long expiresIn) { - super(dao, info, CredDAO.CACHE_SEG, expiresIn); - } - - /** - * Pass through Cred Lookup - * - * Unlike Role and Perm, we don't need or want to cache these elements... Only used for NS Delete. - * - * @param trans - * @param ns - * @return - */ - public Result> readNS(AuthzTrans trans, final String ns) { - - return dao().readNS(trans, ns); - } - - public Result> readID(AuthzTrans trans, final String id) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - return dao().readID(trans, id); - } - }; - - Result> lurd = get(trans, id, getter); - if(lurd.isOK() && lurd.isEmpty()) { - return Result.err(Status.ERR_UserNotFound,"No User Cred found"); - } - return lurd; - } + public CachedCredDAO(CredDAO dao, CIDAO info, long expiresIn) { + super(dao, info, CredDAO.CACHE_SEG, expiresIn); + } + + /** + * Pass through Cred Lookup + * + * Unlike Role and Perm, we don't need or want to cache these elements... Only used for NS Delete. + * + * @param trans + * @param ns + * @return + */ + public Result> readNS(AuthzTrans trans, final String ns) { + + return dao().readNS(trans, ns); + } + + public Result> readID(AuthzTrans trans, final String id) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + return dao().readID(trans, id); + } + }; + + Result> lurd = get(trans, id, getter); + if(lurd.isOK() && lurd.isEmpty()) { + return Result.err(Status.ERR_UserNotFound,"No User Cred found"); + } + return lurd; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedNSDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedNSDAO.java index be860488..e639767c 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedNSDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedNSDAO.java @@ -27,7 +27,7 @@ import org.onap.aaf.auth.dao.cass.NsDAO; import org.onap.aaf.auth.env.AuthzTrans; public class CachedNSDAO extends CachedDAO { - public CachedNSDAO(NsDAO dao, CIDAO info, long expiresIn) { - super(dao, info, NsDAO.CACHE_SEG, expiresIn); - } + public CachedNSDAO(NsDAO dao, CIDAO info, long expiresIn) { + super(dao, info, NsDAO.CACHE_SEG, expiresIn); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java index 4cb7cf2e..a18e6a67 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java @@ -34,91 +34,91 @@ import org.onap.aaf.auth.layer.Result; public class CachedPermDAO extends CachedDAO { - public CachedPermDAO(PermDAO dao, CIDAO info, long expiresIn) { - super(dao, info, PermDAO.CACHE_SEG, expiresIn); - } + public CachedPermDAO(PermDAO dao, CIDAO info, long expiresIn) { + super(dao, info, PermDAO.CACHE_SEG, expiresIn); + } - public Result> readNS(AuthzTrans trans, final String ns) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - return dao.readNS(trans, ns); - } - }; - - Result> lurd = get(trans, ns, getter); - if(lurd.isOKhasData()) { - return lurd; - } else { - - } -// if(getter.result==null) { -// if(lurd==null) { - return Result.err(Status.ERR_PermissionNotFound,"No Permission found - " + lurd.details); -// } else { -// return Result.ok(lurd); -// } -// } -// return getter.result; - } + public Result> readNS(AuthzTrans trans, final String ns) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + return dao.readNS(trans, ns); + } + }; + + Result> lurd = get(trans, ns, getter); + if(lurd.isOKhasData()) { + return lurd; + } else { + + } +// if(getter.result==null) { +// if(lurd==null) { + return Result.err(Status.ERR_PermissionNotFound,"No Permission found - " + lurd.details); +// } else { +// return Result.ok(lurd); +// } +// } +// return getter.result; + } - public Result> readChildren(AuthzTrans trans, final String ns, final String type) { - return dao().readChildren(trans,ns,type); - } + public Result> readChildren(AuthzTrans trans, final String ns, final String type) { + return dao().readChildren(trans,ns,type); + } - /** - * - * @param trans - * @param ns - * @param type - * @return - */ - public Result> readByType(AuthzTrans trans, final String ns, final String type) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - return dao.readByType(trans, ns, type); - } - }; - - // Note: Can reuse index1 here, because there is no name collision versus response - Result> lurd = get(trans, ns+'|'+type, getter); - if(lurd.isOK() && lurd.isEmpty()) { - return Result.err(Status.ERR_PermissionNotFound,"No Permission found"); - } - return lurd; - } - - /** - * Add desciption to this permission - * - * @param trans - * @param ns - * @param type - * @param instance - * @param action - * @param description - * @return - */ - public Result addDescription(AuthzTrans trans, String ns, String type, - String instance, String action, String description) { - //TODO Invalidate? - return dao().addDescription(trans, ns, type, instance, action, description); - } - - public Result addRole(AuthzTrans trans, PermDAO.Data perm, RoleDAO.Data role) { - Result rv = dao().addRole(trans,perm,role.encode()); - if(trans.debug().isLoggable()) - trans.debug().log("Adding",role.encode(),"to", perm, "with CachedPermDAO.addRole"); - invalidate(trans,perm); - return rv; - } + /** + * + * @param trans + * @param ns + * @param type + * @return + */ + public Result> readByType(AuthzTrans trans, final String ns, final String type) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + return dao.readByType(trans, ns, type); + } + }; + + // Note: Can reuse index1 here, because there is no name collision versus response + Result> lurd = get(trans, ns+'|'+type, getter); + if(lurd.isOK() && lurd.isEmpty()) { + return Result.err(Status.ERR_PermissionNotFound,"No Permission found"); + } + return lurd; + } + + /** + * Add desciption to this permission + * + * @param trans + * @param ns + * @param type + * @param instance + * @param action + * @param description + * @return + */ + public Result addDescription(AuthzTrans trans, String ns, String type, + String instance, String action, String description) { + //TODO Invalidate? + return dao().addDescription(trans, ns, type, instance, action, description); + } + + public Result addRole(AuthzTrans trans, PermDAO.Data perm, RoleDAO.Data role) { + Result rv = dao().addRole(trans,perm,role.encode()); + if(trans.debug().isLoggable()) + trans.debug().log("Adding",role.encode(),"to", perm, "with CachedPermDAO.addRole"); + invalidate(trans,perm); + return rv; + } - public Result delRole(AuthzTrans trans, Data perm, RoleDAO.Data role) { - Result rv = dao().delRole(trans,perm,role.encode()); - if(trans.debug().isLoggable()) - trans.debug().log("Removing",role.encode(),"from", perm, "with CachedPermDAO.delRole"); - invalidate(trans,perm); - return rv; - } + public Result delRole(AuthzTrans trans, Data perm, RoleDAO.Data role) { + Result rv = dao().delRole(trans,perm,role.encode()); + if(trans.debug().isLoggable()) + trans.debug().log("Removing",role.encode(),"from", perm, "with CachedPermDAO.delRole"); + invalidate(trans,perm); + return rv; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java index 5fac680c..1d8e6709 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java @@ -33,74 +33,74 @@ import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.layer.Result; public class CachedRoleDAO extends CachedDAO { - public CachedRoleDAO(RoleDAO dao, CIDAO info, long expiresIn) { - super(dao, info, RoleDAO.CACHE_SEG, expiresIn); - } + public CachedRoleDAO(RoleDAO dao, CIDAO info, long expiresIn) { + super(dao, info, RoleDAO.CACHE_SEG, expiresIn); + } - public Result> readNS(AuthzTrans trans, final String ns) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - return dao.readNS(trans, ns); - } - }; - - Result> lurd = get(trans, ns, getter); - if(lurd.isOK() && lurd.isEmpty()) { - return Result.err(Status.ERR_RoleNotFound,"No Role found"); - } - return lurd; - } + public Result> readNS(AuthzTrans trans, final String ns) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + return dao.readNS(trans, ns); + } + }; + + Result> lurd = get(trans, ns, getter); + if(lurd.isOK() && lurd.isEmpty()) { + return Result.err(Status.ERR_RoleNotFound,"No Role found"); + } + return lurd; + } - public Result> readName(AuthzTrans trans, final String name) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - return dao().readName(trans, name); - } - }; - - Result> lurd = get(trans, name, getter); - if(lurd.isOK() && lurd.isEmpty()) { - return Result.err(Status.ERR_RoleNotFound,"No Role found"); - } - return lurd; - } + public Result> readName(AuthzTrans trans, final String name) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + return dao().readName(trans, name); + } + }; + + Result> lurd = get(trans, name, getter); + if(lurd.isOK() && lurd.isEmpty()) { + return Result.err(Status.ERR_RoleNotFound,"No Role found"); + } + return lurd; + } - public Result> readChildren(AuthzTrans trans, final String ns, final String name) { - // At this point, I'm thinking it's better not to try to cache "*" results - // Data probably won't be accurate, and adding it makes every update invalidate most of the cache - // Jonathan 2/4/2014 - return dao().readChildren(trans,ns,name); - } + public Result> readChildren(AuthzTrans trans, final String ns, final String name) { + // At this point, I'm thinking it's better not to try to cache "*" results + // Data probably won't be accurate, and adding it makes every update invalidate most of the cache + // Jonathan 2/4/2014 + return dao().readChildren(trans,ns,name); + } - public Result addPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { - Result rv = dao().addPerm(trans,rd,perm); - if(trans.debug().isLoggable()) - trans.debug().log("Adding",perm,"to", rd, "with CachedRoleDAO.addPerm"); - invalidate(trans, rd); - return rv; - } + public Result addPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { + Result rv = dao().addPerm(trans,rd,perm); + if(trans.debug().isLoggable()) + trans.debug().log("Adding",perm,"to", rd, "with CachedRoleDAO.addPerm"); + invalidate(trans, rd); + return rv; + } - public Result delPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { - Result rv = dao().delPerm(trans,rd,perm); - if(trans.debug().isLoggable()) - trans.debug().log("Removing",perm,"from", rd, "with CachedRoleDAO.addPerm"); - invalidate(trans, rd); - return rv; - } - - /** - * Add description to this role - * - * @param trans - * @param ns - * @param name - * @param description - * @return - */ - public Result addDescription(AuthzTrans trans, String ns, String name, String description) { - //TODO Invalidate? - return dao().addDescription(trans, ns, name, description); + public Result delPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { + Result rv = dao().delPerm(trans,rd,perm); + if(trans.debug().isLoggable()) + trans.debug().log("Removing",perm,"from", rd, "with CachedRoleDAO.addPerm"); + invalidate(trans, rd); + return rv; + } + + /** + * Add description to this role + * + * @param trans + * @param ns + * @param name + * @param description + * @return + */ + public Result addDescription(AuthzTrans trans, String ns, String name, String description) { + //TODO Invalidate? + return dao().addDescription(trans, ns, name, description); - } + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java index 100c81d5..2121b136 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java @@ -34,82 +34,82 @@ import org.onap.aaf.auth.layer.Result; import org.onap.aaf.misc.env.Slot; public class CachedUserRoleDAO extends CachedDAO { - private Slot transURSlot; + private Slot transURSlot; - public CachedUserRoleDAO(UserRoleDAO dao, CIDAO info, long expiresIn) { - super(dao, info, UserRoleDAO.CACHE_SEG, expiresIn); - transURSlot = dao.transURSlot; - } + public CachedUserRoleDAO(UserRoleDAO dao, CIDAO info, long expiresIn) { + super(dao, info, UserRoleDAO.CACHE_SEG, expiresIn); + transURSlot = dao.transURSlot; + } - /** - * Special Case. - * User Roles by User are very likely to be called many times in a Transaction, to validate "May User do..." - * Pull result, and make accessible by the Trans, which is always keyed by User. - * @param trans - * @param user - * @return - */ - public Result> readByUser(AuthzTrans trans, final String user) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - // If the call is for THIS user, and it exists, get from TRANS, add to TRANS if not. - if(user!=null && user.equals(trans.user())) { - Result> transLD = trans.get(transURSlot,null); - if(transLD==null ) { - transLD = dao.readByUser(trans, user); - } - return transLD; - } else { - return dao.readByUser(trans, user); - } - } - }; - Result> lurd = get(trans, user, getter); - if(lurd.isOK() && lurd.isEmpty()) { - return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",user); - } - return lurd; - } + /** + * Special Case. + * User Roles by User are very likely to be called many times in a Transaction, to validate "May User do..." + * Pull result, and make accessible by the Trans, which is always keyed by User. + * @param trans + * @param user + * @return + */ + public Result> readByUser(AuthzTrans trans, final String user) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + // If the call is for THIS user, and it exists, get from TRANS, add to TRANS if not. + if(user!=null && user.equals(trans.user())) { + Result> transLD = trans.get(transURSlot,null); + if(transLD==null ) { + transLD = dao.readByUser(trans, user); + } + return transLD; + } else { + return dao.readByUser(trans, user); + } + } + }; + Result> lurd = get(trans, user, getter); + if(lurd.isOK() && lurd.isEmpty()) { + return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",user); + } + return lurd; + } - - public Result> readByRole(AuthzTrans trans, final String role) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - return dao.readByRole(trans, role); - } - }; - Result> lurd = get(trans, role, getter); - if(lurd.isOK() && lurd.isEmpty()) { - return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",role); - } - return lurd; - } + + public Result> readByRole(AuthzTrans trans, final String role) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + return dao.readByRole(trans, role); + } + }; + Result> lurd = get(trans, role, getter); + if(lurd.isOK() && lurd.isEmpty()) { + return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",role); + } + return lurd; + } - public Result> readUserInRole(final AuthzTrans trans, final String user, final String role) { - DAOGetter getter = new DAOGetter(trans,dao()) { - public Result> call() { - if(user.equals(trans.user())) { - Result> rrbu = readByUser(trans, user); - if(rrbu.isOK()) { - List ld = new ArrayList<>(1); - for(Data d : rrbu.value) { - if(d.role.equals(role)) { - ld.add(d); - break; - } - } - return Result.ok(ld).emptyList(ld.isEmpty()); - } else { - return rrbu; - } - } - return dao.readByUserRole(trans, user, role); - } - }; - Result> lurd = get(trans, keyFromObjs(user,role), getter); - if(lurd.isOK() && lurd.isEmpty()) { - return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for role [%s] and user [%s]",role,user); - } - return lurd; - } + public Result> readUserInRole(final AuthzTrans trans, final String user, final String role) { + DAOGetter getter = new DAOGetter(trans,dao()) { + public Result> call() { + if(user.equals(trans.user())) { + Result> rrbu = readByUser(trans, user); + if(rrbu.isOK()) { + List ld = new ArrayList<>(1); + for(Data d : rrbu.value) { + if(d.role.equals(role)) { + ld.add(d); + break; + } + } + return Result.ok(ld).emptyList(ld.isEmpty()); + } else { + return rrbu; + } + } + return dao.readByUserRole(trans, user, role); + } + }; + Result> lurd = get(trans, keyFromObjs(user,role), getter); + if(lurd.isOK() && lurd.isEmpty()) { + return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for role [%s] and user [%s]",role,user); + } + return lurd; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java index 284d0a84..1948ac65 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java @@ -43,212 +43,212 @@ import com.datastax.driver.core.exceptions.DriverException; public class ApprovalDAO extends CassDAOImpl { - public static final String PENDING = "pending"; - public static final String DENIED = "denied"; - public static final String APPROVED = "approved"; - - private static final String TABLE = "approval"; - private static final String TABLELOG = "approved"; - private HistoryDAO historyDAO; - private PSInfo psByUser, psByApprover, psByTicket, psByStatus; + public static final String PENDING = "pending"; + public static final String DENIED = "denied"; + public static final String APPROVED = "approved"; + + private static final String TABLE = "approval"; + private static final String TABLELOG = "approved"; + private HistoryDAO historyDAO; + private PSInfo psByUser, psByApprover, psByTicket, psByStatus; - - public ApprovalDAO(AuthzTrans trans, Cluster cluster, String keyspace) { - super(trans, ApprovalDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + + public ApprovalDAO(AuthzTrans trans, Cluster cluster, String keyspace) { + super(trans, ApprovalDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); historyDAO = new HistoryDAO(trans, this); - init(trans); - } + init(trans); + } - public ApprovalDAO(AuthzTrans trans, HistoryDAO hDAO) { - super(trans, ApprovalDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - historyDAO=hDAO; - init(trans); - } + public ApprovalDAO(AuthzTrans trans, HistoryDAO hDAO) { + super(trans, ApprovalDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + historyDAO=hDAO; + init(trans); + } - private static final int KEYLIMIT = 1; - public static class Data { - public UUID id; + private static final int KEYLIMIT = 1; + public static class Data { + public UUID id; public UUID ticket; - public String user; - public String approver; - public String type; - public String status; - public String memo; - public String operation; - public Date last_notified; - public Date updated; - } - - private static class ApprovalLoader extends Loader { - public static final ApprovalLoader deflt = new ApprovalLoader(KEYLIMIT); - - public ApprovalLoader(int keylimit) { - super(keylimit); - } - - @Override - public Data load(Data data, Row row) { - data.id = row.getUUID(0); - data.ticket = row.getUUID(1); - data.user = row.getString(2); - data.approver = row.getString(3); - data.type = row.getString(4); - data.status = row.getString(5); - data.memo = row.getString(6); - data.operation = row.getString(7); - data.last_notified = row.getTimestamp(8); - // This is used to get "WRITETIME(STATUS)" from Approval, which gives us an "updated" - if(row.getColumnDefinitions().size()>9) { - // Rows reported in MicroSeconds - data.updated = new Date(row.getLong(9)/1000); - } - return data; - } + public String user; + public String approver; + public String type; + public String status; + public String memo; + public String operation; + public Date last_notified; + public Date updated; + } + + private static class ApprovalLoader extends Loader { + public static final ApprovalLoader deflt = new ApprovalLoader(KEYLIMIT); + + public ApprovalLoader(int keylimit) { + super(keylimit); + } + + @Override + public Data load(Data data, Row row) { + data.id = row.getUUID(0); + data.ticket = row.getUUID(1); + data.user = row.getString(2); + data.approver = row.getString(3); + data.type = row.getString(4); + data.status = row.getString(5); + data.memo = row.getString(6); + data.operation = row.getString(7); + data.last_notified = row.getTimestamp(8); + // This is used to get "WRITETIME(STATUS)" from Approval, which gives us an "updated" + if(row.getColumnDefinitions().size()>9) { + // Rows reported in MicroSeconds + data.updated = new Date(row.getLong(9)/1000); + } + return data; + } - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.id; - } + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.id; + } - @Override - protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.ticket; - obj[++idx]=data.user; - obj[++idx]=data.approver; - obj[++idx]=data.type; - obj[++idx]=data.status; - obj[++idx]=data.memo; - obj[++idx]=data.operation; - obj[++idx]=data.last_notified; - } - } - - private void init(AuthzTrans trans) { - String[] helpers = setCRUD(trans, TABLE, Data.class, ApprovalLoader.deflt,9); - psByUser = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + - " WHERE user = ?", new ApprovalLoader(1) { - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.user; - } - }, readConsistency); - - psByApprover = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + - " WHERE approver = ?", new ApprovalLoader(1) { - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.approver; - } - }, readConsistency); + @Override + protected void body(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.ticket; + obj[++idx]=data.user; + obj[++idx]=data.approver; + obj[++idx]=data.type; + obj[++idx]=data.status; + obj[++idx]=data.memo; + obj[++idx]=data.operation; + obj[++idx]=data.last_notified; + } + } + + private void init(AuthzTrans trans) { + String[] helpers = setCRUD(trans, TABLE, Data.class, ApprovalLoader.deflt,9); + psByUser = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + + " WHERE user = ?", new ApprovalLoader(1) { + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.user; + } + }, readConsistency); + + psByApprover = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + + " WHERE approver = ?", new ApprovalLoader(1) { + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.approver; + } + }, readConsistency); - psByTicket = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + - " WHERE ticket = ?", new ApprovalLoader(1) { - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.ticket; - } - }, readConsistency); + psByTicket = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + + " WHERE ticket = ?", new ApprovalLoader(1) { + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.ticket; + } + }, readConsistency); - psByStatus = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + - " WHERE status = ?", new ApprovalLoader(1) { - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.status; - } - }, readConsistency); + psByStatus = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + ", WRITETIME(status) FROM " + TABLE + + " WHERE status = ?", new ApprovalLoader(1) { + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.status; + } + }, readConsistency); - } + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.CassDAOImpl#create(com.att.inno.env.TransStore, java.lang.Object) - */ - @Override - public Result create(AuthzTrans trans, Data data) { - // If ID is not set (typical), create one. - if(data.id==null) { - data.id = Chrono.dateToUUID(System.currentTimeMillis()); - } - Result rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - return Result.ok(data); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.dao.CassDAOImpl#create(com.att.inno.env.TransStore, java.lang.Object) + */ + @Override + public Result create(AuthzTrans trans, Data data) { + // If ID is not set (typical), create one. + if(data.id==null) { + data.id = Chrono.dateToUUID(System.currentTimeMillis()); + } + Result rs = createPS.exec(trans, C_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + return Result.ok(data); + } - public Result> readByUser(AuthzTrans trans, String user) { - return psByUser.read(trans, R_TEXT, new Object[]{user}); - } + public Result> readByUser(AuthzTrans trans, String user) { + return psByUser.read(trans, R_TEXT, new Object[]{user}); + } - public Result> readByApprover(AuthzTrans trans, String approver) { - return psByApprover.read(trans, R_TEXT, new Object[]{approver}); - } + public Result> readByApprover(AuthzTrans trans, String approver) { + return psByApprover.read(trans, R_TEXT, new Object[]{approver}); + } - public Result> readByTicket(AuthzTrans trans, UUID ticket) { - return psByTicket.read(trans, R_TEXT, new Object[]{ticket}); - } + public Result> readByTicket(AuthzTrans trans, UUID ticket) { + return psByTicket.read(trans, R_TEXT, new Object[]{ticket}); + } - public Result> readByStatus(AuthzTrans trans, String status) { - return psByStatus.read(trans, R_TEXT, new Object[]{status}); - } + public Result> readByStatus(AuthzTrans trans, String status) { + return psByStatus.read(trans, R_TEXT, new Object[]{status}); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.CassDAOImpl#delete(com.att.inno.env.TransStore, java.lang.Object, boolean) - */ - @Override - public Result delete(AuthzTrans trans, Data data, boolean reread) { - if(reread || data.status == null) { // if Memo is empty, likely not full record - Result rd = readPS.exec(trans, R_TEXT, data); - if(rd.notOK()) { - return Result.err(rd); - } - ApprovalLoader.deflt.load(data, rd.value.one()); - } - if("approved".equals(data.status) || "denied".equals(data.status)) { - StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); - sb.append("INSERT INTO "); - sb.append(TABLELOG); - sb.append(" (id,user,approver,type,status,memo,operation) VALUES ("); - sb.append(data.id); - sb.append(",'"); sb.append(data.user); - sb.append("','"); sb.append(data.approver); - sb.append("','"); sb.append(data.type); - sb.append("','"); sb.append(data.status); - sb.append("','"); sb.append(data.memo.replace("'", "''")); - sb.append("','"); sb.append(data.operation); - sb.append("');\n"); - sb.append("DELETE FROM "); - sb.append(TABLE); - sb.append(" WHERE id="); - sb.append(data.id); - sb.append(";\n"); - sb.append("APPLY BATCH;\n"); - TimeTaken tt = trans.start("DELETE APPROVAL",Env.REMOTE); - try { - if(async) { - getSession(trans).executeAsync(sb.toString()); - return Result.ok(); - } else { - getSession(trans).execute(sb.toString()); - return Result.ok(); - } - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } finally { - tt.done(); - } - } else { - return super.delete(trans, data, false); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.dao.CassDAOImpl#delete(com.att.inno.env.TransStore, java.lang.Object, boolean) + */ + @Override + public Result delete(AuthzTrans trans, Data data, boolean reread) { + if(reread || data.status == null) { // if Memo is empty, likely not full record + Result rd = readPS.exec(trans, R_TEXT, data); + if(rd.notOK()) { + return Result.err(rd); + } + ApprovalLoader.deflt.load(data, rd.value.one()); + } + if("approved".equals(data.status) || "denied".equals(data.status)) { + StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); + sb.append("INSERT INTO "); + sb.append(TABLELOG); + sb.append(" (id,user,approver,type,status,memo,operation) VALUES ("); + sb.append(data.id); + sb.append(",'"); sb.append(data.user); + sb.append("','"); sb.append(data.approver); + sb.append("','"); sb.append(data.type); + sb.append("','"); sb.append(data.status); + sb.append("','"); sb.append(data.memo.replace("'", "''")); + sb.append("','"); sb.append(data.operation); + sb.append("');\n"); + sb.append("DELETE FROM "); + sb.append(TABLE); + sb.append(" WHERE id="); + sb.append(data.id); + sb.append(";\n"); + sb.append("APPLY BATCH;\n"); + TimeTaken tt = trans.start("DELETE APPROVAL",Env.REMOTE); + try { + if(async) { + getSession(trans).executeAsync(sb.toString()); + return Result.ok(); + } else { + getSession(trans).execute(sb.toString()); + return Result.ok(); + } + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } finally { + tt.done(); + } + } else { + return super.delete(trans, data, false); + } - } + } - /** + /** * Log Modification statements to History * * @param modified which CRUD action was done @@ -257,8 +257,8 @@ public class ApprovalDAO extends CassDAOImpl { */ @Override protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; HistoryDAO.Data hd = HistoryDAO.newInitedData(); hd.user = trans.user(); @@ -271,7 +271,7 @@ public class ApprovalDAO extends CassDAOImpl { // Detail? // Reconstruct? if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); + trans.error().log("Cannot log to History"); } } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java index a6fbecaf..6702476a 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java @@ -52,7 +52,7 @@ public class ArtiDAO extends CassDAOImpl { private HistoryDAO historyDAO; private PSInfo psByMechID,psByMachine, psByNs; - + public ArtiDAO(AuthzTrans trans, Cluster cluster, String keyspace) { super(trans, ArtiDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); init(trans); @@ -65,67 +65,67 @@ public class ArtiDAO extends CassDAOImpl { } public static final int KEYLIMIT = 2; - public static class Data implements Bytification { - public String mechid; - public String machine; - private Set type; - public String sponsor; - public String ca; - public String dir; - public String ns; - public String os_user; - public String notify; - public Date expires; - public int renewDays; - public Set sans; + public static class Data implements Bytification { + public String mechid; + public String machine; + private Set type; + public String sponsor; + public String ca; + public String dir; + public String ns; + public String os_user; + public String notify; + public Date expires; + public int renewDays; + public Set sans; // // Getters - public Set type(boolean mutable) { - if (type == null) { - type = new HashSet<>(); - } else if (mutable && !(type instanceof HashSet)) { - type = new HashSet<>(type); - } - return type; - } + public Set type(boolean mutable) { + if (type == null) { + type = new HashSet<>(); + } else if (mutable && !(type instanceof HashSet)) { + type = new HashSet<>(type); + } + return type; + } - public Set sans(boolean mutable) { - if (sans == null) { - sans = new HashSet<>(); - } else if (mutable && !(sans instanceof HashSet)) { - sans = new HashSet<>(sans); - } - return sans; - } + public Set sans(boolean mutable) { + if (sans == null) { + sans = new HashSet<>(); + } else if (mutable && !(sans instanceof HashSet)) { + sans = new HashSet<>(sans); + } + return sans; + } - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ArtifactLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - ArtifactLoader.deflt.unmarshal(this, toDIS(bb)); - } + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ArtifactLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + ArtifactLoader.deflt.unmarshal(this, toDIS(bb)); + } - public String toString() { - return mechid + ' ' + machine + ' ' + Chrono.dateTime(expires); - } + public String toString() { + return mechid + ' ' + machine + ' ' + Chrono.dateTime(expires); + } } private static class ArtifactLoader extends Loader implements Streamer{ - public static final int MAGIC=95829343; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; // Note: + public static final int MAGIC=95829343; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; // Note: - public static final ArtifactLoader deflt = new ArtifactLoader(KEYLIMIT); - public ArtifactLoader(int keylimit) { + public static final ArtifactLoader deflt = new ArtifactLoader(KEYLIMIT); + public ArtifactLoader(int keylimit) { super(keylimit); } - @Override + @Override public Data load(Data data, Row row) { data.mechid = row.getString(0); data.machine = row.getString(1); @@ -144,7 +144,7 @@ public class ArtiDAO extends CassDAOImpl { @Override protected void key(final Data data, final int idx, Object[] obj) { - int i; + int i; obj[i=idx] = data.mechid; obj[++i] = data.machine; } @@ -164,110 +164,110 @@ public class ArtiDAO extends CassDAOImpl { obj[++i] = data.sans; } - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.mechid); - writeString(os, data.machine); - os.writeInt(data.type.size()); - for(String s : data.type) { - writeString(os, s); - } - writeString(os, data.sponsor); - writeString(os, data.ca); - writeString(os, data.dir); - writeString(os, data.ns); - writeString(os, data.os_user); - writeString(os, data.notify); - os.writeLong(data.expires==null?-1:data.expires.getTime()); - os.writeInt(data.renewDays); - if(data.sans!=null) { - os.writeInt(data.sans.size()); - for(String s : data.sans) { - writeString(os, s); - } - } else { - os.writeInt(0); - } - } + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.mechid); + writeString(os, data.machine); + os.writeInt(data.type.size()); + for(String s : data.type) { + writeString(os, s); + } + writeString(os, data.sponsor); + writeString(os, data.ca); + writeString(os, data.dir); + writeString(os, data.ns); + writeString(os, data.os_user); + writeString(os, data.notify); + os.writeLong(data.expires==null?-1:data.expires.getTime()); + os.writeInt(data.renewDays); + if(data.sans!=null) { + os.writeInt(data.sans.size()); + for(String s : data.sans) { + writeString(os, s); + } + } else { + os.writeInt(0); + } + } - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.mechid = readString(is,buff); - data.machine = readString(is,buff); - int size = is.readInt(); - data.type = new HashSet<>(size); - for(int i=0;i(size); - for(int i=0;i(size); + for(int i=0;i(size); + for(int i=0;i> readByMechID(AuthzTrans trans, String mechid) { - return psByMechID.read(trans, R_TEXT, new Object[]{mechid}); - } + return psByMechID.read(trans, R_TEXT, new Object[]{mechid}); + } - public Result> readByMachine(AuthzTrans trans, String machine) { - return psByMachine.read(trans, R_TEXT, new Object[]{machine}); - } + public Result> readByMachine(AuthzTrans trans, String machine) { + return psByMachine.read(trans, R_TEXT, new Object[]{machine}); + } - public Result> readByNs(AuthzTrans trans, String ns) { - return psByNs.read(trans, R_TEXT, new Object[]{ns}); - } + public Result> readByNs(AuthzTrans trans, String ns) { + return psByNs.read(trans, R_TEXT, new Object[]{ns}); + } - /** + /** * Log Modification statements to History * * @param modified which CRUD action was done @@ -276,8 +276,8 @@ public class ArtiDAO extends CassDAOImpl { */ @Override protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; HistoryDAO.Data hd = HistoryDAO.newInitedData(); hd.user = trans.user(); @@ -288,16 +288,16 @@ public class ArtiDAO extends CassDAOImpl { ? String.format("%s by %s", override[0], hd.user) : String.format("%sd %s for %s",modified.name(),data.mechid,data.machine); // Detail? - if(modified==CRUD.delete) { - try { - hd.reconstruct = data.bytify(); - } catch (IOException e) { - trans.error().log(e,"Could not serialize CredDAO.Data"); - } - } + if(modified==CRUD.delete) { + try { + hd.reconstruct = data.bytify(); + } catch (IOException e) { + trans.error().log(e,"Could not serialize CredDAO.Data"); + } + } if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); + trans.error().log("Cannot log to History"); } } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java index 6d9900b9..e3f994c0 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java @@ -62,405 +62,405 @@ import com.datastax.driver.core.exceptions.DriverException; public class CacheInfoDAO extends CassDAOImpl implements CIDAO { - private static final String TABLE = "cache"; - public static final Map info = new ConcurrentHashMap<>(); + private static final String TABLE = "cache"; + public static final Map info = new ConcurrentHashMap<>(); - private static CacheUpdate cacheUpdate; - - // Hold current time stamps from Tables - private final Date startTime; - private PreparedStatement psCheck; - - public CacheInfoDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { - super(trans, CacheInfoDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE,readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - startTime = new Date(); - init(trans); - } + private static CacheUpdate cacheUpdate; + + // Hold current time stamps from Tables + private final Date startTime; + private PreparedStatement psCheck; + + public CacheInfoDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { + super(trans, CacheInfoDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE,readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + startTime = new Date(); + init(trans); + } - public CacheInfoDAO(AuthzTrans trans, AbsCassDAO aDao) throws APIException, IOException { - super(trans, CacheInfoDAO.class.getSimpleName(),aDao,Data.class,TABLE,readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - startTime = new Date(); - init(trans); - } + public CacheInfoDAO(AuthzTrans trans, AbsCassDAO aDao) throws APIException, IOException { + super(trans, CacheInfoDAO.class.getSimpleName(),aDao,Data.class,TABLE,readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + startTime = new Date(); + init(trans); + } ////////////////////////////////////////// // Data Definition, matches Cassandra DM ////////////////////////////////////////// private static final int KEYLIMIT = 2; - /** + /** * @author Jonathan */ - public static class Data { - public Data() { - name = null; - touched = null; - } - public Data(String name, int seg) { - this.name = name; - this.seg = seg; - touched = null; - } - - public String name; - public int seg; - public Date touched; + public static class Data { + public Data() { + name = null; + touched = null; + } + public Data(String name, int seg) { + this.name = name; + this.seg = seg; + touched = null; + } + + public String name; + public int seg; + public Date touched; } private static class InfoLoader extends Loader { - public static final InfoLoader dflt = new InfoLoader(KEYLIMIT); - - public InfoLoader(int keylimit) { - super(keylimit); - } - - @Override - public Data load(Data data, Row row) { - // Int more efficient - data.name = row.getString(0); - data.seg = row.getInt(1); - data.touched = row.getTimestamp(2); - return data; - } + public static final InfoLoader dflt = new InfoLoader(KEYLIMIT); + + public InfoLoader(int keylimit) { + super(keylimit); + } + + @Override + public Data load(Data data, Row row) { + // Int more efficient + data.name = row.getString(0); + data.seg = row.getInt(1); + data.touched = row.getTimestamp(2); + return data; + } - @Override - protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; + @Override + protected void key(Data data, int _idx, Object[] obj) { + int idx = _idx; - obj[idx]=data.name; - obj[++idx]=data.seg; - } + obj[idx]=data.name; + obj[++idx]=data.seg; + } - @Override - protected void body(Data data, int idx, Object[] obj) { - obj[idx]=data.touched; - } + @Override + protected void body(Data data, int idx, Object[] obj) { + obj[idx]=data.touched; + } } - public static void startUpdate(AuthzEnv env, HMangr hman, SecuritySetter ss, String ip, int port) { - if(cacheUpdate==null) { - Thread t= new Thread(cacheUpdate = new CacheUpdate(env,hman,ss, ip,port),"CacheInfo Update Thread"); - t.setDaemon(true); - t.start(); - } - } + public static void startUpdate(AuthzEnv env, HMangr hman, SecuritySetter ss, String ip, int port) { + if(cacheUpdate==null) { + Thread t= new Thread(cacheUpdate = new CacheUpdate(env,hman,ss, ip,port),"CacheInfo Update Thread"); + t.setDaemon(true); + t.start(); + } + } - public static void stopUpdate() { - if(cacheUpdate!=null) { - cacheUpdate.go=false; - } - } + public static void stopUpdate() { + if(cacheUpdate!=null) { + cacheUpdate.go=false; + } + } - private final static class CacheUpdate extends Thread { - public static BlockingQueue notifyDQ = new LinkedBlockingQueue(2000); + private final static class CacheUpdate extends Thread { + public static BlockingQueue notifyDQ = new LinkedBlockingQueue(2000); - private static final String VOID_CT="application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"; - private AuthzEnv env; - private HMangr hman; - private SecuritySetter ss; - private final String authority; - public boolean go = true; - - public CacheUpdate(AuthzEnv env, HMangr hman, SecuritySetter ss, String ip, int port) { - this.env = env; - this.hman = hman; - this.ss = ss; - - this.authority = ip+':'+port; - } - - private static class Transfer { - public String table; - public int segs[]; - public Transfer(String table, int[] segs) { - this.table = table; - this.segs = segs; - } - } - private class CacheClear extends Retryable { - public int total=0; - private AuthzTrans trans; - private String type; - private String segs; - - public CacheClear(AuthzTrans trans) { - this.trans = trans; - } + private static final String VOID_CT="application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"; + private AuthzEnv env; + private HMangr hman; + private SecuritySetter ss; + private final String authority; + public boolean go = true; + + public CacheUpdate(AuthzEnv env, HMangr hman, SecuritySetter ss, String ip, int port) { + this.env = env; + this.hman = hman; + this.ss = ss; + + this.authority = ip+':'+port; + } + + private static class Transfer { + public String table; + public int segs[]; + public Transfer(String table, int[] segs) { + this.table = table; + this.segs = segs; + } + } + private class CacheClear extends Retryable { + public int total=0; + private AuthzTrans trans; + private String type; + private String segs; + + public CacheClear(AuthzTrans trans) { + this.trans = trans; + } - public void set(Entry es) { - type = es.getKey(); - segs = es.getValue().toString(); - } - - @Override - public Integer code(Rcli client) throws APIException, CadiException { - URI to = client.getURI(); - if(!to.getAuthority().equals(authority)) { - Future f = client.delete("/mgmt/cache/"+type+'/'+segs,VOID_CT); - if(f.get(hman.readTimeout())) { - ++total; - } else { - trans.error().log("Error During AAF Peer Notify",f.code(),f.body()); - } - } - return total; - } - } - - private class IntHolder { - private int[] raw; - HashSet set; - - public IntHolder(int ints[]) { - raw = ints; - set = null; - } - public void add(int[] ints) { - if(set==null) { - set = new HashSet<>(); - - for(int i=0;i es) { + type = es.getKey(); + segs = es.getValue().toString(); + } + + @Override + public Integer code(Rcli client) throws APIException, CadiException { + URI to = client.getURI(); + if(!to.getAuthority().equals(authority)) { + Future f = client.delete("/mgmt/cache/"+type+'/'+segs,VOID_CT); + if(f.get(hman.readTimeout())) { + ++total; + } else { + trans.error().log("Error During AAF Peer Notify",f.code(),f.body()); + } + } + return total; + } + } + + private class IntHolder { + private int[] raw; + HashSet set; + + public IntHolder(int ints[]) { + raw = ints; + set = null; + } + public void add(int[] ints) { + if(set==null) { + set = new HashSet<>(); + + for(int i=0;i gather = null; - AuthzTrans trans = null; - long start=0; - // Do a block poll first - do { - if(gather==null) { - start = System.nanoTime(); - trans = env.newTransNoAvg(); - cc = new CacheClear(trans); - gather = new HashMap<>(); - } - IntHolder prev = gather.get(data.table); - if(prev==null) { - gather.put(data.table,new IntHolder(data.segs)); - } else { - prev.add(data.segs); - } - // continue while there is data - } while((data = notifyDQ.poll())!=null); - if(gather!=null) { - for(Entry es : gather.entrySet()) { - cc.set(es); - try { - if(hman.all(ss, cc, false)!=null) { - ++count; - } - } catch (Exception e) { - trans.error().log(e, "Error on Cache Update"); - } - } - if(env.debug().isLoggable()) { - float millis = (System.nanoTime()-start)/1000000f; - StringBuilder sb = new StringBuilder("Direct Cache Refresh: "); - sb.append("Updated "); - sb.append(count); - if(count==1) { - sb.append(" entry for "); - } else { - sb.append(" entries for "); - } - int peers = count<=0?0:cc.total/count; - sb.append(peers); - sb.append(" client"); - if(peers!=1) { - sb.append('s'); - } - sb.append(" in "); - sb.append(millis); - sb.append("ms"); - trans.auditTrail(0, sb, Env.REMOTE); - env.debug().log(sb); - } - } - } catch (InterruptedException e1) { - go = false; - Thread.currentThread().interrupt(); - } - } while(go); - } - } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + boolean first = true; + if(set==null) { + for(int i : raw) { + if(first) { + first=false; + } else { + sb.append(','); + } + sb.append(i); + } + } else { + for(Integer i : set) { + if(first) { + first=false; + } else { + sb.append(','); + } + sb.append(i); + } + } + return sb.toString(); + } + } + + @Override + public void run() { + do { + try { + Transfer data = notifyDQ.poll(4,TimeUnit.SECONDS); + if(data==null) { + continue; + } + + int count = 0; + CacheClear cc = null; + Map gather = null; + AuthzTrans trans = null; + long start=0; + // Do a block poll first + do { + if(gather==null) { + start = System.nanoTime(); + trans = env.newTransNoAvg(); + cc = new CacheClear(trans); + gather = new HashMap<>(); + } + IntHolder prev = gather.get(data.table); + if(prev==null) { + gather.put(data.table,new IntHolder(data.segs)); + } else { + prev.add(data.segs); + } + // continue while there is data + } while((data = notifyDQ.poll())!=null); + if(gather!=null) { + for(Entry es : gather.entrySet()) { + cc.set(es); + try { + if(hman.all(ss, cc, false)!=null) { + ++count; + } + } catch (Exception e) { + trans.error().log(e, "Error on Cache Update"); + } + } + if(env.debug().isLoggable()) { + float millis = (System.nanoTime()-start)/1000000f; + StringBuilder sb = new StringBuilder("Direct Cache Refresh: "); + sb.append("Updated "); + sb.append(count); + if(count==1) { + sb.append(" entry for "); + } else { + sb.append(" entries for "); + } + int peers = count<=0?0:cc.total/count; + sb.append(peers); + sb.append(" client"); + if(peers!=1) { + sb.append('s'); + } + sb.append(" in "); + sb.append(millis); + sb.append("ms"); + trans.auditTrail(0, sb, Env.REMOTE); + env.debug().log(sb); + } + } + } catch (InterruptedException e1) { + go = false; + Thread.currentThread().interrupt(); + } + } while(go); + } + } - private void init(AuthzTrans trans) throws APIException, IOException { - - String[] helpers = setCRUD(trans, TABLE, Data.class, InfoLoader.dflt); - psCheck = getSession(trans).prepare(SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE); + private void init(AuthzTrans trans) throws APIException, IOException { + + String[] helpers = setCRUD(trans, TABLE, Data.class, InfoLoader.dflt); + psCheck = getSession(trans).prepare(SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE); - disable(CRUD.create); - disable(CRUD.delete); - } + disable(CRUD.create); + disable(CRUD.delete); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.cass.CIDAO#touch(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, int) - */ - - @Override - public Result touch(AuthzTrans trans, String name, int ... seg) { - ///////////// - // Direct Service Cache Invalidation - ///////////// - // ConcurrentQueues are open-ended. We don't want any Memory leaks - // Note: we keep a separate counter, because "size()" on a Linked Queue is expensive - if(cacheUpdate!=null) { - try { - if(!CacheUpdate.notifyDQ.offer(new CacheUpdate.Transfer(name, seg),2,TimeUnit.SECONDS)) { - trans.error().log("Cache Notify Queue is not accepting messages, bouncing may be appropriate" ); - } - } catch (InterruptedException e) { - trans.error().log("Cache Notify Queue posting was interrupted" ); - Thread.currentThread().interrupt(); - } - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.dao.cass.CIDAO#touch(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, int) + */ + + @Override + public Result touch(AuthzTrans trans, String name, int ... seg) { + ///////////// + // Direct Service Cache Invalidation + ///////////// + // ConcurrentQueues are open-ended. We don't want any Memory leaks + // Note: we keep a separate counter, because "size()" on a Linked Queue is expensive + if(cacheUpdate!=null) { + try { + if(!CacheUpdate.notifyDQ.offer(new CacheUpdate.Transfer(name, seg),2,TimeUnit.SECONDS)) { + trans.error().log("Cache Notify Queue is not accepting messages, bouncing may be appropriate" ); + } + } catch (InterruptedException e) { + trans.error().log("Cache Notify Queue posting was interrupted" ); + Thread.currentThread().interrupt(); + } + } - ///////////// - // Table Based Cache Invalidation (original) - ///////////// - // Note: Save time with multiple Sequence Touches, but PreparedStmt doesn't support IN - StringBuilder start = new StringBuilder("CacheInfoDAO Touch segments "); - start.append(name); - start.append(": "); - StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); - boolean first = true; - for(int s : seg) { - sb.append(UPDATE_SP); - sb.append(TABLE); - sb.append(" SET touched=dateof(now()) WHERE name = '"); - sb.append(name); - sb.append("' AND seg = "); - sb.append(s); - sb.append(";\n"); - if(first) { - first =false; - } else { - start.append(','); - } - start.append(s); - } - sb.append("APPLY BATCH;"); - TimeTaken tt = trans.start(start.toString(),Env.REMOTE); - try { - getSession(trans).executeAsync(sb.toString()); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } finally { - tt.done(); - } - return Result.ok(); - } + ///////////// + // Table Based Cache Invalidation (original) + ///////////// + // Note: Save time with multiple Sequence Touches, but PreparedStmt doesn't support IN + StringBuilder start = new StringBuilder("CacheInfoDAO Touch segments "); + start.append(name); + start.append(": "); + StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); + boolean first = true; + for(int s : seg) { + sb.append(UPDATE_SP); + sb.append(TABLE); + sb.append(" SET touched=dateof(now()) WHERE name = '"); + sb.append(name); + sb.append("' AND seg = "); + sb.append(s); + sb.append(";\n"); + if(first) { + first =false; + } else { + start.append(','); + } + start.append(s); + } + sb.append("APPLY BATCH;"); + TimeTaken tt = trans.start(start.toString(),Env.REMOTE); + try { + getSession(trans).executeAsync(sb.toString()); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } finally { + tt.done(); + } + return Result.ok(); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.cass.CIDAO#check(org.onap.aaf.auth.env.test.AuthzTrans) - */ - @Override - public Result check(AuthzTrans trans) { - ResultSet rs; - TimeTaken tt = trans.start("Check Table Timestamps",Env.REMOTE); - try { - rs = getSession(trans).execute(new BoundStatement(psCheck)); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } finally { - tt.done(); - } - - String lastName = null; - Date[] dates = null; - for(Row row : rs.all()) { - String name = row.getString(0); - int seg = row.getInt(1); - if(!name.equals(lastName)) { - dates = info.get(name); - lastName=name; - } - if(dates==null) { - dates=new Date[seg+1]; - info.put(name,dates); - } else if(dates.length<=seg) { - Date[] temp = new Date[seg+1]; - System.arraycopy(dates, 0, temp, 0, dates.length); - dates = temp; - info.put(name, dates); - } - Date temp = row.getTimestamp(2); - if(dates[seg]==null || dates[seg].before(temp)) { - dates[seg]=temp; - } - } - return Result.ok(); - } - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.cass.CIDAO#get(java.lang.String, int) - */ + * @see org.onap.aaf.auth.dao.cass.CIDAO#check(org.onap.aaf.auth.env.test.AuthzTrans) + */ @Override - public Date get(AuthzTrans trans, String table, int seg) { - Date[] dates = info.get(table); - if(dates==null) { - dates = new Date[seg+1]; - touch(trans,table, seg); - } else if(dates.length<=seg) { - Date[] temp = new Date[seg+1]; - System.arraycopy(dates, 0, temp, 0, dates.length); - dates = temp; - } - Date rv = dates[seg]; - if(rv==null) { - rv=dates[seg]=startTime; - } - return rv; - } + public Result check(AuthzTrans trans) { + ResultSet rs; + TimeTaken tt = trans.start("Check Table Timestamps",Env.REMOTE); + try { + rs = getSession(trans).execute(new BoundStatement(psCheck)); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } finally { + tt.done(); + } + + String lastName = null; + Date[] dates = null; + for(Row row : rs.all()) { + String name = row.getString(0); + int seg = row.getInt(1); + if(!name.equals(lastName)) { + dates = info.get(name); + lastName=name; + } + if(dates==null) { + dates=new Date[seg+1]; + info.put(name,dates); + } else if(dates.length<=seg) { + Date[] temp = new Date[seg+1]; + System.arraycopy(dates, 0, temp, 0, dates.length); + dates = temp; + info.put(name, dates); + } + Date temp = row.getTimestamp(2); + if(dates[seg]==null || dates[seg].before(temp)) { + dates[seg]=temp; + } + } + return Result.ok(); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.dao.cass.CIDAO#get(java.lang.String, int) + */ + @Override + public Date get(AuthzTrans trans, String table, int seg) { + Date[] dates = info.get(table); + if(dates==null) { + dates = new Date[seg+1]; + touch(trans,table, seg); + } else if(dates.length<=seg) { + Date[] temp = new Date[seg+1]; + System.arraycopy(dates, 0, temp, 0, dates.length); + dates = temp; + } + Date rv = dates[seg]; + if(rv==null) { + rv=dates[seg]=startTime; + } + return rv; + } - @Override - protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - // Do nothing - } + @Override + protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { + // Do nothing + } } \ No newline at end of file diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheableData.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheableData.java index af4b2302..be7c44ae 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheableData.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheableData.java @@ -26,10 +26,10 @@ import org.onap.aaf.auth.dao.Cached; import org.onap.aaf.auth.dao.CachedDAO; public abstract class CacheableData implements Cacheable { - // WARNING: DON'T attempt to add any members here, as it will - // be treated by system as fields expected in Tables - protected int seg(Cached cache, Object ... fields) { - return cache==null?0:cache.invalidate(CachedDAO.keyFromObjs(fields)); - } - + // WARNING: DON'T attempt to add any members here, as it will + // be treated by system as fields expected in Tables + protected int seg(Cached cache, Object ... fields) { + return cache==null?0:cache.invalidate(CachedDAO.keyFromObjs(fields)); + } + } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java index 28e27497..00c9ae90 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java @@ -52,9 +52,9 @@ public class CertDAO extends CassDAOImpl { public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F private HistoryDAO historyDAO; - private CIDAO infoDAO; - private PSInfo psX500,psID; - + private CIDAO infoDAO; + private PSInfo psX500,psID; + public CertDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { super(trans, CertDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); init(trans); @@ -68,47 +68,47 @@ public class CertDAO extends CassDAOImpl { } public static final int KEYLIMIT = 2; - public static class Data extends CacheableData implements Bytification { - - public String ca; - public BigInteger serial; - public String id; - public String x500; - public String x509; + public static class Data extends CacheableData implements Bytification { + + public String ca; + public BigInteger serial; + public String id; + public String x500; + public String x509; @Override - public int[] invalidate(Cached cache) { - return new int[] { - seg(cache,ca,serial) - }; - } + public int[] invalidate(Cached cache) { + return new int[] { + seg(cache,ca,serial) + }; + } - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - CertLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - CertLoader.deflt.unmarshal(this, toDIS(bb)); - } + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CertLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + CertLoader.deflt.unmarshal(this, toDIS(bb)); + } } private static class CertLoader extends Loader implements Streamer{ - public static final int MAGIC=85102934; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; // Note: + public static final int MAGIC=85102934; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; // Note: - public static final CertLoader deflt = new CertLoader(KEYLIMIT); - public CertLoader(int keylimit) { + public static final CertLoader deflt = new CertLoader(KEYLIMIT); + public CertLoader(int keylimit) { super(keylimit); } - @Override + @Override public Data load(Data data, Row row) { - data.ca = row.getString(0); + data.ca = row.getString(0); ByteBuffer bb = row.getBytesUnsafe(1); byte[] bytes = new byte[bb.remaining()]; bb.get(bytes); @@ -127,7 +127,7 @@ public class CertDAO extends CassDAOImpl { @Override protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; + int idx = _idx; obj[idx] = data.id; obj[++idx] = data.x500; @@ -136,74 +136,74 @@ public class CertDAO extends CassDAOImpl { } - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.id); - writeString(os, data.x500); - writeString(os, data.x509); - writeString(os, data.ca); - if(data.serial==null) { - os.writeInt(-1); - } else { - byte[] dsba = data.serial.toByteArray(); - int l = dsba.length; - os.writeInt(l); - os.write(dsba,0,l); - } - } - - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.id = readString(is,buff); - data.x500 = readString(is,buff); - data.x509 = readString(is,buff); - data.ca = readString(is,buff); - int i = is.readInt(); - data.serial=null; - if(i>=0) { - byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads - if(is.read(bytes)>0) { - data.serial = new BigInteger(bytes); - } - } - } + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.id); + writeString(os, data.x500); + writeString(os, data.x509); + writeString(os, data.ca); + if(data.serial==null) { + os.writeInt(-1); + } else { + byte[] dsba = data.serial.toByteArray(); + int l = dsba.length; + os.writeInt(l); + os.write(dsba,0,l); + } + } + + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; + data.id = readString(is,buff); + data.x500 = readString(is,buff); + data.x509 = readString(is,buff); + data.ca = readString(is,buff); + int i = is.readInt(); + data.serial=null; + if(i>=0) { + byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads + if(is.read(bytes)>0) { + data.serial = new BigInteger(bytes); + } + } + } } public Result> read(AuthzTrans trans, Object ... key) { - // Translate BigInteger to Byte array for lookup - return super.read(trans, key[0],ByteBuffer.wrap(((BigInteger)key[1]).toByteArray())); + // Translate BigInteger to Byte array for lookup + return super.read(trans, key[0],ByteBuffer.wrap(((BigInteger)key[1]).toByteArray())); } private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs if(historyDAO==null) { - historyDAO = new HistoryDAO(trans,this); + historyDAO = new HistoryDAO(trans,this); + } + if(infoDAO==null) { + infoDAO = new CacheInfoDAO(trans,this); } - if(infoDAO==null) { - infoDAO = new CacheInfoDAO(trans,this); - } - String[] helpers = setCRUD(trans, TABLE, Data.class, CertLoader.deflt); + String[] helpers = setCRUD(trans, TABLE, Data.class, CertLoader.deflt); - psID = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE id = ?", CertLoader.deflt,readConsistency); + psID = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE id = ?", CertLoader.deflt,readConsistency); - psX500 = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE x500 = ?", CertLoader.deflt,readConsistency); - + psX500 = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE x500 = ?", CertLoader.deflt,readConsistency); + } - public Result> readX500(AuthzTrans trans, String x500) { - return psX500.read(trans, R_TEXT, new Object[]{x500}); - } + public Result> readX500(AuthzTrans trans, String x500) { + return psX500.read(trans, R_TEXT, new Object[]{x500}); + } - public Result> readID(AuthzTrans trans, String id) { - return psID.read(trans, R_TEXT, new Object[]{id}); - } + public Result> readID(AuthzTrans trans, String id) { + return psID.read(trans, R_TEXT, new Object[]{id}); + } /** * Log Modification statements to History @@ -214,8 +214,8 @@ public class CertDAO extends CassDAOImpl { */ @Override protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; HistoryDAO.Data hd = HistoryDAO.newInitedData(); hd.user = trans.user(); @@ -226,19 +226,19 @@ public class CertDAO extends CassDAOImpl { ? String.format("%s by %s", override[0], hd.user) : (modified.name() + "d certificate info for " + data.id); // Detail? - if(modified==CRUD.delete) { - try { - hd.reconstruct = data.bytify(); - } catch (IOException e) { - trans.error().log(e,"Could not serialize CertDAO.Data"); - } - } + if(modified==CRUD.delete) { + try { + hd.reconstruct = data.bytify(); + } catch (IOException e) { + trans.error().log(e,"Could not serialize CertDAO.Data"); + } + } if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); + trans.error().log("Cannot log to History"); } if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { - trans.error().log("Cannot touch Cert"); + trans.error().log("Cannot touch Cert"); } } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ConfigDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ConfigDAO.java index df284044..398e7323 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ConfigDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ConfigDAO.java @@ -45,7 +45,7 @@ import com.datastax.driver.core.Row; public class ConfigDAO extends CassDAOImpl { public static final String TABLE = "config"; public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F - private PSInfo psName; + private PSInfo psName; public ConfigDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { super(trans, ConfigDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); @@ -58,25 +58,25 @@ public class ConfigDAO extends CassDAOImpl { } public static final int KEYLIMIT = 2; - public static class Data { - public String name; - public String tag; - public String value; + public static class Data { + public String name; + public String tag; + public String value; } private static class ConfigLoader extends Loader implements Streamer{ - public static final int MAGIC=2673849; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; + public static final int MAGIC=2673849; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; - public static final ConfigLoader deflt = new ConfigLoader(KEYLIMIT); - public ConfigLoader(int keylimit) { + public static final ConfigLoader deflt = new ConfigLoader(KEYLIMIT); + public ConfigLoader(int keylimit) { super(keylimit); } - @Override + @Override public Data load(Data data, Row row) { - data.name = row.getString(0); + data.name = row.getString(0); data.tag = row.getString(1); data.value = row.getString(2); return data; @@ -93,30 +93,30 @@ public class ConfigDAO extends CassDAOImpl { obj[_idx] = data.value; } - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.name); - writeString(os, data.tag); - writeString(os, data.value); - } - - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.name = readString(is,buff); - data.tag = readString(is,buff); - data.value = readString(is,buff); - } + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.name); + writeString(os, data.tag); + writeString(os, data.value); + } + + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; + data.name = readString(is,buff); + data.tag = readString(is,buff); + data.value = readString(is,buff); + } } private void init(AuthzTrans trans) throws APIException, IOException { - String[] helpers = setCRUD(trans, TABLE, Data.class, ConfigLoader.deflt); + String[] helpers = setCRUD(trans, TABLE, Data.class, ConfigLoader.deflt); - psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE name = ?", ConfigLoader.deflt,readConsistency); + psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE name = ?", ConfigLoader.deflt,readConsistency); } @@ -129,12 +129,12 @@ public class ConfigDAO extends CassDAOImpl { */ @Override protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - // not an auditable table. + // not an auditable table. } - public Result> readName(AuthzTrans trans, String name) { - return psName.read(trans, R_TEXT, new Object[]{name}); - } + public Result> readName(AuthzTrans trans, String name) { + return psName.read(trans, R_TEXT, new Object[]{name}); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java index 76e3b424..5bcba9d9 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java @@ -51,16 +51,16 @@ import com.datastax.driver.core.Row; public class CredDAO extends CassDAOImpl { public static final String TABLE = "cred"; public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F - public static final int RAW = -1; + public static final int RAW = -1; public static final int BASIC_AUTH = 1; public static final int BASIC_AUTH_SHA256 = 2; public static final int CERT_SHA256_RSA =200; private HistoryDAO historyDAO; - private CIDAO infoDAO; - private PSInfo psNS; - private PSInfo psID; - + private CIDAO infoDAO; + private PSInfo psNS; + private PSInfo psID; + public CredDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { super(trans, CredDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); init(trans); @@ -74,52 +74,52 @@ public class CredDAO extends CassDAOImpl { } public static final int KEYLIMIT = 3; - public static class Data extends CacheableData implements Bytification { - - public String id; - public Integer type; - public Date expires; - public Integer other; - public String ns; - public String notes; - public ByteBuffer cred; // this is a blob in cassandra + public static class Data extends CacheableData implements Bytification { + + public String id; + public Integer type; + public Date expires; + public Integer other; + public String ns; + public String notes; + public ByteBuffer cred; // this is a blob in cassandra @Override - public int[] invalidate(Cached cache) { - return new int[] { - seg(cache,id) // cache is for all entities - }; - } + public int[] invalidate(Cached cache) { + return new int[] { + seg(cache,id) // cache is for all entities + }; + } + + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CredLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - CredLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - CredLoader.deflt.unmarshal(this, toDIS(bb)); - } + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + CredLoader.deflt.unmarshal(this, toDIS(bb)); + } - public String toString() { - return id + ' ' + type + ' ' + Chrono.dateTime(expires); - } + public String toString() { + return id + ' ' + type + ' ' + Chrono.dateTime(expires); + } } private static class CredLoader extends Loader implements Streamer{ - public static final int MAGIC=153323443; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; // Note: + public static final int MAGIC=153323443; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; // Note: - public static final CredLoader deflt = new CredLoader(KEYLIMIT); - public CredLoader(int keylimit) { + public static final CredLoader deflt = new CredLoader(KEYLIMIT); + public CredLoader(int keylimit) { super(keylimit); } - @Override + @Override public Data load(Data data, Row row) { data.id = row.getString(0); data.type = row.getInt(1); // NOTE: in datastax driver, If the int value is NULL, 0 is returned! @@ -133,7 +133,7 @@ public class CredDAO extends CassDAOImpl { @Override protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; + int idx = _idx; obj[idx] = data.id; obj[++idx] = data.type; @@ -149,77 +149,77 @@ public class CredDAO extends CassDAOImpl { obj[++i] = data.cred; } - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.id); - os.writeInt(data.type); - os.writeLong(data.expires==null?-1:data.expires.getTime()); - os.writeInt(data.other==null?0:data.other); - writeString(os, data.ns); - writeString(os, data.notes); - if(data.cred==null) { - os.writeInt(-1); - } else { - int l = data.cred.limit()-data.cred.position(); - os.writeInt(l); - os.write(data.cred.array(),data.cred.position(),l); - } - } + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.id); + os.writeInt(data.type); + os.writeLong(data.expires==null?-1:data.expires.getTime()); + os.writeInt(data.other==null?0:data.other); + writeString(os, data.ns); + writeString(os, data.notes); + if(data.cred==null) { + os.writeInt(-1); + } else { + int l = data.cred.limit()-data.cred.position(); + os.writeInt(l); + os.write(data.cred.array(),data.cred.position(),l); + } + } - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.id = readString(is,buff); - data.type = is.readInt(); - - long l = is.readLong(); - data.expires = l<0?null:new Date(l); - data.other = is.readInt(); - data.ns = readString(is,buff); - data.notes = readString(is,buff); - - int i = is.readInt(); - data.cred=null; - if(i>=0) { - byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads - int read = is.read(bytes); - if(read>0) { - data.cred = ByteBuffer.wrap(bytes); - } - } - } + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; + data.id = readString(is,buff); + data.type = is.readInt(); + + long l = is.readLong(); + data.expires = l<0?null:new Date(l); + data.other = is.readInt(); + data.ns = readString(is,buff); + data.notes = readString(is,buff); + + int i = is.readInt(); + data.cred=null; + if(i>=0) { + byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads + int read = is.read(bytes); + if(read>0) { + data.cred = ByteBuffer.wrap(bytes); + } + } + } } private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs if(historyDAO==null) { - historyDAO = new HistoryDAO(trans,this); + historyDAO = new HistoryDAO(trans,this); } - if(infoDAO==null) { - infoDAO = new CacheInfoDAO(trans,this); - } - + if(infoDAO==null) { + infoDAO = new CacheInfoDAO(trans,this); + } + - String[] helpers = setCRUD(trans, TABLE, Data.class, CredLoader.deflt); - - psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE ns = ?", CredLoader.deflt,readConsistency); - - psID = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE id = ?", CredLoader.deflt,readConsistency); + String[] helpers = setCRUD(trans, TABLE, Data.class, CredLoader.deflt); + + psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE ns = ?", CredLoader.deflt,readConsistency); + + psID = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE id = ?", CredLoader.deflt,readConsistency); + } + + public Result> readNS(AuthzTrans trans, String ns) { + return psNS.read(trans, R_TEXT, new Object[]{ns}); + } + + public Result> readID(AuthzTrans trans, String id) { + return psID.read(trans, R_TEXT, new Object[]{id}); } - public Result> readNS(AuthzTrans trans, String ns) { - return psNS.read(trans, R_TEXT, new Object[]{ns}); - } - - public Result> readID(AuthzTrans trans, String id) { - return psID.read(trans, R_TEXT, new Object[]{id}); - } - /** * Log Modification statements to History * @@ -229,8 +229,8 @@ public class CredDAO extends CassDAOImpl { */ @Override protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; HistoryDAO.Data hd = HistoryDAO.newInitedData(); hd.user = trans.user(); @@ -241,19 +241,19 @@ public class CredDAO extends CassDAOImpl { ? String.format("%s by %s", override[0], hd.user) : (modified.name() + "d credential for " + data.id); // Detail? - if(modified==CRUD.delete) { - try { - hd.reconstruct = data.bytify(); - } catch (IOException e) { - trans.error().log(e,"Could not serialize CredDAO.Data"); - } - } + if(modified==CRUD.delete) { + try { + hd.reconstruct = data.bytify(); + } catch (IOException e) { + trans.error().log(e,"Could not serialize CredDAO.Data"); + } + } if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); + trans.error().log("Cannot log to History"); } if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { - trans.error().log("Cannot touch Cred"); + trans.error().log("Cannot touch Cred"); } } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/DelegateDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/DelegateDAO.java index 78a98e1d..b137b640 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/DelegateDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/DelegateDAO.java @@ -42,97 +42,97 @@ import com.datastax.driver.core.Row; public class DelegateDAO extends CassDAOImpl { - public static final String TABLE = "delegate"; - private PSInfo psByDelegate; - - public DelegateDAO(AuthzTrans trans, Cluster cluster, String keyspace) { - super(trans, DelegateDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - init(trans); - } - - public DelegateDAO(AuthzTrans trans, AbsCassDAO aDao) { - super(trans, DelegateDAO.class.getSimpleName(),aDao,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - init(trans); - } - - private static final int KEYLIMIT = 1; - public static class Data implements Bytification { - public String user; - public String delegate; - public Date expires; - - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DelegateLoader.dflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - DelegateLoader.dflt.unmarshal(this, toDIS(bb)); - } - } - - private static class DelegateLoader extends Loader implements Streamer{ - public static final int MAGIC=0xD823ACF2; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; - - public static final DelegateLoader dflt = new DelegateLoader(KEYLIMIT); - - public DelegateLoader(int keylimit) { - super(keylimit); - } - - @Override - public Data load(Data data, Row row) { - data.user = row.getString(0); - data.delegate = row.getString(1); - data.expires = row.getTimestamp(2); - return data; - } - - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.user; - } - - @Override - protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; - - obj[idx]=data.delegate; - obj[++idx]=data.expires; - } - - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.user); - writeString(os, data.delegate); - os.writeLong(data.expires.getTime()); - } - - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.user = readString(is, buff); - data.delegate = readString(is,buff); - data.expires = new Date(is.readLong()); - } - } - - private void init(AuthzTrans trans) { - String[] helpers = setCRUD(trans, TABLE, Data.class, DelegateLoader.dflt); - psByDelegate = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE delegate = ?", new DelegateLoader(1),readConsistency); - - } - - public Result> readByDelegate(AuthzTrans trans, String delegate) { - return psByDelegate.read(trans, R_TEXT, new Object[]{delegate}); - } + public static final String TABLE = "delegate"; + private PSInfo psByDelegate; + + public DelegateDAO(AuthzTrans trans, Cluster cluster, String keyspace) { + super(trans, DelegateDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + init(trans); + } + + public DelegateDAO(AuthzTrans trans, AbsCassDAO aDao) { + super(trans, DelegateDAO.class.getSimpleName(),aDao,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + init(trans); + } + + private static final int KEYLIMIT = 1; + public static class Data implements Bytification { + public String user; + public String delegate; + public Date expires; + + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DelegateLoader.dflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + DelegateLoader.dflt.unmarshal(this, toDIS(bb)); + } + } + + private static class DelegateLoader extends Loader implements Streamer{ + public static final int MAGIC=0xD823ACF2; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; + + public static final DelegateLoader dflt = new DelegateLoader(KEYLIMIT); + + public DelegateLoader(int keylimit) { + super(keylimit); + } + + @Override + public Data load(Data data, Row row) { + data.user = row.getString(0); + data.delegate = row.getString(1); + data.expires = row.getTimestamp(2); + return data; + } + + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.user; + } + + @Override + protected void body(Data data, int _idx, Object[] obj) { + int idx = _idx; + + obj[idx]=data.delegate; + obj[++idx]=data.expires; + } + + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.user); + writeString(os, data.delegate); + os.writeLong(data.expires.getTime()); + } + + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; + data.user = readString(is, buff); + data.delegate = readString(is,buff); + data.expires = new Date(is.readLong()); + } + } + + private void init(AuthzTrans trans) { + String[] helpers = setCRUD(trans, TABLE, Data.class, DelegateLoader.dflt); + psByDelegate = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE delegate = ?", new DelegateLoader(1),readConsistency); + + } + + public Result> readByDelegate(AuthzTrans trans, String delegate) { + return psByDelegate.read(trans, R_TEXT, new Object[]{delegate}); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java index 0263e009..6b0ea2df 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java @@ -45,13 +45,13 @@ import com.datastax.driver.core.Row; */ public class FutureDAO extends CassDAOImpl { private static final String TABLE = "future"; - private final HistoryDAO historyDAO; -// private static String createString; - private PSInfo psByStartAndTarget; - + private final HistoryDAO historyDAO; +// private static String createString; + private PSInfo psByStartAndTarget; + public FutureDAO(AuthzTrans trans, Cluster cluster, String keyspace) { super(trans, FutureDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - historyDAO = new HistoryDAO(trans, this); + historyDAO = new HistoryDAO(trans, this); init(trans); } @@ -64,11 +64,11 @@ public class FutureDAO extends CassDAOImpl { public static final int KEYLIMIT = 1; public static class Data { public UUID id; - public String target; - public String memo; - public Date start; - public Date expires; - public ByteBuffer construct; // this is a blob in cassandra + public String target; + public String memo; + public Date start; + public Date expires; + public ByteBuffer construct; // this is a blob in cassandra } private static class FLoader extends Loader { @@ -81,13 +81,13 @@ public class FutureDAO extends CassDAOImpl { } @Override - public Data load(Data data, Row row) { - data.id = row.getUUID(0); - data.target = row.getString(1); + public Data load(Data data, Row row) { + data.id = row.getUUID(0); + data.target = row.getString(1); data.memo = row.getString(2); - data.start = row.getTimestamp(3); - data.expires = row.getTimestamp(4); - data.construct = row.getBytes(5); + data.start = row.getTimestamp(3); + data.expires = row.getTimestamp(4); + data.construct = row.getBytes(5); return data; } @@ -98,7 +98,7 @@ public class FutureDAO extends CassDAOImpl { @Override protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; + int idx = _idx; obj[idx] = data.target; obj[++idx] = data.memo; @@ -113,71 +113,71 @@ public class FutureDAO extends CassDAOImpl { String[] helpers = setCRUD(trans, TABLE, Data.class, new FLoader(KEYLIMIT)); // Uh, oh. Can't use "now()" in Prepared Statements (at least at this level) -// createString = "INSERT INTO " + TABLE + " ("+helpers[FIELD_COMMAS] +") VALUES (now(),"; +// createString = "INSERT INTO " + TABLE + " ("+helpers[FIELD_COMMAS] +") VALUES (now(),"; // -// // Need a specialty Creator to handle the "now()" -// replace(CRUD.Create, new PSInfo(trans, "INSERT INTO future (" + helpers[FIELD_COMMAS] + -// ") VALUES(now(),?,?,?,?,?)",new FLoader(0))); - - // Other SELECT style statements... match with a local Method - psByStartAndTarget = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + - " FROM future WHERE start <= ? and target = ? ALLOW FILTERING", new FLoader(2) { - @Override - protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; - - obj[idx]=data.start; - obj[++idx]=data.target; - } - },readConsistency); - +// // Need a specialty Creator to handle the "now()" +// replace(CRUD.Create, new PSInfo(trans, "INSERT INTO future (" + helpers[FIELD_COMMAS] + +// ") VALUES(now(),?,?,?,?,?)",new FLoader(0))); + + // Other SELECT style statements... match with a local Method + psByStartAndTarget = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + + " FROM future WHERE start <= ? and target = ? ALLOW FILTERING", new FLoader(2) { + @Override + protected void key(Data data, int _idx, Object[] obj) { + int idx = _idx; + + obj[idx]=data.start; + obj[++idx]=data.target; + } + },readConsistency); + } public Result> readByStartAndTarget(AuthzTrans trans, Date start, String target) throws DAOException { - return psByStartAndTarget.read(trans, R_TEXT, new Object[]{start, target}); - } + return psByStartAndTarget.read(trans, R_TEXT, new Object[]{start, target}); + } /** - * Override create to add secondary ID to Subject in History, and create Data.ID, if it is null + * Override create to add secondary ID to Subject in History, and create Data.ID, if it is null */ - public Result create(AuthzTrans trans, FutureDAO.Data data, String id) { - // If ID is not set (typical), create one. - if(data.id==null) { - StringBuilder sb = new StringBuilder(trans.user()); - sb.append(data.target); - sb.append(System.currentTimeMillis()); - data.id = UUID.nameUUIDFromBytes(sb.toString().getBytes()); - } - Result rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { - return Result.err(rs); - } - wasModified(trans, CRUD.create, data, null, id); - return Result.ok(data); - } - - /** - * Log Modification statements to History - * - * @param modified which CRUD action was done - * @param data entity data that needs a log entry - * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data - */ - @Override - protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; - HistoryDAO.Data hd = HistoryDAO.newInitedData(); - hd.user = trans.user(); - hd.action = modified.name(); - hd.target = TABLE; - hd.subject = subject?override[1]:""; - hd.memo = memo?String.format("%s by %s", override[0], hd.user):data.memo; - - if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); - } - } + public Result create(AuthzTrans trans, FutureDAO.Data data, String id) { + // If ID is not set (typical), create one. + if(data.id==null) { + StringBuilder sb = new StringBuilder(trans.user()); + sb.append(data.target); + sb.append(System.currentTimeMillis()); + data.id = UUID.nameUUIDFromBytes(sb.toString().getBytes()); + } + Result rs = createPS.exec(trans, C_TEXT, data); + if(rs.notOK()) { + return Result.err(rs); + } + wasModified(trans, CRUD.create, data, null, id); + return Result.ok(data); + } + + /** + * Log Modification statements to History + * + * @param modified which CRUD action was done + * @param data entity data that needs a log entry + * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data + */ + @Override + protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; + HistoryDAO.Data hd = HistoryDAO.newInitedData(); + hd.user = trans.user(); + hd.action = modified.name(); + hd.target = TABLE; + hd.subject = subject?override[1]:""; + hd.memo = memo?String.format("%s by %s", override[0], hd.user):data.memo; + + if(historyDAO.create(trans, hd).status!=Status.OK) { + trans.error().log("Cannot log to History"); + } + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java index 13af8795..ce7e5477 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java @@ -54,175 +54,175 @@ import com.datastax.driver.core.Row; * */ public class HistoryDAO extends CassDAOImpl { - private static final String TABLE = "history"; - - private String[] helpers; - - private HistLoader defLoader; - - private AbsCassDAO.PSInfo readByUser, readBySubject, readByYRMN; - - public HistoryDAO(AuthzTrans trans, Cluster cluster, String keyspace) { - super(trans, HistoryDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE,ConsistencyLevel.LOCAL_ONE,ConsistencyLevel.ANY); - init(trans); - } - - public HistoryDAO(AuthzTrans trans, AbsCassDAO aDao) { - super(trans, HistoryDAO.class.getSimpleName(),aDao,Data.class,TABLE,ConsistencyLevel.LOCAL_ONE,ConsistencyLevel.ANY); - init(trans); - } - - - private static final int KEYLIMIT = 1; - public static class Data { - public UUID id; - public int yr_mon; - public String user; - public String action; - public String target; - public String subject; - public String memo; - public ByteBuffer reconstruct; - } - - private static class HistLoader extends Loader { - public HistLoader(int keylimit) { - super(keylimit); - } - - @Override - public Data load(Data data, Row row) { - data.id = row.getUUID(0); - data.yr_mon = row.getInt(1); - data.user = row.getString(2); - data.action = row.getString(3); - data.target = row.getString(4); - data.subject = row.getString(5); - data.memo = row.getString(6); - data.reconstruct = row.getBytes(7); - return data; - } - - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.id; - } - - @Override - protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.yr_mon; - obj[++idx]=data.user; - obj[++idx]=data.action; - obj[++idx]=data.target; - obj[++idx]=data.subject; - obj[++idx]=data.memo; -// obj[++idx]=data.detail; - obj[++idx]=data.reconstruct; - } - }; - - private void init(AuthzTrans trans) { - // Loader must match fields order - defLoader = new HistLoader(KEYLIMIT); - helpers = setCRUD(trans, TABLE, Data.class, defLoader); - - // Need a specialty Creator to handle the "now()" - // 9/9/2013 - Jonathan - Just great... now() is evaluated once on Client side, invalidating usage (what point is a now() from a long time in the past? - // Unless this is fixed, we're putting in non-prepared statement - // Solved in Cassandra. Make sure you are running 1.2.6 Cassandra or later. https://issues.apache.org/jira/browse/CASSANDRA-5616 - replace(CRUD.create, new PSInfo(trans, "INSERT INTO history (" + helpers[FIELD_COMMAS] + - ") VALUES(now(),?,?,?,?,?,?,?)", - new HistLoader(0) { - @Override - protected void key(Data data, int idx, Object[] obj) { - } - },writeConsistency) - ); -// disable(CRUD.Create); - - replace(CRUD.read, new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + - " FROM history WHERE id = ?", defLoader,readConsistency) -// new HistLoader(2) { -// @Override -// protected void key(Data data, int idx, Object[] obj) { -// obj[idx]=data.yr_mon; -// obj[++idx]=data.id; -// } -// }) - ); - disable(CRUD.update); - disable(CRUD.delete); - - readByUser = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + - " FROM history WHERE user = ?", defLoader,readConsistency); - readBySubject = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + - " FROM history WHERE subject = ? and target = ? ALLOW FILTERING", defLoader,readConsistency); - readByYRMN = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + - " FROM history WHERE yr_mon = ?", defLoader,readConsistency); - async(true); //TODO dropping messages with Async - } - - public static Data newInitedData() { - Data data = new Data(); - Date now = new Date(); - // Sonar claims that SimpleDateFormat is not thread safe, so we can't be static - data.yr_mon = Integer.parseInt(new SimpleDateFormat("yyyyMM").format(now)); - // data.day_time = Integer.parseInt(dayTimeFormat.format(now)); - return data; - } - - public Result> readByYYYYMM(AuthzTrans trans, int yyyymm) { - Result rs = readByYRMN.exec(trans, "yr_mon", yyyymm); - if(rs.notOK()) { - return Result.err(rs); - } - return extract(defLoader,rs.value,null,dflt); - } - - /** - * Gets the history for a user in the specified year and month - * year - the year in yyyy format - * month - the month in a year ...values 1 - 12 - **/ - public Result> readByUser(AuthzTrans trans, String user, int ... yyyymm) { - if(yyyymm.length==0) { - return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified"); - } - Result rs = readByUser.exec(trans, "user", user); - if(rs.notOK()) { - return Result.err(rs); - } - return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt); - } - - public Result> readBySubject(AuthzTrans trans, String subject, String target, int ... yyyymm) { - if(yyyymm.length==0) { - return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified"); - } - Result rs = readBySubject.exec(trans, "subject", subject, target); - if(rs.notOK()) { - return Result.err(rs); - } - return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt); - } - - private class YYYYMM implements Accept { - private int[] yyyymm; - public YYYYMM(int yyyymm[]) { - this.yyyymm = yyyymm; - } - @Override - public boolean ok(Data data) { - int dym = data.yr_mon; - for(int ym:yyyymm) { - if(dym==ym) { - return true; - } - } - return false; - } - - }; - + private static final String TABLE = "history"; + + private String[] helpers; + + private HistLoader defLoader; + + private AbsCassDAO.PSInfo readByUser, readBySubject, readByYRMN; + + public HistoryDAO(AuthzTrans trans, Cluster cluster, String keyspace) { + super(trans, HistoryDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE,ConsistencyLevel.LOCAL_ONE,ConsistencyLevel.ANY); + init(trans); + } + + public HistoryDAO(AuthzTrans trans, AbsCassDAO aDao) { + super(trans, HistoryDAO.class.getSimpleName(),aDao,Data.class,TABLE,ConsistencyLevel.LOCAL_ONE,ConsistencyLevel.ANY); + init(trans); + } + + + private static final int KEYLIMIT = 1; + public static class Data { + public UUID id; + public int yr_mon; + public String user; + public String action; + public String target; + public String subject; + public String memo; + public ByteBuffer reconstruct; + } + + private static class HistLoader extends Loader { + public HistLoader(int keylimit) { + super(keylimit); + } + + @Override + public Data load(Data data, Row row) { + data.id = row.getUUID(0); + data.yr_mon = row.getInt(1); + data.user = row.getString(2); + data.action = row.getString(3); + data.target = row.getString(4); + data.subject = row.getString(5); + data.memo = row.getString(6); + data.reconstruct = row.getBytes(7); + return data; + } + + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.id; + } + + @Override + protected void body(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.yr_mon; + obj[++idx]=data.user; + obj[++idx]=data.action; + obj[++idx]=data.target; + obj[++idx]=data.subject; + obj[++idx]=data.memo; +// obj[++idx]=data.detail; + obj[++idx]=data.reconstruct; + } + }; + + private void init(AuthzTrans trans) { + // Loader must match fields order + defLoader = new HistLoader(KEYLIMIT); + helpers = setCRUD(trans, TABLE, Data.class, defLoader); + + // Need a specialty Creator to handle the "now()" + // 9/9/2013 - Jonathan - Just great... now() is evaluated once on Client side, invalidating usage (what point is a now() from a long time in the past? + // Unless this is fixed, we're putting in non-prepared statement + // Solved in Cassandra. Make sure you are running 1.2.6 Cassandra or later. https://issues.apache.org/jira/browse/CASSANDRA-5616 + replace(CRUD.create, new PSInfo(trans, "INSERT INTO history (" + helpers[FIELD_COMMAS] + + ") VALUES(now(),?,?,?,?,?,?,?)", + new HistLoader(0) { + @Override + protected void key(Data data, int idx, Object[] obj) { + } + },writeConsistency) + ); +// disable(CRUD.Create); + + replace(CRUD.read, new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + + " FROM history WHERE id = ?", defLoader,readConsistency) +// new HistLoader(2) { +// @Override +// protected void key(Data data, int idx, Object[] obj) { +// obj[idx]=data.yr_mon; +// obj[++idx]=data.id; +// } +// }) + ); + disable(CRUD.update); + disable(CRUD.delete); + + readByUser = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + + " FROM history WHERE user = ?", defLoader,readConsistency); + readBySubject = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + + " FROM history WHERE subject = ? and target = ? ALLOW FILTERING", defLoader,readConsistency); + readByYRMN = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + + " FROM history WHERE yr_mon = ?", defLoader,readConsistency); + async(true); //TODO dropping messages with Async + } + + public static Data newInitedData() { + Data data = new Data(); + Date now = new Date(); + // Sonar claims that SimpleDateFormat is not thread safe, so we can't be static + data.yr_mon = Integer.parseInt(new SimpleDateFormat("yyyyMM").format(now)); + // data.day_time = Integer.parseInt(dayTimeFormat.format(now)); + return data; + } + + public Result> readByYYYYMM(AuthzTrans trans, int yyyymm) { + Result rs = readByYRMN.exec(trans, "yr_mon", yyyymm); + if(rs.notOK()) { + return Result.err(rs); + } + return extract(defLoader,rs.value,null,dflt); + } + + /** + * Gets the history for a user in the specified year and month + * year - the year in yyyy format + * month - the month in a year ...values 1 - 12 + **/ + public Result> readByUser(AuthzTrans trans, String user, int ... yyyymm) { + if(yyyymm.length==0) { + return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified"); + } + Result rs = readByUser.exec(trans, "user", user); + if(rs.notOK()) { + return Result.err(rs); + } + return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt); + } + + public Result> readBySubject(AuthzTrans trans, String subject, String target, int ... yyyymm) { + if(yyyymm.length==0) { + return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified"); + } + Result rs = readBySubject.exec(trans, "subject", subject, target); + if(rs.notOK()) { + return Result.err(rs); + } + return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt); + } + + private class YYYYMM implements Accept { + private int[] yyyymm; + public YYYYMM(int yyyymm[]) { + this.yyyymm = yyyymm; + } + @Override + public boolean ok(Data data) { + int dym = data.yr_mon; + for(int ym:yyyymm) { + if(dym==ym) { + return true; + } + } + return false; + } + + }; + } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java index 4778331b..5d7aebed 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java @@ -50,7 +50,7 @@ import com.datastax.driver.core.Row; */ public class LocateDAO extends CassDAOImpl { public static final String TABLE = "locate"; - private AbsCassDAO.PSInfo psName; + private AbsCassDAO.PSInfo psName; public LocateDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { super(trans, LocateDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); @@ -63,68 +63,68 @@ public class LocateDAO extends CassDAOImpl { } public static final int KEYLIMIT = 3; - public static class Data implements Bytification { - - public String name; - public String hostname; - public int port; - public int major; - public int minor; - public int patch; - public int pkg; - public float latitude; - public float longitude; - public String protocol; - private Set subprotocol; - public UUID port_key; // Note: Keep Port_key LAST at all times, because we shorten the UPDATE to leave Port_key Alone during reregistration. + public static class Data implements Bytification { + + public String name; + public String hostname; + public int port; + public int major; + public int minor; + public int patch; + public int pkg; + public float latitude; + public float longitude; + public String protocol; + private Set subprotocol; + public UUID port_key; // Note: Keep Port_key LAST at all times, because we shorten the UPDATE to leave Port_key Alone during reregistration. - // Getters - public Set subprotocol(boolean mutable) { - if (subprotocol == null) { - subprotocol = new HashSet<>(); - } else if (mutable && !(subprotocol instanceof HashSet)) { - subprotocol = new HashSet<>(subprotocol); - } - return subprotocol; - } - + // Getters + public Set subprotocol(boolean mutable) { + if (subprotocol == null) { + subprotocol = new HashSet<>(); + } else if (mutable && !(subprotocol instanceof HashSet)) { + subprotocol = new HashSet<>(subprotocol); + } + return subprotocol; + } + + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + LocateLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LocateLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - LocateLoader.deflt.unmarshal(this, toDIS(bb)); - } + public void reconstitute(ByteBuffer bb) throws IOException { + LocateLoader.deflt.unmarshal(this, toDIS(bb)); + } } private static class LocateLoader extends Loader implements Streamer{ - public static final int MAGIC=85102934; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; // Note: - - public static final LocateLoader deflt = new LocateLoader(KEYLIMIT); - public LocateLoader(int keylimit) { - super(keylimit); + public static final int MAGIC=85102934; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; // Note: + + public static final LocateLoader deflt = new LocateLoader(KEYLIMIT); + public LocateLoader(int keylimit) { + super(keylimit); } - @Override + @Override public Data load(Data data, Row row) { - data.name = row.getString(0); - data.hostname = row.getString(1); - data.port = row.getInt(2); - data.major = row.getInt(3); - data.minor = row.getInt(4); - data.patch = row.getInt(5); - data.pkg = row.getInt(6); - data.latitude = row.getFloat(7); - data.longitude = row.getFloat(8); - data.protocol = row.getString(9); - data.subprotocol = row.getSet(10,String.class); - data.port_key = row.getUUID(11); + data.name = row.getString(0); + data.hostname = row.getString(1); + data.port = row.getInt(2); + data.major = row.getInt(3); + data.minor = row.getInt(4); + data.patch = row.getInt(5); + data.pkg = row.getInt(6); + data.latitude = row.getFloat(7); + data.longitude = row.getFloat(8); + data.protocol = row.getString(9); + data.subprotocol = row.getSet(10,String.class); + data.port_key = row.getUUID(11); return data; } @@ -137,7 +137,7 @@ public class LocateDAO extends CassDAOImpl { @Override protected void body(final Data data, final int _idx, final Object[] obj) { - int idx = _idx; + int idx = _idx; obj[idx] = data.major; obj[++idx] = data.minor; obj[++idx] = data.patch; @@ -149,73 +149,73 @@ public class LocateDAO extends CassDAOImpl { obj[++idx] = data.port_key; } - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.name); - writeString(os, data.hostname); - os.writeInt(data.port); - os.writeInt(data.major); - os.writeInt(data.minor); - os.writeInt(data.patch); - os.writeInt(data.pkg); - os.writeFloat(data.latitude); - os.writeFloat(data.longitude); - writeString(os, data.protocol); - if(data.subprotocol==null) { - os.writeInt(0); - } else { - os.writeInt(data.subprotocol.size()); - for(String s: data.subprotocol) { - writeString(os,s); - } - } - - writeString(os,data.port_key==null?"":data.port_key.toString()); - } + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.name); + writeString(os, data.hostname); + os.writeInt(data.port); + os.writeInt(data.major); + os.writeInt(data.minor); + os.writeInt(data.patch); + os.writeInt(data.pkg); + os.writeFloat(data.latitude); + os.writeFloat(data.longitude); + writeString(os, data.protocol); + if(data.subprotocol==null) { + os.writeInt(0); + } else { + os.writeInt(data.subprotocol.size()); + for(String s: data.subprotocol) { + writeString(os,s); + } + } + + writeString(os,data.port_key==null?"":data.port_key.toString()); + } - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.name = readString(is,buff); - data.hostname = readString(is,buff); - data.port = is.readInt(); - data.major = is.readInt(); - data.minor = is.readInt(); - data.patch = is.readInt(); - data.pkg = is.readInt(); - data.latitude = is.readFloat(); - data.longitude = is.readFloat(); - data.protocol = readString(is,buff); - - int size = is.readInt(); - data.subprotocol = new HashSet<>(size); - for(int i=0;i0) { - data.port_key=UUID.fromString(port_key); - } else { - data.port_key = null; - } - } + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; + data.name = readString(is,buff); + data.hostname = readString(is,buff); + data.port = is.readInt(); + data.major = is.readInt(); + data.minor = is.readInt(); + data.patch = is.readInt(); + data.pkg = is.readInt(); + data.latitude = is.readFloat(); + data.longitude = is.readFloat(); + data.protocol = readString(is,buff); + + int size = is.readInt(); + data.subprotocol = new HashSet<>(size); + for(int i=0;i0) { + data.port_key=UUID.fromString(port_key); + } else { + data.port_key = null; + } + } } public Result> readByName(AuthzTrans trans, String service) { - return psName.read(trans, "Read By Name", new Object[] {service}); + return psName.read(trans, "Read By Name", new Object[] {service}); } private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs - String[] helpers = setCRUD(trans, TABLE, Data.class, LocateLoader.deflt); -// int lastComma = helpers[ASSIGNMENT_COMMAS].lastIndexOf(','); -// replace(CRUD.update,new PSInfo(trans,"UPDATE LOCATE SET " + helpers[ASSIGNMENT_COMMAS].substring(0, lastComma) + -// " WHERE name=? AND hostname=? AND port=?;", new LocateLoader(3),writeConsistency)); - psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE name = ?", new LocateLoader(1),readConsistency); + String[] helpers = setCRUD(trans, TABLE, Data.class, LocateLoader.deflt); +// int lastComma = helpers[ASSIGNMENT_COMMAS].lastIndexOf(','); +// replace(CRUD.update,new PSInfo(trans,"UPDATE LOCATE SET " + helpers[ASSIGNMENT_COMMAS].substring(0, lastComma) + +// " WHERE name=? AND hostname=? AND port=?;", new LocateLoader(3),writeConsistency)); + psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE name = ?", new LocateLoader(1),readConsistency); } /** diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java index 11ee4bcb..29ac379b 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java @@ -37,114 +37,114 @@ import org.onap.aaf.auth.rserv.Pair; public class Namespace implements Bytification { - public static final int MAGIC=250935515; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; + public static final int MAGIC=250935515; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; - public String name; - public List owner; - public List admin; - public List> attrib; - public String description; - public Integer type; - public String parent; - public Namespace() {} - - public Namespace(NsDAO.Data ndd) { - name = ndd.name; - description = ndd.description; - type = ndd.type; - parent = ndd.parent; - if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { - attrib = new ArrayList<>(); - for( Entry entry : ndd.attrib.entrySet()) { - attrib.add(new Pair(entry.getKey(),entry.getValue())); - } - } - } - - public Namespace(NsDAO.Data ndd,List owner, List admin) { - name = ndd.name; - this.owner = owner; - this.admin = admin; - description = ndd.description; - type = ndd.type; - parent = ndd.parent; - if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { - attrib = new ArrayList<>(); - for( Entry entry : ndd.attrib.entrySet()) { - attrib.add(new Pair(entry.getKey(),entry.getValue())); - } - } - } + public String name; + public List owner; + public List admin; + public List> attrib; + public String description; + public Integer type; + public String parent; + public Namespace() {} + + public Namespace(NsDAO.Data ndd) { + name = ndd.name; + description = ndd.description; + type = ndd.type; + parent = ndd.parent; + if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { + attrib = new ArrayList<>(); + for( Entry entry : ndd.attrib.entrySet()) { + attrib.add(new Pair(entry.getKey(),entry.getValue())); + } + } + } + + public Namespace(NsDAO.Data ndd,List owner, List admin) { + name = ndd.name; + this.owner = owner; + this.admin = admin; + description = ndd.description; + type = ndd.type; + parent = ndd.parent; + if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { + attrib = new ArrayList<>(); + for( Entry entry : ndd.attrib.entrySet()) { + attrib.add(new Pair(entry.getKey(),entry.getValue())); + } + } + } - public NsDAO.Data data() { - NsDAO.Data ndd = new NsDAO.Data(); - ndd.name = name; - ndd.description = description; - ndd.parent = parent; - ndd.type = type; - return ndd; - } + public NsDAO.Data data() { + NsDAO.Data ndd = new NsDAO.Data(); + ndd.name = name; + ndd.description = description; + ndd.parent = parent; + ndd.type = type; + return ndd; + } - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(baos); + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream os = new DataOutputStream(baos); - Loader.writeHeader(os,MAGIC,VERSION); - Loader.writeString(os, name); - os.writeInt(type); - Loader.writeStringSet(os,admin); - Loader.writeStringSet(os,owner); - Loader.writeString(os,description); - Loader.writeString(os,parent); + Loader.writeHeader(os,MAGIC,VERSION); + Loader.writeString(os, name); + os.writeInt(type); + Loader.writeStringSet(os,admin); + Loader.writeStringSet(os,owner); + Loader.writeString(os,description); + Loader.writeString(os,parent); - return ByteBuffer.wrap(baos.toByteArray()); - } + return ByteBuffer.wrap(baos.toByteArray()); + } - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - DataInputStream is = CassDAOImpl.toDIS(bb); - /*int version = */Loader.readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - - byte[] buff = new byte[BUFF_SIZE]; - name = Loader.readString(is, buff); - type = is.readInt(); - admin = Loader.readStringList(is,buff); - owner = Loader.readStringList(is,buff); - description = Loader.readString(is,buff); - parent = Loader.readString(is,buff); - - } + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + DataInputStream is = CassDAOImpl.toDIS(bb); + /*int version = */Loader.readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + + byte[] buff = new byte[BUFF_SIZE]; + name = Loader.readString(is, buff); + type = is.readInt(); + admin = Loader.readStringList(is,buff); + owner = Loader.readStringList(is,buff); + description = Loader.readString(is,buff); + parent = Loader.readString(is,buff); + + } - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return name.hashCode(); - } - + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return name.hashCode(); + } + - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return name.toString(); - } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return name.toString(); + } - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object arg0) { - if(arg0==null || !(arg0 instanceof Namespace)) { - return false; - } - return name.equals(((Namespace)arg0).name); - } + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object arg0) { + if(arg0==null || !(arg0 instanceof Namespace)) { + return false; + } + return name.equals(((Namespace)arg0).name); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java index 07890544..30f0d6b5 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java @@ -61,33 +61,33 @@ import com.datastax.driver.core.exceptions.DriverException; * */ public class NsDAO extends CassDAOImpl { - public static final String TABLE = "ns"; - public static final String TABLE_ATTRIB = "ns_attrib"; + public static final String TABLE = "ns"; + public static final String TABLE_ATTRIB = "ns_attrib"; public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F public static final int ROOT = 1; public static final int COMPANY=2; public static final int APP = 3; - private static final String BEGIN_BATCH = "BEGIN BATCH\n"; - private static final String APPLY_BATCH = "\nAPPLY BATCH;\n"; - private static final String SQSCCR = "';\n"; - private static final String SQCSQ = "','"; + private static final String BEGIN_BATCH = "BEGIN BATCH\n"; + private static final String APPLY_BATCH = "\nAPPLY BATCH;\n"; + private static final String SQSCCR = "';\n"; + private static final String SQCSQ = "','"; - private HistoryDAO historyDAO; - private CacheInfoDAO infoDAO; - private PSInfo psNS; + private HistoryDAO historyDAO; + private CacheInfoDAO infoDAO; + private PSInfo psNS; - public NsDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { - super(trans, NsDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - init(trans); - } + public NsDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { + super(trans, NsDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + init(trans); + } - public NsDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO iDAO) throws APIException, IOException { - super(trans, NsDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - historyDAO=hDAO; - infoDAO = iDAO; - init(trans); - } + public NsDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO iDAO) throws APIException, IOException { + super(trans, NsDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + historyDAO=hDAO; + infoDAO = iDAO; + init(trans); + } ////////////////////////////////////////// @@ -99,428 +99,428 @@ public class NsDAO extends CassDAOImpl { * * @author Jonathan */ - public static class Data extends CacheableData implements Bytification { - public String name; - public int type; - public String description; - public String parent; - public Map attrib; - -// //////////////////////////////////////// + public static class Data extends CacheableData implements Bytification { + public String name; + public int type; + public String description; + public String parent; + public Map attrib; + +// //////////////////////////////////////// // // Getters - public Map attrib(boolean mutable) { - if (attrib == null) { - attrib = new HashMap<>(); - } else if (mutable && !(attrib instanceof HashMap)) { - attrib = new HashMap<>(attrib); - } - return attrib; - } - - @Override - public int[] invalidate(Cached cache) { - return new int[] { - seg(cache,name) - }; - } - - public NsSplit split(String name) { - return new NsSplit(this,name); - } - - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - NSLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - NSLoader.deflt.unmarshal(this,toDIS(bb)); - } - - @Override - public String toString() { - return name; - } - + public Map attrib(boolean mutable) { + if (attrib == null) { + attrib = new HashMap<>(); + } else if (mutable && !(attrib instanceof HashMap)) { + attrib = new HashMap<>(attrib); + } + return attrib; + } + + @Override + public int[] invalidate(Cached cache) { + return new int[] { + seg(cache,name) + }; + } + + public NsSplit split(String name) { + return new NsSplit(this,name); + } + + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + NSLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + NSLoader.deflt.unmarshal(this,toDIS(bb)); + } + + @Override + public String toString() { + return name; + } + } private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs if(historyDAO==null) { - historyDAO = new HistoryDAO(trans, this); - } + historyDAO = new HistoryDAO(trans, this); + } if(infoDAO==null) { - infoDAO = new CacheInfoDAO(trans,this); - } + infoDAO = new CacheInfoDAO(trans,this); + } - String[] helpers = setCRUD(trans, TABLE, Data.class, NSLoader.deflt,4/*need to skip attrib */); - - psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE parent = ?", new NSLoader(1),readConsistency); + String[] helpers = setCRUD(trans, TABLE, Data.class, NSLoader.deflt,4/*need to skip attrib */); + + psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE parent = ?", new NSLoader(1),readConsistency); - } - + } + private static final class NSLoader extends Loader implements Streamer { - public static final int MAGIC=250935515; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; - - public static final NSLoader deflt = new NSLoader(KEYLIMIT); - - public NSLoader(int keylimit) { - super(keylimit); - } - - @Override - public Data load(Data data, Row row) { - // Int more efficient - data.name = row.getString(0); - data.type = row.getInt(1); - data.description = row.getString(2); - data.parent = row.getString(3); - return data; - } - - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.name; - } - - @Override - protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; - - obj[idx]=data.type; - obj[++idx]=data.description; - obj[++idx]=data.parent; - } - - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.name); - os.writeInt(data.type); - writeString(os,data.description); - writeString(os,data.parent); - if(data.attrib==null) { - os.writeInt(-1); - } else { - os.writeInt(data.attrib.size()); - for(Entry es : data.attrib(false).entrySet()) { - writeString(os,es.getKey()); - writeString(os,es.getValue()); - } - } - } - - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - - byte[] buff = new byte[BUFF_SIZE]; - data.name = readString(is, buff); - data.type = is.readInt(); - data.description = readString(is,buff); - data.parent = readString(is,buff); - int count = is.readInt(); - if(count>0) { - Map da = data.attrib(true); - for(int i=0;i es : data.attrib(false).entrySet()) { + writeString(os,es.getKey()); + writeString(os,es.getValue()); + } + } + } + + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + + byte[] buff = new byte[BUFF_SIZE]; + data.name = readString(is, buff); + data.type = is.readInt(); + data.description = readString(is,buff); + data.parent = readString(is,buff); + int count = is.readInt(); + if(count>0) { + Map da = data.attrib(true); + for(int i=0;i create(AuthzTrans trans, Data data) { - String ns = data.name; - // Ensure Parent is set - if(data.parent==null) { - return Result.err(Result.ERR_BadData, "Need parent for %s", ns); - } - - // insert Attributes - StringBuilder stmt = new StringBuilder(); - stmt.append(BEGIN_BATCH); - attribInsertStmts(stmt, data); - stmt.append(APPLY_BATCH); - try { - getSession(trans).execute(stmt.toString()); -//// TEST CODE for Exception -// boolean force = true; -// if(force) { -// throw new com.datastax.driver.core.exceptions.NoHostAvailableException(new HashMap<>()); -//// throw new com.datastax.driver.core.exceptions.AuthenticationException(new InetSocketAddress(9999),"Sample Message"); -// } + @Override + public Result create(AuthzTrans trans, Data data) { + String ns = data.name; + // Ensure Parent is set + if(data.parent==null) { + return Result.err(Result.ERR_BadData, "Need parent for %s", ns); + } + + // insert Attributes + StringBuilder stmt = new StringBuilder(); + stmt.append(BEGIN_BATCH); + attribInsertStmts(stmt, data); + stmt.append(APPLY_BATCH); + try { + getSession(trans).execute(stmt.toString()); +//// TEST CODE for Exception +// boolean force = true; +// if(force) { +// throw new com.datastax.driver.core.exceptions.NoHostAvailableException(new HashMap<>()); +//// throw new com.datastax.driver.core.exceptions.AuthenticationException(new InetSocketAddress(9999),"Sample Message"); +// } ////END TEST CODE - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - trans.info().log(stmt); - return Result.err(Result.ERR_Backend, "Backend Access"); - } - return super.create(trans, data); - } - - @Override - public Result update(AuthzTrans trans, Data data) { - String ns = data.name; - // Ensure Parent is set - if(data.parent==null) { - return Result.err(Result.ERR_BadData, "Need parent for %s", ns); - } - - StringBuilder stmt = new StringBuilder(); - stmt.append(BEGIN_BATCH); - try { - Map localAttr = data.attrib; - Result> rremoteAttr = readAttribByNS(trans,ns); - if(rremoteAttr.notOK()) { - return Result.err(rremoteAttr); - } - // update Attributes - String str; - for(Entry es : localAttr.entrySet()) { - str = rremoteAttr.value.get(es.getKey()); - if(str==null || !str.equals(es.getValue())) { - attribUpdateStmt(stmt, ns, es.getKey(),es.getValue()); - } - } - - // No point in deleting... insert overwrites... -// for(Entry es : remoteAttr.entrySet()) { -// str = localAttr.get(es.getKey()); -// if(str==null || !str.equals(es.getValue())) { -// attribDeleteStmt(stmt, ns, es.getKey()); -// } -// } - if(stmt.length()>BEGIN_BATCH.length()) { - stmt.append(APPLY_BATCH); - getSession(trans).execute(stmt.toString()); - } - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - trans.info().log(stmt); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - return super.update(trans,data); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.CassDAOImpl#read(com.att.inno.env.TransStore, java.lang.Object) - */ - @Override - public Result> read(AuthzTrans trans, Data data) { - Result> rld = super.read(trans, data); - - if(rld.isOKhasData()) { - for(Data d : rld.value) { - // Note: Map is null at this point, save time/mem by assignment - Result> rabn = readAttribByNS(trans,d.name); - if(rabn.isOK()) { - d.attrib = rabn.value; - } else { - return Result.err(rabn); - } - } - } - return rld; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.CassDAOImpl#read(com.att.inno.env.TransStore, java.lang.Object[]) - */ - @Override - public Result> read(AuthzTrans trans, Object... key) { - Result> rld = super.read(trans, key); - - if(rld.isOKhasData()) { - for(Data d : rld.value) { - // Note: Map is null at this point, save time/mem by assignment - Result> rabn = readAttribByNS(trans,d.name); - if(rabn.isOK()) { - d.attrib = rabn.value; - } else { - return Result.err(rabn); - } - } - } - return rld; - } - - @Override - public Result delete(AuthzTrans trans, Data data, boolean reread) { - TimeTaken tt = trans.start("Delete NS Attributes " + data.name, Env.REMOTE); - try { - StringBuilder stmt = new StringBuilder(); - attribDeleteAllStmt(stmt, data); - try { - getSession(trans).execute(stmt.toString()); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - trans.info().log(stmt); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - } finally { - tt.done(); - } - return super.delete(trans, data, reread); - - } + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + trans.info().log(stmt); + return Result.err(Result.ERR_Backend, "Backend Access"); + } + return super.create(trans, data); + } + + @Override + public Result update(AuthzTrans trans, Data data) { + String ns = data.name; + // Ensure Parent is set + if(data.parent==null) { + return Result.err(Result.ERR_BadData, "Need parent for %s", ns); + } + + StringBuilder stmt = new StringBuilder(); + stmt.append(BEGIN_BATCH); + try { + Map localAttr = data.attrib; + Result> rremoteAttr = readAttribByNS(trans,ns); + if(rremoteAttr.notOK()) { + return Result.err(rremoteAttr); + } + // update Attributes + String str; + for(Entry es : localAttr.entrySet()) { + str = rremoteAttr.value.get(es.getKey()); + if(str==null || !str.equals(es.getValue())) { + attribUpdateStmt(stmt, ns, es.getKey(),es.getValue()); + } + } + + // No point in deleting... insert overwrites... +// for(Entry es : remoteAttr.entrySet()) { +// str = localAttr.get(es.getKey()); +// if(str==null || !str.equals(es.getValue())) { +// attribDeleteStmt(stmt, ns, es.getKey()); +// } +// } + if(stmt.length()>BEGIN_BATCH.length()) { + stmt.append(APPLY_BATCH); + getSession(trans).execute(stmt.toString()); + } + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + trans.info().log(stmt); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + return super.update(trans,data); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.dao.CassDAOImpl#read(com.att.inno.env.TransStore, java.lang.Object) + */ + @Override + public Result> read(AuthzTrans trans, Data data) { + Result> rld = super.read(trans, data); + + if(rld.isOKhasData()) { + for(Data d : rld.value) { + // Note: Map is null at this point, save time/mem by assignment + Result> rabn = readAttribByNS(trans,d.name); + if(rabn.isOK()) { + d.attrib = rabn.value; + } else { + return Result.err(rabn); + } + } + } + return rld; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.dao.CassDAOImpl#read(com.att.inno.env.TransStore, java.lang.Object[]) + */ + @Override + public Result> read(AuthzTrans trans, Object... key) { + Result> rld = super.read(trans, key); + + if(rld.isOKhasData()) { + for(Data d : rld.value) { + // Note: Map is null at this point, save time/mem by assignment + Result> rabn = readAttribByNS(trans,d.name); + if(rabn.isOK()) { + d.attrib = rabn.value; + } else { + return Result.err(rabn); + } + } + } + return rld; + } + + @Override + public Result delete(AuthzTrans trans, Data data, boolean reread) { + TimeTaken tt = trans.start("Delete NS Attributes " + data.name, Env.REMOTE); + try { + StringBuilder stmt = new StringBuilder(); + attribDeleteAllStmt(stmt, data); + try { + getSession(trans).execute(stmt.toString()); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + trans.info().log(stmt); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + } finally { + tt.done(); + } + return super.delete(trans, data, reread); + + } - public Result> readAttribByNS(AuthzTrans trans, String ns) { - Map map = new HashMap<>(); - TimeTaken tt = trans.start("readAttribByNS " + ns, Env.REMOTE); - try { - ResultSet rs = getSession(trans).execute("SELECT key,value FROM " - + TABLE_ATTRIB - + " WHERE ns='" - + ns - + "';"); - - for(Iterator iter = rs.iterator();iter.hasNext(); ) { - Row r = iter.next(); - map.put(r.getString(0), r.getString(1)); - } - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } finally { - tt.done(); - } - return Result.ok(map); - } - - public Result> readNsByAttrib(AuthzTrans trans, String key) { - Set set = new HashSet<>(); - TimeTaken tt = trans.start("readNsBykey " + key, Env.REMOTE); - try { - ResultSet rs = getSession(trans).execute("SELECT ns FROM " - + TABLE_ATTRIB - + " WHERE key='" - + key - + "';"); - - for(Iterator iter = rs.iterator();iter.hasNext(); ) { - Row r = iter.next(); - set.add(r.getString(0)); - } - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } finally { - tt.done(); - } - return Result.ok(set); - } - - public Result attribAdd(AuthzTrans trans, String ns, String key, String value) { - try { - getSession(trans).execute(attribInsertStmt(new StringBuilder(),ns,key,value).toString()); - return Result.ok(); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - } - - private StringBuilder attribInsertStmt(StringBuilder sb, String ns, String key, String value) { - sb.append("INSERT INTO "); - sb.append(TABLE_ATTRIB); - sb.append(" (ns,key,value) VALUES ('"); - sb.append(ns); - sb.append(SQCSQ); - sb.append(key); - sb.append(SQCSQ); - sb.append(value); - sb.append("');"); - return sb; - } - - private StringBuilder attribUpdateStmt(StringBuilder sb, String ns, String key, String value) { - sb.append("UPDATE "); - sb.append(TABLE_ATTRIB); - sb.append(" set value='"); - sb.append(value); - sb.append("' where ns='"); - sb.append(ns); - sb.append("' AND key='"); - sb.append(key); - sb.append("';"); - return sb; - } - - - public Result attribRemove(AuthzTrans trans, String ns, String key) { - try { - getSession(trans).execute(attribDeleteStmt(new StringBuilder(),ns,key).toString()); - return Result.ok(); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - } - - private StringBuilder attribDeleteStmt(StringBuilder stmt, String ns, String key) { - stmt.append("DELETE FROM "); - stmt.append(TABLE_ATTRIB); - stmt.append(" WHERE ns='"); - stmt.append(ns); - stmt.append("' AND key='"); - stmt.append(key); - stmt.append("';"); - return stmt; - } - - private void attribDeleteAllStmt(StringBuilder stmt, Data data) { - stmt.append(" DELETE FROM "); - stmt.append(TABLE_ATTRIB); - stmt.append(" WHERE ns='"); - stmt.append(data.name); - stmt.append(SQSCCR); - } - - private void attribInsertStmts(StringBuilder stmt, Data data) { - // INSERT new Attrib - for(Entry es : data.attrib(false).entrySet() ) { - stmt.append(" "); - attribInsertStmt(stmt,data.name,es.getKey(),es.getValue()); - } - } - - /** - * Add description to Namespace - * @param trans - * @param ns - * @param description - * @return - */ - public Result addDescription(AuthzTrans trans, String ns, String description) { - try { - getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" - + description.replace("'", "''") + "' WHERE name = '" + ns + "';"); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - Data data = new Data(); - data.name=ns; - wasModified(trans, CRUD.update, data, "Added description " + description + " to namespace " + ns, null ); - return Result.ok(); - } - - public Result> getChildren(AuthzTrans trans, String parent) { - return psNS.read(trans, R_TEXT, new Object[]{parent}); - } - + public Result> readAttribByNS(AuthzTrans trans, String ns) { + Map map = new HashMap<>(); + TimeTaken tt = trans.start("readAttribByNS " + ns, Env.REMOTE); + try { + ResultSet rs = getSession(trans).execute("SELECT key,value FROM " + + TABLE_ATTRIB + + " WHERE ns='" + + ns + + "';"); + + for(Iterator iter = rs.iterator();iter.hasNext(); ) { + Row r = iter.next(); + map.put(r.getString(0), r.getString(1)); + } + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } finally { + tt.done(); + } + return Result.ok(map); + } + + public Result> readNsByAttrib(AuthzTrans trans, String key) { + Set set = new HashSet<>(); + TimeTaken tt = trans.start("readNsBykey " + key, Env.REMOTE); + try { + ResultSet rs = getSession(trans).execute("SELECT ns FROM " + + TABLE_ATTRIB + + " WHERE key='" + + key + + "';"); + + for(Iterator iter = rs.iterator();iter.hasNext(); ) { + Row r = iter.next(); + set.add(r.getString(0)); + } + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } finally { + tt.done(); + } + return Result.ok(set); + } + + public Result attribAdd(AuthzTrans trans, String ns, String key, String value) { + try { + getSession(trans).execute(attribInsertStmt(new StringBuilder(),ns,key,value).toString()); + return Result.ok(); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + } + + private StringBuilder attribInsertStmt(StringBuilder sb, String ns, String key, String value) { + sb.append("INSERT INTO "); + sb.append(TABLE_ATTRIB); + sb.append(" (ns,key,value) VALUES ('"); + sb.append(ns); + sb.append(SQCSQ); + sb.append(key); + sb.append(SQCSQ); + sb.append(value); + sb.append("');"); + return sb; + } + + private StringBuilder attribUpdateStmt(StringBuilder sb, String ns, String key, String value) { + sb.append("UPDATE "); + sb.append(TABLE_ATTRIB); + sb.append(" set value='"); + sb.append(value); + sb.append("' where ns='"); + sb.append(ns); + sb.append("' AND key='"); + sb.append(key); + sb.append("';"); + return sb; + } + + + public Result attribRemove(AuthzTrans trans, String ns, String key) { + try { + getSession(trans).execute(attribDeleteStmt(new StringBuilder(),ns,key).toString()); + return Result.ok(); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + } + + private StringBuilder attribDeleteStmt(StringBuilder stmt, String ns, String key) { + stmt.append("DELETE FROM "); + stmt.append(TABLE_ATTRIB); + stmt.append(" WHERE ns='"); + stmt.append(ns); + stmt.append("' AND key='"); + stmt.append(key); + stmt.append("';"); + return stmt; + } + + private void attribDeleteAllStmt(StringBuilder stmt, Data data) { + stmt.append(" DELETE FROM "); + stmt.append(TABLE_ATTRIB); + stmt.append(" WHERE ns='"); + stmt.append(data.name); + stmt.append(SQSCCR); + } + + private void attribInsertStmts(StringBuilder stmt, Data data) { + // INSERT new Attrib + for(Entry es : data.attrib(false).entrySet() ) { + stmt.append(" "); + attribInsertStmt(stmt,data.name,es.getKey(),es.getValue()); + } + } + + /** + * Add description to Namespace + * @param trans + * @param ns + * @param description + * @return + */ + public Result addDescription(AuthzTrans trans, String ns, String description) { + try { + getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" + + description.replace("'", "''") + "' WHERE name = '" + ns + "';"); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + Data data = new Data(); + data.name=ns; + wasModified(trans, CRUD.update, data, "Added description " + description + " to namespace " + ns, null ); + return Result.ok(); + } + + public Result> getChildren(AuthzTrans trans, String parent) { + return psNS.read(trans, R_TEXT, new Object[]{parent}); + } + /** * Log Modification statements to History @@ -531,8 +531,8 @@ public class NsDAO extends CassDAOImpl { */ @Override protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; //TODO Must log history HistoryDAO.Data hd = HistoryDAO.newInitedData(); @@ -541,20 +541,20 @@ public class NsDAO extends CassDAOImpl { hd.target = TABLE; hd.subject = subject ? override[1] : data.name; hd.memo = memo ? override[0] : (data.name + " was " + modified.name() + 'd' ); - if(modified==CRUD.delete) { - try { - hd.reconstruct = data.bytify(); - } catch (IOException e) { - trans.error().log(e,"Could not serialize NsDAO.Data"); - } - } + if(modified==CRUD.delete) { + try { + hd.reconstruct = data.bytify(); + } catch (IOException e) { + trans.error().log(e,"Could not serialize NsDAO.Data"); + } + } if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); - } + trans.error().log("Cannot log to History"); + } if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { - trans.error().log("Cannot touch CacheInfo"); - } + trans.error().log("Cannot touch CacheInfo"); + } } } \ No newline at end of file diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java index 2694c6c8..a64c0a94 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java @@ -22,40 +22,40 @@ package org.onap.aaf.auth.dao.cass; public class NsSplit { - public final String ns; - public final String name; - public final NsDAO.Data nsd; - - public NsSplit(NsDAO.Data nsd, String child) { - this.nsd = nsd; - if(child.startsWith(nsd.name)) { - ns = nsd.name; - int dot = ns.length(); - if(dot=0) { - nsd.parent = ns.substring(0, dot); - } else { - nsd.parent = "."; - } - } + public final String ns; + public final String name; + public final NsDAO.Data nsd; + + public NsSplit(NsDAO.Data nsd, String child) { + this.nsd = nsd; + if(child.startsWith(nsd.name)) { + ns = nsd.name; + int dot = ns.length(); + if(dot=0) { + nsd.parent = ns.substring(0, dot); + } else { + nsd.parent = "."; + } + } - public boolean isOK() { - return ns!=null && name !=null; - } + public boolean isOK() { + return ns!=null && name !=null; + } } \ No newline at end of file diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java index 18d5eeec..59e18ae9 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java @@ -27,48 +27,48 @@ package org.onap.aaf.auth.dao.cass; * */ public enum NsType { - UNKNOWN (-1), - DOT (0), - ROOT (1), - COMPANY (2), - APP (3), - STACKED_APP (10), - STACK (11); - - public final int type; - private NsType(int t) { - type = t; - } - /** - * This is not the Ordinal, but the Type that is stored in NS Tables - * - * @param t - * @return - */ - public static NsType fromType(int t) { - for(NsType nst : values()) { - if(t==nst.type) { - return nst; - } - } - return UNKNOWN; - } - - /** - * Use this one rather than "valueOf" to avoid Exception - * @param s - * @return - */ - public static NsType fromString(String s) { - if(s!=null) { - for(NsType nst : values()) { - if(nst.name().equals(s)) { - return nst; - } - } - } - return UNKNOWN; - } + UNKNOWN (-1), + DOT (0), + ROOT (1), + COMPANY (2), + APP (3), + STACKED_APP (10), + STACK (11); + + public final int type; + private NsType(int t) { + type = t; + } + /** + * This is not the Ordinal, but the Type that is stored in NS Tables + * + * @param t + * @return + */ + public static NsType fromType(int t) { + for(NsType nst : values()) { + if(t==nst.type) { + return nst; + } + } + return UNKNOWN; + } + + /** + * Use this one rather than "valueOf" to avoid Exception + * @param s + * @return + */ + public static NsType fromString(String s) { + if(s!=null) { + for(NsType nst : values()) { + if(nst.name().equals(s)) { + return nst; + } + } + } + return UNKNOWN; + } - + } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/OAuthTokenDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/OAuthTokenDAO.java index 4fe3aaab..5d0f084b 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/OAuthTokenDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/OAuthTokenDAO.java @@ -50,7 +50,7 @@ import com.datastax.driver.core.Row; */ public class OAuthTokenDAO extends CassDAOImpl { public static final String TABLE = "oauth_token"; - private AbsCassDAO.PSInfo psByUser; + private AbsCassDAO.PSInfo psByUser; public OAuthTokenDAO(AuthzTrans trans, Cluster cluster, String keyspace) { super(trans, OAuthTokenDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); @@ -58,63 +58,63 @@ public class OAuthTokenDAO extends CassDAOImpl { } public OAuthTokenDAO(AuthzTrans trans, AbsCassDAO aDao) { - super(trans, OAuthTokenDAO.class.getSimpleName(),aDao, Data.class, TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - init(trans); + super(trans, OAuthTokenDAO.class.getSimpleName(),aDao, Data.class, TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + init(trans); } public static final int KEYLIMIT = 1; - public static class Data implements Bytification { - public String id; - public String client_id; - public String user; - public boolean active; - public int type; - public String refresh; - public Date expires; - public long exp_sec; - public String content; - public Set scopes; - public String state; - public String req_ip; // requesting - - public Set scopes(boolean mutable) { - if (scopes == null) { - scopes = new HashSet<>(); - } else if (mutable && !(scopes instanceof HashSet)) { - scopes = new HashSet<>(scopes); - } - return scopes; - } - - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OAuthLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - OAuthLoader.deflt.unmarshal(this, toDIS(bb)); - } - - public String toString() { - return user.toString() + ' ' + id.toString() + ' ' + Chrono.dateTime(expires) + (active?"":"in") + "active"; - } + public static class Data implements Bytification { + public String id; + public String client_id; + public String user; + public boolean active; + public int type; + public String refresh; + public Date expires; + public long exp_sec; + public String content; + public Set scopes; + public String state; + public String req_ip; // requesting + + public Set scopes(boolean mutable) { + if (scopes == null) { + scopes = new HashSet<>(); + } else if (mutable && !(scopes instanceof HashSet)) { + scopes = new HashSet<>(scopes); + } + return scopes; + } + + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OAuthLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + OAuthLoader.deflt.unmarshal(this, toDIS(bb)); + } + + public String toString() { + return user.toString() + ' ' + id.toString() + ' ' + Chrono.dateTime(expires) + (active?"":"in") + "active"; + } } private static class OAuthLoader extends Loader implements Streamer{ - public static final int MAGIC=235677843; - public static final int VERSION=1; - public static final int BUFF_SIZE=96; // Note: only used when - - public static final OAuthLoader deflt = new OAuthLoader(KEYLIMIT); - public OAuthLoader(int keylimit) { - super(keylimit); - } - - @Override + public static final int MAGIC=235677843; + public static final int VERSION=1; + public static final int BUFF_SIZE=96; // Note: only used when + + public static final OAuthLoader deflt = new OAuthLoader(KEYLIMIT); + public OAuthLoader(int keylimit) { + super(keylimit); + } + + @Override public Data load(Data data, Row row) { data.id = row.getString(0); data.client_id = row.getString(1); @@ -152,43 +152,43 @@ public class OAuthTokenDAO extends CassDAOImpl { obj[++i] = data.req_ip; } - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.id); - writeString(os, data.client_id); - writeString(os, data.user); - os.writeBoolean(data.active); - os.writeInt(data.type); - writeString(os, data.refresh); - os.writeLong(data.expires==null?-1:data.expires.getTime()); - os.writeLong(data.exp_sec); - writeString(os, data.content); - writeStringSet(os,data.scopes); - writeString(os, data.state); - writeString(os, data.req_ip); - } - - - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; // used only if fits - data.id = readString(is,buff); - data.client_id = readString(is,buff); - data.user = readString(is,buff); - data.active = is.readBoolean(); - data.type = is.readInt(); - data.refresh = readString(is,buff); - long l = is.readLong(); - data.expires = l<0?null:new Date(l); - data.exp_sec = is.readLong(); - data.content = readString(is,buff); // note, large strings still ok with small buffer - data.scopes = readStringSet(is,buff); - data.state = readString(is,buff); - data.req_ip = readString(is,buff); - } + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.id); + writeString(os, data.client_id); + writeString(os, data.user); + os.writeBoolean(data.active); + os.writeInt(data.type); + writeString(os, data.refresh); + os.writeLong(data.expires==null?-1:data.expires.getTime()); + os.writeLong(data.exp_sec); + writeString(os, data.content); + writeStringSet(os,data.scopes); + writeString(os, data.state); + writeString(os, data.req_ip); + } + + + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; // used only if fits + data.id = readString(is,buff); + data.client_id = readString(is,buff); + data.user = readString(is,buff); + data.active = is.readBoolean(); + data.type = is.readInt(); + data.refresh = readString(is,buff); + long l = is.readLong(); + data.expires = l<0?null:new Date(l); + data.exp_sec = is.readLong(); + data.content = readString(is,buff); // note, large strings still ok with small buffer + data.scopes = readStringSet(is,buff); + data.state = readString(is,buff); + data.req_ip = readString(is,buff); + } } private void init(AuthzTrans trans) { @@ -196,7 +196,7 @@ public class OAuthTokenDAO extends CassDAOImpl { psByUser = new PSInfo(trans, "SELECT " + helpers[0] + " from " + TABLE + " WHERE user=?",OAuthLoader.deflt,readConsistency); } - /** + /** * Log Modification statements to History * * @param modified which CRUD action was done @@ -207,7 +207,7 @@ public class OAuthTokenDAO extends CassDAOImpl { protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { } - public Result> readByUser(AuthzTrans trans, String user) { - return psByUser.read(trans, "Read By User", new Object[]{user}); - } + public Result> readByUser(AuthzTrans trans, String user) { + return psByUser.read(trans, "Read By User", new Object[]{user}); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java index 0ecdd98d..c02387b1 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java @@ -49,169 +49,169 @@ import com.datastax.driver.core.exceptions.DriverException; public class PermDAO extends CassDAOImpl { - public static final String TABLE = "perm"; + public static final String TABLE = "perm"; public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F - private static final String STAR = "*"; - - private final HistoryDAO historyDAO; - private final CacheInfoDAO infoDAO; - - private PSInfo psNS, psChildren, psByType; - - public PermDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { - super(trans, PermDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - init(trans); - historyDAO = new HistoryDAO(trans, this); - infoDAO = new CacheInfoDAO(trans,this); - } - - public PermDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) { - super(trans, PermDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - historyDAO = hDAO; - infoDAO=ciDAO; - init(trans); - } - - - private static final int KEYLIMIT = 4; - public static class Data extends CacheableData implements Bytification { - public String ns; - public String type; - public String instance; - public String action; - public Set roles; - public String description; - - public Data() {} - - public Data(NsSplit nss, String instance, String action) { - ns = nss.ns; - type = nss.name; - this.instance = instance; - this.action = action; - } - - public String fullType() { - return ns + '.' + type; - } - - public String fullPerm() { - return ns + '.' + type + '|' + instance + '|' + action; - } - - public String encode() { - return ns + '|' + type + '|' + instance + '|' + action; - } - - /** - * Decode Perm String, including breaking into appropriate Namespace - * - * @param trans - * @param q - * @param p - * @return - */ - public static Result decode(AuthzTrans trans, Question q, String p) { - String[] ss = Split.splitTrim('|', p,4); - if(ss[2]==null) { - return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'"); - } - Data data = new Data(); - if(ss[3]==null) { // older 3 part encoding must be evaluated for NS - Result nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { - return Result.err(nss); - } - data.ns=nss.value.ns; - data.type=nss.value.name; - data.instance=ss[1]; - data.action=ss[2]; - } else { // new 4 part encoding - data.ns=ss[0]; - data.type=ss[1]; - data.instance=ss[2]; - data.action=ss[3]; - } - return Result.ok(data); - } - - /** - * Decode Perm String, including breaking into appropriate Namespace - * - * @param trans - * @param q - * @param p - * @return - */ - public static Result decodeToArray(AuthzTrans trans, Question q, String p) { - String[] ss = Split.splitTrim('|', p,4); - if(ss[2]==null) { - return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'"); - } - - if(ss[3]==null) { // older 3 part encoding must be evaluated for NS - ss[3] = ss[2]; - ss[2] = ss[1]; - Result nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { - return Result.err(nss); - } - ss[1] = nss.value.name; - ss[0] = nss.value.ns; - } - return Result.ok(ss); - } - - public static Data create(NsDAO.Data ns, String name) { - NsSplit nss = new NsSplit(ns,name); - Data rv = new Data(); - rv.ns = nss.ns; - String[] s = nss.name.split("\\|"); - switch(s.length) { - case 3: - rv.type=s[0]; - rv.instance=s[1]; - rv.action=s[2]; - break; - case 2: - rv.type=s[0]; - rv.instance=s[1]; - rv.action=STAR; - break; - default: - rv.type=s[0]; - rv.instance = STAR; - rv.action = STAR; - } - return rv; - } - - public static Data create(AuthzTrans trans, Question q, String name) { - String[] s = name.split("\\|"); - Result rdns = q.deriveNsSplit(trans, s[0]); - Data rv = new PermDAO.Data(); - if(rdns.isOKhasData()) { - switch(s.length) { - case 3: - rv.type=s[1]; - rv.instance=s[2]; - rv.action=s[3]; - break; - case 2: - rv.type=s[1]; - rv.instance=s[2]; - rv.action=STAR; - break; - default: - rv.type=s[1]; - rv.instance = STAR; - rv.action = STAR; - } - } - return rv; - } - + private static final String STAR = "*"; + + private final HistoryDAO historyDAO; + private final CacheInfoDAO infoDAO; + + private PSInfo psNS, psChildren, psByType; + + public PermDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { + super(trans, PermDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + init(trans); + historyDAO = new HistoryDAO(trans, this); + infoDAO = new CacheInfoDAO(trans,this); + } + + public PermDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) { + super(trans, PermDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + historyDAO = hDAO; + infoDAO=ciDAO; + init(trans); + } + + + private static final int KEYLIMIT = 4; + public static class Data extends CacheableData implements Bytification { + public String ns; + public String type; + public String instance; + public String action; + public Set roles; + public String description; + + public Data() {} + + public Data(NsSplit nss, String instance, String action) { + ns = nss.ns; + type = nss.name; + this.instance = instance; + this.action = action; + } + + public String fullType() { + return ns + '.' + type; + } + + public String fullPerm() { + return ns + '.' + type + '|' + instance + '|' + action; + } + + public String encode() { + return ns + '|' + type + '|' + instance + '|' + action; + } + + /** + * Decode Perm String, including breaking into appropriate Namespace + * + * @param trans + * @param q + * @param p + * @return + */ + public static Result decode(AuthzTrans trans, Question q, String p) { + String[] ss = Split.splitTrim('|', p,4); + if(ss[2]==null) { + return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'"); + } + Data data = new Data(); + if(ss[3]==null) { // older 3 part encoding must be evaluated for NS + Result nss = q.deriveNsSplit(trans, ss[0]); + if(nss.notOK()) { + return Result.err(nss); + } + data.ns=nss.value.ns; + data.type=nss.value.name; + data.instance=ss[1]; + data.action=ss[2]; + } else { // new 4 part encoding + data.ns=ss[0]; + data.type=ss[1]; + data.instance=ss[2]; + data.action=ss[3]; + } + return Result.ok(data); + } + + /** + * Decode Perm String, including breaking into appropriate Namespace + * + * @param trans + * @param q + * @param p + * @return + */ + public static Result decodeToArray(AuthzTrans trans, Question q, String p) { + String[] ss = Split.splitTrim('|', p,4); + if(ss[2]==null) { + return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'"); + } + + if(ss[3]==null) { // older 3 part encoding must be evaluated for NS + ss[3] = ss[2]; + ss[2] = ss[1]; + Result nss = q.deriveNsSplit(trans, ss[0]); + if(nss.notOK()) { + return Result.err(nss); + } + ss[1] = nss.value.name; + ss[0] = nss.value.ns; + } + return Result.ok(ss); + } + + public static Data create(NsDAO.Data ns, String name) { + NsSplit nss = new NsSplit(ns,name); + Data rv = new Data(); + rv.ns = nss.ns; + String[] s = nss.name.split("\\|"); + switch(s.length) { + case 3: + rv.type=s[0]; + rv.instance=s[1]; + rv.action=s[2]; + break; + case 2: + rv.type=s[0]; + rv.instance=s[1]; + rv.action=STAR; + break; + default: + rv.type=s[0]; + rv.instance = STAR; + rv.action = STAR; + } + return rv; + } + + public static Data create(AuthzTrans trans, Question q, String name) { + String[] s = name.split("\\|"); + Result rdns = q.deriveNsSplit(trans, s[0]); + Data rv = new PermDAO.Data(); + if(rdns.isOKhasData()) { + switch(s.length) { + case 3: + rv.type=s[1]; + rv.instance=s[2]; + rv.action=s[3]; + break; + case 2: + rv.type=s[1]; + rv.instance=s[2]; + rv.action=STAR; + break; + default: + rv.type=s[1]; + rv.instance = STAR; + rv.action = STAR; + } + } + return rv; + } + //////////////////////////////////////// // Getters public Set roles(boolean mutable) { @@ -223,279 +223,279 @@ public class PermDAO extends CassDAOImpl { return roles; } - @Override - public int[] invalidate(Cached cache) { - return new int[] { - seg(cache,ns), - seg(cache,ns,type), - seg(cache,ns,type,STAR), - seg(cache,ns,type,instance,action) - }; - } - - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PermLoader.deflt.marshal(this, new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - PermLoader.deflt.unmarshal(this, toDIS(bb)); - } - - @Override - public String toString() { - return encode(); - } - } - - private static class PermLoader extends Loader implements Streamer { - public static final int MAGIC=283939453; - public static final int VERSION=1; - public static final int BUFF_SIZE=96; - - public static final PermLoader deflt = new PermLoader(KEYLIMIT); - - public PermLoader(int keylimit) { - super(keylimit); - } - - @Override - public Data load(Data data, Row row) { - // Int more efficient Match "fields" string - data.ns = row.getString(0); - data.type = row.getString(1); - data.instance = row.getString(2); - data.action = row.getString(3); - data.roles = row.getSet(4,String.class); - data.description = row.getString(5); - return data; - } - - @Override - protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.ns; - obj[++idx]=data.type; - obj[++idx]=data.instance; - obj[++idx]=data.action; - } - - @Override - protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.roles; - obj[++idx]=data.description; - } - - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.ns); - writeString(os, data.type); - writeString(os, data.instance); - writeString(os, data.action); - writeStringSet(os, data.roles); - writeString(os, data.description); - } - - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.ns = readString(is, buff); - data.type = readString(is,buff); - data.instance = readString(is,buff); - data.action = readString(is,buff); - data.roles = readStringSet(is,buff); - data.description = readString(is,buff); - } - } - - private void init(AuthzTrans trans) { - // the 3 is the number of key fields - String[] helpers = setCRUD(trans, TABLE, Data.class, PermLoader.deflt); - - // Other SELECT style statements... match with a local Method - psByType = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE ns = ? AND type = ?", new PermLoader(2) { - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.type; - } - },readConsistency); - - psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE ns = ?", new PermLoader(1),readConsistency); - - psChildren = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE ns=? AND type > ? AND type < ?", - new PermLoader(3) { - @Override - protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx] = data.ns; - obj[++idx]=data.type + DOT; - obj[++idx]=data.type + DOT_PLUS_ONE; - } - },readConsistency); - - } - - - /** - * Add a single Permission to the Role's Permission Collection - * - * @param trans - * @param roleFullName - * @param perm - * @param type - * @param action - * @return - */ - public Result addRole(AuthzTrans trans, PermDAO.Data perm, String roleFullName) { - // Note: Prepared Statements for Collection updates aren't supported - //ResultSet rv = - try { - getSession(trans).execute(UPDATE_SP + TABLE + " SET roles = roles + {'" + roleFullName + "'} " + - "WHERE " + - "ns = '" + perm.ns + "' AND " + - "type = '" + perm.type + "' AND " + - "instance = '" + perm.instance + "' AND " + - "action = '" + perm.action + "';" - ); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - wasModified(trans, CRUD.update, perm, "Added role " + roleFullName + " to perm " + - perm.ns + '.' + perm.type + '|' + perm.instance + '|' + perm.action); - return Result.ok(); - } - - /** - * Remove a single Permission from the Role's Permission Collection - * @param trans - * @param roleFullName - * @param perm - * @param type - * @param action - * @return - */ - public Result delRole(AuthzTrans trans, PermDAO.Data perm, String roleFullName) { - // Note: Prepared Statements for Collection updates aren't supported - //ResultSet rv = - try { - getSession(trans).execute(UPDATE_SP + TABLE + " SET roles = roles - {'" + roleFullName + "'} " + - "WHERE " + - "ns = '" + perm.ns + "' AND " + - "type = '" + perm.type + "' AND " + - "instance = '" + perm.instance + "' AND " + - "action = '" + perm.action + "';" - ); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - //TODO how can we tell when it doesn't? - wasModified(trans, CRUD.update, perm, "Removed role " + roleFullName + " from perm " + - perm.ns + '.' + perm.type + '|' + perm.instance + '|' + perm.action); - return Result.ok(); - } - - - - /** - * Additional method: - * Select all Permissions by Name - * - * @param name - * @return - * @throws DAOException - */ - public Result> readByType(AuthzTrans trans, String ns, String type) { - return psByType.read(trans, R_TEXT, new Object[]{ns, type}); - } - - public Result> readChildren(AuthzTrans trans, String ns, String type) { - return psChildren.read(trans, R_TEXT, new Object[]{ns, type+DOT, type + DOT_PLUS_ONE}); - } - - public Result> readNS(AuthzTrans trans, String ns) { - return psNS.read(trans, R_TEXT, new Object[]{ns}); - } - - /** - * Add description to this permission - * - * @param trans - * @param ns - * @param type - * @param instance - * @param action - * @param description - * @return - */ - public Result addDescription(AuthzTrans trans, String ns, String type, - String instance, String action, String description) { - try { - getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" - + description + "' WHERE ns = '" + ns + "' AND type = '" + type + "'" - + "AND instance = '" + instance + "' AND action = '" + action + "';"); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - Data data = new Data(); - data.ns=ns; - data.type=type; - data.instance=instance; - data.action=action; - wasModified(trans, CRUD.update, data, "Added description " + description + " to permission " - + data.encode(), null ); - return Result.ok(); - } - - /** - * Log Modification statements to History - */ - @Override - protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; - - // Need to update history - HistoryDAO.Data hd = HistoryDAO.newInitedData(); - hd.user = trans.user(); - hd.action = modified.name(); - hd.target = TABLE; - hd.subject = subject ? override[1] : data.fullType(); - if (memo) { + @Override + public int[] invalidate(Cached cache) { + return new int[] { + seg(cache,ns), + seg(cache,ns,type), + seg(cache,ns,type,STAR), + seg(cache,ns,type,instance,action) + }; + } + + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PermLoader.deflt.marshal(this, new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + PermLoader.deflt.unmarshal(this, toDIS(bb)); + } + + @Override + public String toString() { + return encode(); + } + } + + private static class PermLoader extends Loader implements Streamer { + public static final int MAGIC=283939453; + public static final int VERSION=1; + public static final int BUFF_SIZE=96; + + public static final PermLoader deflt = new PermLoader(KEYLIMIT); + + public PermLoader(int keylimit) { + super(keylimit); + } + + @Override + public Data load(Data data, Row row) { + // Int more efficient Match "fields" string + data.ns = row.getString(0); + data.type = row.getString(1); + data.instance = row.getString(2); + data.action = row.getString(3); + data.roles = row.getSet(4,String.class); + data.description = row.getString(5); + return data; + } + + @Override + protected void key(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.ns; + obj[++idx]=data.type; + obj[++idx]=data.instance; + obj[++idx]=data.action; + } + + @Override + protected void body(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.roles; + obj[++idx]=data.description; + } + + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.ns); + writeString(os, data.type); + writeString(os, data.instance); + writeString(os, data.action); + writeStringSet(os, data.roles); + writeString(os, data.description); + } + + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; + data.ns = readString(is, buff); + data.type = readString(is,buff); + data.instance = readString(is,buff); + data.action = readString(is,buff); + data.roles = readStringSet(is,buff); + data.description = readString(is,buff); + } + } + + private void init(AuthzTrans trans) { + // the 3 is the number of key fields + String[] helpers = setCRUD(trans, TABLE, Data.class, PermLoader.deflt); + + // Other SELECT style statements... match with a local Method + psByType = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE ns = ? AND type = ?", new PermLoader(2) { + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.type; + } + },readConsistency); + + psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE ns = ?", new PermLoader(1),readConsistency); + + psChildren = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE ns=? AND type > ? AND type < ?", + new PermLoader(3) { + @Override + protected void key(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx] = data.ns; + obj[++idx]=data.type + DOT; + obj[++idx]=data.type + DOT_PLUS_ONE; + } + },readConsistency); + + } + + + /** + * Add a single Permission to the Role's Permission Collection + * + * @param trans + * @param roleFullName + * @param perm + * @param type + * @param action + * @return + */ + public Result addRole(AuthzTrans trans, PermDAO.Data perm, String roleFullName) { + // Note: Prepared Statements for Collection updates aren't supported + //ResultSet rv = + try { + getSession(trans).execute(UPDATE_SP + TABLE + " SET roles = roles + {'" + roleFullName + "'} " + + "WHERE " + + "ns = '" + perm.ns + "' AND " + + "type = '" + perm.type + "' AND " + + "instance = '" + perm.instance + "' AND " + + "action = '" + perm.action + "';" + ); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + wasModified(trans, CRUD.update, perm, "Added role " + roleFullName + " to perm " + + perm.ns + '.' + perm.type + '|' + perm.instance + '|' + perm.action); + return Result.ok(); + } + + /** + * Remove a single Permission from the Role's Permission Collection + * @param trans + * @param roleFullName + * @param perm + * @param type + * @param action + * @return + */ + public Result delRole(AuthzTrans trans, PermDAO.Data perm, String roleFullName) { + // Note: Prepared Statements for Collection updates aren't supported + //ResultSet rv = + try { + getSession(trans).execute(UPDATE_SP + TABLE + " SET roles = roles - {'" + roleFullName + "'} " + + "WHERE " + + "ns = '" + perm.ns + "' AND " + + "type = '" + perm.type + "' AND " + + "instance = '" + perm.instance + "' AND " + + "action = '" + perm.action + "';" + ); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + //TODO how can we tell when it doesn't? + wasModified(trans, CRUD.update, perm, "Removed role " + roleFullName + " from perm " + + perm.ns + '.' + perm.type + '|' + perm.instance + '|' + perm.action); + return Result.ok(); + } + + + + /** + * Additional method: + * Select all Permissions by Name + * + * @param name + * @return + * @throws DAOException + */ + public Result> readByType(AuthzTrans trans, String ns, String type) { + return psByType.read(trans, R_TEXT, new Object[]{ns, type}); + } + + public Result> readChildren(AuthzTrans trans, String ns, String type) { + return psChildren.read(trans, R_TEXT, new Object[]{ns, type+DOT, type + DOT_PLUS_ONE}); + } + + public Result> readNS(AuthzTrans trans, String ns) { + return psNS.read(trans, R_TEXT, new Object[]{ns}); + } + + /** + * Add description to this permission + * + * @param trans + * @param ns + * @param type + * @param instance + * @param action + * @param description + * @return + */ + public Result addDescription(AuthzTrans trans, String ns, String type, + String instance, String action, String description) { + try { + getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" + + description + "' WHERE ns = '" + ns + "' AND type = '" + type + "'" + + "AND instance = '" + instance + "' AND action = '" + action + "';"); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + Data data = new Data(); + data.ns=ns; + data.type=type; + data.instance=instance; + data.action=action; + wasModified(trans, CRUD.update, data, "Added description " + description + " to permission " + + data.encode(), null ); + return Result.ok(); + } + + /** + * Log Modification statements to History + */ + @Override + protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; + + // Need to update history + HistoryDAO.Data hd = HistoryDAO.newInitedData(); + hd.user = trans.user(); + hd.action = modified.name(); + hd.target = TABLE; + hd.subject = subject ? override[1] : data.fullType(); + if (memo) { hd.memo = String.format("%s", override[0]); } else { hd.memo = String.format("%sd %s|%s|%s", modified.name(),data.fullType(),data.instance,data.action); } - - if(modified==CRUD.delete) { - try { - hd.reconstruct = data.bytify(); - } catch (IOException e) { - trans.error().log(e,"Could not serialize PermDAO.Data"); - } - } - + + if(modified==CRUD.delete) { + try { + hd.reconstruct = data.bytify(); + } catch (IOException e) { + trans.error().log(e,"Could not serialize PermDAO.Data"); + } + } + if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); + trans.error().log("Cannot log to History"); } if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { - trans.error().log("Cannot touch CacheInfo"); + trans.error().log("Cannot touch CacheInfo"); } - } + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java index 974f73fe..4489d268 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java @@ -48,28 +48,28 @@ import com.datastax.driver.core.exceptions.DriverException; public class RoleDAO extends CassDAOImpl { - public static final String TABLE = "role"; + public static final String TABLE = "role"; public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F - private final HistoryDAO historyDAO; - private final CacheInfoDAO infoDAO; + private final HistoryDAO historyDAO; + private final CacheInfoDAO infoDAO; - private PSInfo psChildren, psNS, psName; + private PSInfo psChildren, psNS, psName; - public RoleDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { - super(trans, RoleDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + public RoleDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { + super(trans, RoleDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); // Set up sub-DAOs historyDAO = new HistoryDAO(trans, this); - infoDAO = new CacheInfoDAO(trans,this); - init(trans); - } + infoDAO = new CacheInfoDAO(trans,this); + init(trans); + } - public RoleDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) { - super(trans, RoleDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - historyDAO = hDAO; - infoDAO = ciDAO; - init(trans); - } + public RoleDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) { + super(trans, RoleDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + historyDAO = hDAO; + infoDAO = ciDAO; + init(trans); + } ////////////////////////////////////////// @@ -80,301 +80,301 @@ public class RoleDAO extends CassDAOImpl { * Data class that matches the Cassandra Table "role" * @author Jonathan */ - public static class Data extends CacheableData implements Bytification { - public String ns; - public String name; - public Set perms; - public String description; + public static class Data extends CacheableData implements Bytification { + public String ns; + public String name; + public Set perms; + public String description; //////////////////////////////////////// // Getters - public Set perms(boolean mutable) { - if (perms == null) { - perms = new HashSet<>(); - } else if (mutable && !(perms instanceof HashSet)) { - perms = new HashSet<>(perms); - } - return perms; - } - - public static Data create(NsDAO.Data ns, String name) { - NsSplit nss = new NsSplit(ns,name); - RoleDAO.Data rv = new Data(); - rv.ns = nss.ns; - rv.name=nss.name; - return rv; - } - - public String fullName() { - return ns + '.' + name; - } - - public String encode() { - return ns + '|' + name; - } - - /** - * Decode Perm String, including breaking into appropriate Namespace - * - * @param trans - * @param q - * @param r - * @return - */ - public static Result decode(AuthzTrans trans, Question q, String r) { - String[] ss = Split.splitTrim('|', r,2); - Data data = new Data(); - if(ss[1]==null) { // older 1 part encoding must be evaluated for NS - Result nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { - return Result.err(nss); - } - data.ns=nss.value.ns; - data.name=nss.value.name; - } else { // new 4 part encoding - data.ns=ss[0]; - data.name=ss[1]; - } - return Result.ok(data); - } - - /** - * Decode from UserRole Data - * @param urdd - * @return - */ - public static RoleDAO.Data decode(UserRoleDAO.Data urdd) { - RoleDAO.Data rd = new RoleDAO.Data(); - rd.ns = urdd.ns; - rd.name = urdd.rname; - return rd; - } - - - /** - * Decode Perm String, including breaking into appropriate Namespace - * - * @param trans - * @param q - * @param p - * @return - */ - public static Result decodeToArray(AuthzTrans trans, Question q, String p) { - String[] ss = Split.splitTrim('|', p,2); - if(ss[1]==null) { // older 1 part encoding must be evaluated for NS - Result nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { - return Result.err(nss); - } - ss[0] = nss.value.ns; - ss[1] = nss.value.name; - } - return Result.ok(ss); - } - - @Override - public int[] invalidate(Cached cache) { - return new int[] { - seg(cache,ns,name), - seg(cache,ns), - seg(cache,name), - }; - } - - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - RoleLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - RoleLoader.deflt.unmarshal(this, toDIS(bb)); - } - - @Override - public String toString() { - return ns + '.' + name; - } + public Set perms(boolean mutable) { + if (perms == null) { + perms = new HashSet<>(); + } else if (mutable && !(perms instanceof HashSet)) { + perms = new HashSet<>(perms); + } + return perms; + } + + public static Data create(NsDAO.Data ns, String name) { + NsSplit nss = new NsSplit(ns,name); + RoleDAO.Data rv = new Data(); + rv.ns = nss.ns; + rv.name=nss.name; + return rv; + } + + public String fullName() { + return ns + '.' + name; + } + + public String encode() { + return ns + '|' + name; + } + + /** + * Decode Perm String, including breaking into appropriate Namespace + * + * @param trans + * @param q + * @param r + * @return + */ + public static Result decode(AuthzTrans trans, Question q, String r) { + String[] ss = Split.splitTrim('|', r,2); + Data data = new Data(); + if(ss[1]==null) { // older 1 part encoding must be evaluated for NS + Result nss = q.deriveNsSplit(trans, ss[0]); + if(nss.notOK()) { + return Result.err(nss); + } + data.ns=nss.value.ns; + data.name=nss.value.name; + } else { // new 4 part encoding + data.ns=ss[0]; + data.name=ss[1]; + } + return Result.ok(data); + } + + /** + * Decode from UserRole Data + * @param urdd + * @return + */ + public static RoleDAO.Data decode(UserRoleDAO.Data urdd) { + RoleDAO.Data rd = new RoleDAO.Data(); + rd.ns = urdd.ns; + rd.name = urdd.rname; + return rd; + } + + + /** + * Decode Perm String, including breaking into appropriate Namespace + * + * @param trans + * @param q + * @param p + * @return + */ + public static Result decodeToArray(AuthzTrans trans, Question q, String p) { + String[] ss = Split.splitTrim('|', p,2); + if(ss[1]==null) { // older 1 part encoding must be evaluated for NS + Result nss = q.deriveNsSplit(trans, ss[0]); + if(nss.notOK()) { + return Result.err(nss); + } + ss[0] = nss.value.ns; + ss[1] = nss.value.name; + } + return Result.ok(ss); + } + + @Override + public int[] invalidate(Cached cache) { + return new int[] { + seg(cache,ns,name), + seg(cache,ns), + seg(cache,name), + }; + } + + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + RoleLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + RoleLoader.deflt.unmarshal(this, toDIS(bb)); + } + + @Override + public String toString() { + return ns + '.' + name; + } } private static class RoleLoader extends Loader implements Streamer { - public static final int MAGIC=923577343; - public static final int VERSION=1; - public static final int BUFF_SIZE=96; - - public static final RoleLoader deflt = new RoleLoader(KEYLIMIT); - - public RoleLoader(int keylimit) { - super(keylimit); - } - - @Override - public Data load(Data data, Row row) { - // Int more efficient - data.ns = row.getString(0); - data.name = row.getString(1); - data.perms = row.getSet(2,String.class); - data.description = row.getString(3); - return data; - } - - @Override - protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.ns; - obj[++idx]=data.name; - } - - @Override - protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.perms; - obj[++idx]=data.description; - } - - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); - writeString(os, data.ns); - writeString(os, data.name); - writeStringSet(os,data.perms); - writeString(os, data.description); - } - - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - byte[] buff = new byte[BUFF_SIZE]; - data.ns = readString(is, buff); - data.name = readString(is,buff); - data.perms = readStringSet(is,buff); - data.description = readString(is,buff); - } + public static final int MAGIC=923577343; + public static final int VERSION=1; + public static final int BUFF_SIZE=96; + + public static final RoleLoader deflt = new RoleLoader(KEYLIMIT); + + public RoleLoader(int keylimit) { + super(keylimit); + } + + @Override + public Data load(Data data, Row row) { + // Int more efficient + data.ns = row.getString(0); + data.name = row.getString(1); + data.perms = row.getSet(2,String.class); + data.description = row.getString(3); + return data; + } + + @Override + protected void key(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.ns; + obj[++idx]=data.name; + } + + @Override + protected void body(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.perms; + obj[++idx]=data.description; + } + + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); + writeString(os, data.ns); + writeString(os, data.name); + writeStringSet(os,data.perms); + writeString(os, data.description); + } + + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + byte[] buff = new byte[BUFF_SIZE]; + data.ns = readString(is, buff); + data.name = readString(is,buff); + data.perms = readStringSet(is,buff); + data.description = readString(is,buff); + } }; - private void init(AuthzTrans trans) { - String[] helpers = setCRUD(trans, TABLE, Data.class, RoleLoader.deflt); - - psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE ns = ?", new RoleLoader(1),readConsistency); - - psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE name = ?", new RoleLoader(1),readConsistency); - - psChildren = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + - " WHERE ns=? AND name > ? AND name < ?", - new RoleLoader(3) { - @Override - protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx] = data.ns; - obj[++idx]=data.name + DOT; - obj[++idx]=data.name + DOT_PLUS_ONE; - } - },readConsistency); - - } - - public Result> readNS(AuthzTrans trans, String ns) { - return psNS.read(trans, R_TEXT + " NS " + ns, new Object[]{ns}); - } - - public Result> readName(AuthzTrans trans, String name) { - return psName.read(trans, R_TEXT + name, new Object[]{name}); - } - - public Result> readChildren(AuthzTrans trans, String ns, String role) { - if(role.length()==0 || "*".equals(role)) { - return psChildren.read(trans, R_TEXT, new Object[]{ns, FIRST_CHAR, LAST_CHAR}); - } else { - return psChildren.read(trans, R_TEXT, new Object[]{ns, role+DOT, role+DOT_PLUS_ONE}); - } - } - - /** - * Add a single Permission to the Role's Permission Collection - * - * @param trans - * @param role - * @param perm - * @param type - * @param action - * @return - */ - public Result addPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) { - // Note: Prepared Statements for Collection updates aren't supported - String pencode = perm.encode(); - try { - getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms + {'" + - pencode + "'} WHERE " + - "ns = '" + role.ns + "' AND name = '" + role.name + "';"); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - wasModified(trans, CRUD.update, role, "Added permission " + pencode + " to role " + role.fullName()); - return Result.ok(); - } - - /** - * Remove a single Permission from the Role's Permission Collection - * @param trans - * @param role - * @param perm - * @param type - * @param action - * @return - */ - public Result delPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) { - // Note: Prepared Statements for Collection updates aren't supported - - String pencode = perm.encode(); - - //ResultSet rv = - try { - getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms - {'" + - pencode + "'} WHERE " + - "ns = '" + role.ns + "' AND name = '" + role.name + "';"); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - //TODO how can we tell when it doesn't? - wasModified(trans, CRUD.update, role, "Removed permission " + pencode + " from role " + role.fullName() ); - return Result.ok(); - } - - /** - * Add description to role - * - * @param trans - * @param ns - * @param name - * @param description - * @return - */ - public Result addDescription(AuthzTrans trans, String ns, String name, String description) { - try { - getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" - + description + "' WHERE ns = '" + ns + "' AND name = '" + name + "';"); - } catch (DriverException | APIException | IOException e) { - reportPerhapsReset(trans,e); - return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); - } - - Data data = new Data(); - data.ns=ns; - data.name=name; - wasModified(trans, CRUD.update, data, "Added description " + description + " to role " + data.fullName(), null ); - return Result.ok(); - } - - + private void init(AuthzTrans trans) { + String[] helpers = setCRUD(trans, TABLE, Data.class, RoleLoader.deflt); + + psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE ns = ?", new RoleLoader(1),readConsistency); + + psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE name = ?", new RoleLoader(1),readConsistency); + + psChildren = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + + " WHERE ns=? AND name > ? AND name < ?", + new RoleLoader(3) { + @Override + protected void key(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx] = data.ns; + obj[++idx]=data.name + DOT; + obj[++idx]=data.name + DOT_PLUS_ONE; + } + },readConsistency); + + } + + public Result> readNS(AuthzTrans trans, String ns) { + return psNS.read(trans, R_TEXT + " NS " + ns, new Object[]{ns}); + } + + public Result> readName(AuthzTrans trans, String name) { + return psName.read(trans, R_TEXT + name, new Object[]{name}); + } + + public Result> readChildren(AuthzTrans trans, String ns, String role) { + if(role.length()==0 || "*".equals(role)) { + return psChildren.read(trans, R_TEXT, new Object[]{ns, FIRST_CHAR, LAST_CHAR}); + } else { + return psChildren.read(trans, R_TEXT, new Object[]{ns, role+DOT, role+DOT_PLUS_ONE}); + } + } + + /** + * Add a single Permission to the Role's Permission Collection + * + * @param trans + * @param role + * @param perm + * @param type + * @param action + * @return + */ + public Result addPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) { + // Note: Prepared Statements for Collection updates aren't supported + String pencode = perm.encode(); + try { + getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms + {'" + + pencode + "'} WHERE " + + "ns = '" + role.ns + "' AND name = '" + role.name + "';"); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + wasModified(trans, CRUD.update, role, "Added permission " + pencode + " to role " + role.fullName()); + return Result.ok(); + } + + /** + * Remove a single Permission from the Role's Permission Collection + * @param trans + * @param role + * @param perm + * @param type + * @param action + * @return + */ + public Result delPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) { + // Note: Prepared Statements for Collection updates aren't supported + + String pencode = perm.encode(); + + //ResultSet rv = + try { + getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms - {'" + + pencode + "'} WHERE " + + "ns = '" + role.ns + "' AND name = '" + role.name + "';"); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + //TODO how can we tell when it doesn't? + wasModified(trans, CRUD.update, role, "Removed permission " + pencode + " from role " + role.fullName() ); + return Result.ok(); + } + + /** + * Add description to role + * + * @param trans + * @param ns + * @param name + * @param description + * @return + */ + public Result addDescription(AuthzTrans trans, String ns, String name, String description) { + try { + getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" + + description + "' WHERE ns = '" + ns + "' AND name = '" + name + "';"); + } catch (DriverException | APIException | IOException e) { + reportPerhapsReset(trans,e); + return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG); + } + + Data data = new Data(); + data.ns=ns; + data.name=name; + wasModified(trans, CRUD.update, data, "Added description " + description + " to role " + data.fullName(), null ); + return Result.ok(); + } + + /** * Log Modification statements to History * @param modified which CRUD action was done @@ -383,28 +383,28 @@ public class RoleDAO extends CassDAOImpl { */ @Override protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; - HistoryDAO.Data hd = HistoryDAO.newInitedData(); + HistoryDAO.Data hd = HistoryDAO.newInitedData(); hd.user = trans.user(); hd.action = modified.name(); hd.target = TABLE; hd.subject = subject ? override[1] : data.fullName(); hd.memo = memo ? override[0] : (data.fullName() + " was " + modified.name() + 'd' ); - if(modified==CRUD.delete) { - try { - hd.reconstruct = data.bytify(); - } catch (IOException e) { - trans.error().log(e,"Could not serialize RoleDAO.Data"); - } - } + if(modified==CRUD.delete) { + try { + hd.reconstruct = data.bytify(); + } catch (IOException e) { + trans.error().log(e,"Could not serialize RoleDAO.Data"); + } + } if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); + trans.error().log("Cannot log to History"); } if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { - trans.error().log("Cannot touch CacheInfo for Role"); + trans.error().log("Cannot touch CacheInfo for Role"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Status.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Status.java index be52c406..8a617b94 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Status.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Status.java @@ -36,53 +36,53 @@ import org.onap.aaf.auth.layer.Result; * @param */ public class Status extends Result { - - // Jonathan 10/1/2013: Initially, I used enum, but it's not extensible. + + // Jonathan 10/1/2013: Initially, I used enum, but it's not extensible. public final static int ERR_NsNotFound = Result.ERR_General+1, - ERR_RoleNotFound = Result.ERR_General+2, - ERR_PermissionNotFound = Result.ERR_General+3, - ERR_UserNotFound = Result.ERR_General+4, - ERR_UserRoleNotFound = Result.ERR_General+5, - ERR_DelegateNotFound = Result.ERR_General+6, - ERR_InvalidDelegate = Result.ERR_General+7, - ERR_DependencyExists = Result.ERR_General+8, - ERR_NoApprovals = Result.ERR_General+9, - ACC_Now = Result.ERR_General+10, - ACC_Future = Result.ERR_General+11, - ERR_ChoiceNeeded = Result.ERR_General+12, - ERR_FutureNotRequested = Result.ERR_General+13; + ERR_RoleNotFound = Result.ERR_General+2, + ERR_PermissionNotFound = Result.ERR_General+3, + ERR_UserNotFound = Result.ERR_General+4, + ERR_UserRoleNotFound = Result.ERR_General+5, + ERR_DelegateNotFound = Result.ERR_General+6, + ERR_InvalidDelegate = Result.ERR_General+7, + ERR_DependencyExists = Result.ERR_General+8, + ERR_NoApprovals = Result.ERR_General+9, + ACC_Now = Result.ERR_General+10, + ACC_Future = Result.ERR_General+11, + ERR_ChoiceNeeded = Result.ERR_General+12, + ERR_FutureNotRequested = Result.ERR_General+13; - /** + /** * Constructor for Result set. * @param data * @param status */ private Status(RV value, int status, String details, String[] variables ) { - super(value,status,details,variables); + super(value,status,details,variables); } - public static String name(int status) { - switch(status) { - case OK: return "OK"; - case ERR_NsNotFound: return "ERR_NsNotFound"; - case ERR_RoleNotFound: return "ERR_RoleNotFound"; - case ERR_PermissionNotFound: return "ERR_PermissionNotFound"; - case ERR_UserNotFound: return "ERR_UserNotFound"; - case ERR_UserRoleNotFound: return "ERR_UserRoleNotFound"; - case ERR_DelegateNotFound: return "ERR_DelegateNotFound"; - case ERR_InvalidDelegate: return "ERR_InvalidDelegate"; - case ERR_ConflictAlreadyExists: return "ERR_ConflictAlreadyExists"; - case ERR_DependencyExists: return "ERR_DependencyExists"; - case ERR_ActionNotCompleted: return "ERR_ActionNotCompleted"; - case ERR_Denied: return "ERR_Denied"; - case ERR_Policy: return "ERR_Policy"; - case ERR_BadData: return "ERR_BadData"; - case ERR_NotImplemented: return "ERR_NotImplemented"; - case ERR_NotFound: return "ERR_NotFound"; - case ERR_ChoiceNeeded: return "ERR_ChoiceNeeded"; - } - //case ERR_General: or unknown... - return "ERR_General"; - } + public static String name(int status) { + switch(status) { + case OK: return "OK"; + case ERR_NsNotFound: return "ERR_NsNotFound"; + case ERR_RoleNotFound: return "ERR_RoleNotFound"; + case ERR_PermissionNotFound: return "ERR_PermissionNotFound"; + case ERR_UserNotFound: return "ERR_UserNotFound"; + case ERR_UserRoleNotFound: return "ERR_UserRoleNotFound"; + case ERR_DelegateNotFound: return "ERR_DelegateNotFound"; + case ERR_InvalidDelegate: return "ERR_InvalidDelegate"; + case ERR_ConflictAlreadyExists: return "ERR_ConflictAlreadyExists"; + case ERR_DependencyExists: return "ERR_DependencyExists"; + case ERR_ActionNotCompleted: return "ERR_ActionNotCompleted"; + case ERR_Denied: return "ERR_Denied"; + case ERR_Policy: return "ERR_Policy"; + case ERR_BadData: return "ERR_BadData"; + case ERR_NotImplemented: return "ERR_NotImplemented"; + case ERR_NotFound: return "ERR_NotFound"; + case ERR_ChoiceNeeded: return "ERR_ChoiceNeeded"; + } + //case ERR_General: or unknown... + return "ERR_General"; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java index 301e47fc..7b9f7b91 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java @@ -46,274 +46,274 @@ import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Row; public class UserRoleDAO extends CassDAOImpl { - public static final String TABLE = "user_role"; - + public static final String TABLE = "user_role"; + public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F - private static final String TRANS_UR_SLOT = "_TRANS_UR_SLOT_"; - public Slot transURSlot; - - private final HistoryDAO historyDAO; - private final CacheInfoDAO infoDAO; - - private PSInfo psByUser, psByRole, psUserInRole; + private static final String TRANS_UR_SLOT = "_TRANS_UR_SLOT_"; + public Slot transURSlot; + + private final HistoryDAO historyDAO; + private final CacheInfoDAO infoDAO; + + private PSInfo psByUser, psByRole, psUserInRole; - public UserRoleDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { - super(trans, UserRoleDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - transURSlot = trans.slot(TRANS_UR_SLOT); - init(trans); + public UserRoleDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { + super(trans, UserRoleDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + transURSlot = trans.slot(TRANS_UR_SLOT); + init(trans); - // Set up sub-DAOs - historyDAO = new HistoryDAO(trans, this); - infoDAO = new CacheInfoDAO(trans,this); - } + // Set up sub-DAOs + historyDAO = new HistoryDAO(trans, this); + infoDAO = new CacheInfoDAO(trans,this); + } - public UserRoleDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) { - super(trans, UserRoleDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); - transURSlot = trans.slot(TRANS_UR_SLOT); - historyDAO = hDAO; - infoDAO = ciDAO; - init(trans); - } + public UserRoleDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) { + super(trans, UserRoleDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); + transURSlot = trans.slot(TRANS_UR_SLOT); + historyDAO = hDAO; + infoDAO = ciDAO; + init(trans); + } - private static final int KEYLIMIT = 2; - public static class Data extends CacheableData implements Bytification { - public String user; - public String role; - public String ns; - public String rname; - public Date expires; - - @Override - public int[] invalidate(Cached cache) { - // Note: I'm not worried about Name collisions, because the formats are different: - // Jonathan... etc versus - // com. ... - // The "dot" makes the difference. - return new int[] { - seg(cache,user,role), - seg(cache,user), - seg(cache,role) - }; - } + private static final int KEYLIMIT = 2; + public static class Data extends CacheableData implements Bytification { + public String user; + public String role; + public String ns; + public String rname; + public Date expires; + + @Override + public int[] invalidate(Cached cache) { + // Note: I'm not worried about Name collisions, because the formats are different: + // Jonathan... etc versus + // com. ... + // The "dot" makes the difference. + return new int[] { + seg(cache,user,role), + seg(cache,user), + seg(cache,role) + }; + } - @Override - public ByteBuffer bytify() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - URLoader.deflt.marshal(this,new DataOutputStream(baos)); - return ByteBuffer.wrap(baos.toByteArray()); - } - - @Override - public void reconstitute(ByteBuffer bb) throws IOException { - URLoader.deflt.unmarshal(this, toDIS(bb)); - } + @Override + public ByteBuffer bytify() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + URLoader.deflt.marshal(this,new DataOutputStream(baos)); + return ByteBuffer.wrap(baos.toByteArray()); + } + + @Override + public void reconstitute(ByteBuffer bb) throws IOException { + URLoader.deflt.unmarshal(this, toDIS(bb)); + } - public void role(String ns, String rname) { - this.ns = ns; - this.rname = rname; - this.role = ns + '.' + rname; - } - - public void role(RoleDAO.Data rdd) { - ns = rdd.ns; - rname = rdd.name; - role = rdd.fullName(); - } + public void role(String ns, String rname) { + this.ns = ns; + this.rname = rname; + this.role = ns + '.' + rname; + } + + public void role(RoleDAO.Data rdd) { + ns = rdd.ns; + rname = rdd.name; + role = rdd.fullName(); + } - - public boolean role(AuthzTrans trans, Question ques, String role) { - this.role = role; - Result rnss = ques.deriveNsSplit(trans, role); - if(rnss.isOKhasData()) { - ns = rnss.value.ns; - rname = rnss.value.name; - return true; - } else { - return false; - } - } + + public boolean role(AuthzTrans trans, Question ques, String role) { + this.role = role; + Result rnss = ques.deriveNsSplit(trans, role); + if(rnss.isOKhasData()) { + ns = rnss.value.ns; + rname = rnss.value.name; + return true; + } else { + return false; + } + } - @Override - public String toString() { - return user + '|' + ns + '|' + rname + '|' + Chrono.dateStamp(expires); - } + @Override + public String toString() { + return user + '|' + ns + '|' + rname + '|' + Chrono.dateStamp(expires); + } - } - - private static class URLoader extends Loader implements Streamer { - public static final int MAGIC=738469903; - public static final int VERSION=1; - public static final int BUFF_SIZE=48; - - public static final URLoader deflt = new URLoader(KEYLIMIT); + } + + private static class URLoader extends Loader implements Streamer { + public static final int MAGIC=738469903; + public static final int VERSION=1; + public static final int BUFF_SIZE=48; + + public static final URLoader deflt = new URLoader(KEYLIMIT); - public URLoader(int keylimit) { - super(keylimit); - } + public URLoader(int keylimit) { + super(keylimit); + } - @Override - public Data load(Data data, Row row) { - data.user = row.getString(0); - data.role = row.getString(1); - data.ns = row.getString(2); - data.rname = row.getString(3); - data.expires = row.getTimestamp(4); - return data; - } + @Override + public Data load(Data data, Row row) { + data.user = row.getString(0); + data.role = row.getString(1); + data.ns = row.getString(2); + data.rname = row.getString(3); + data.expires = row.getTimestamp(4); + return data; + } - @Override - protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.user; - obj[++idx]=data.role; - } + @Override + protected void key(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.user; + obj[++idx]=data.role; + } - @Override - protected void body(Data data, int _idx, Object[] obj) { - int idx = _idx; - obj[idx]=data.ns; - obj[++idx]=data.rname; - obj[++idx]=data.expires; - } - - @Override - public void marshal(Data data, DataOutputStream os) throws IOException { - writeHeader(os,MAGIC,VERSION); + @Override + protected void body(Data data, int _idx, Object[] obj) { + int idx = _idx; + obj[idx]=data.ns; + obj[++idx]=data.rname; + obj[++idx]=data.expires; + } + + @Override + public void marshal(Data data, DataOutputStream os) throws IOException { + writeHeader(os,MAGIC,VERSION); - writeString(os, data.user); - writeString(os, data.role); - writeString(os, data.ns); - writeString(os, data.rname); - os.writeLong(data.expires==null?-1:data.expires.getTime()); - } + writeString(os, data.user); + writeString(os, data.role); + writeString(os, data.ns); + writeString(os, data.rname); + os.writeLong(data.expires==null?-1:data.expires.getTime()); + } - @Override - public void unmarshal(Data data, DataInputStream is) throws IOException { - /*int version = */readHeader(is,MAGIC,VERSION); - // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields - - byte[] buff = new byte[BUFF_SIZE]; - data.user = readString(is,buff); - data.role = readString(is,buff); - data.ns = readString(is,buff); - data.rname = readString(is,buff); - long l = is.readLong(); - data.expires = l<0?null:new Date(l); - } + @Override + public void unmarshal(Data data, DataInputStream is) throws IOException { + /*int version = */readHeader(is,MAGIC,VERSION); + // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields + + byte[] buff = new byte[BUFF_SIZE]; + data.user = readString(is,buff); + data.role = readString(is,buff); + data.ns = readString(is,buff); + data.rname = readString(is,buff); + long l = is.readLong(); + data.expires = l<0?null:new Date(l); + } - }; - - private void init(AuthzTrans trans) { - String[] helper = setCRUD(trans, TABLE, Data.class, URLoader.deflt); - - psByUser = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ?", - new URLoader(1) { - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.user; - } - },readConsistency); - - // Note: We understand this call may have poor performance, so only should be used in Management (Delete) func - psByRole = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE role = ? ALLOW FILTERING", - new URLoader(1) { - @Override - protected void key(Data data, int idx, Object[] obj) { - obj[idx]=data.role; - } - },readConsistency); - - psUserInRole = new PSInfo(trans,SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ? AND role = ?", - URLoader.deflt,readConsistency); - } + }; + + private void init(AuthzTrans trans) { + String[] helper = setCRUD(trans, TABLE, Data.class, URLoader.deflt); + + psByUser = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ?", + new URLoader(1) { + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.user; + } + },readConsistency); + + // Note: We understand this call may have poor performance, so only should be used in Management (Delete) func + psByRole = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE role = ? ALLOW FILTERING", + new URLoader(1) { + @Override + protected void key(Data data, int idx, Object[] obj) { + obj[idx]=data.role; + } + },readConsistency); + + psUserInRole = new PSInfo(trans,SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ? AND role = ?", + URLoader.deflt,readConsistency); + } - public Result> readByUser(AuthzTrans trans, String user) { - return psByUser.read(trans, R_TEXT + " by User " + user, new Object[]{user}); - } + public Result> readByUser(AuthzTrans trans, String user) { + return psByUser.read(trans, R_TEXT + " by User " + user, new Object[]{user}); + } - /** - * Note: Use Sparingly. Cassandra's forced key structure means this will perform fairly poorly - * @param trans - * @param role - * @return - * @throws DAOException - */ - public Result> readByRole(AuthzTrans trans, String role) { - return psByRole.read(trans, R_TEXT + " by Role " + role, new Object[]{role}); - } - - /** - * Direct Lookup of User Role - * Don't forget to check for Expiration - */ - public Result> readByUserRole(AuthzTrans trans, String user, String role) { - return psUserInRole.read(trans, R_TEXT + " by User " + user + " and Role " + role, new Object[]{user,role}); - } + /** + * Note: Use Sparingly. Cassandra's forced key structure means this will perform fairly poorly + * @param trans + * @param role + * @return + * @throws DAOException + */ + public Result> readByRole(AuthzTrans trans, String role) { + return psByRole.read(trans, R_TEXT + " by Role " + role, new Object[]{role}); + } + + /** + * Direct Lookup of User Role + * Don't forget to check for Expiration + */ + public Result> readByUserRole(AuthzTrans trans, String user, String role) { + return psUserInRole.read(trans, R_TEXT + " by User " + user + " and Role " + role, new Object[]{user,role}); + } - /** + /** * Log Modification statements to History * @param modified which CRUD action was done * @param data entity data that needs a log entry * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data */ - @Override - protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { - boolean memo = override.length>0 && override[0]!=null; - boolean subject = override.length>1 && override[1]!=null; + @Override + protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) { + boolean memo = override.length>0 && override[0]!=null; + boolean subject = override.length>1 && override[1]!=null; - HistoryDAO.Data hd = HistoryDAO.newInitedData(); - HistoryDAO.Data hdRole = HistoryDAO.newInitedData(); - + HistoryDAO.Data hd = HistoryDAO.newInitedData(); + HistoryDAO.Data hdRole = HistoryDAO.newInitedData(); + hd.user = hdRole.user = trans.user(); - hd.action = modified.name(); - // Modifying User/Role is an Update to Role, not a Create. Jonathan, 07-14-2015 - hdRole.action = CRUD.update.name(); - hd.target = TABLE; - hdRole.target = RoleDAO.TABLE; - hd.subject = subject?override[1] : (data.user + '|'+data.role); - hdRole.subject = data.role; - switch(modified) { - case create: - hd.memo = hdRole.memo = memo - ? String.format("%s by %s", override[0], hd.user) - : String.format("%s added to %s",data.user,data.role); - break; - case update: - hd.memo = hdRole.memo = memo - ? String.format("%s by %s", override[0], hd.user) - : String.format("%s - %s was updated",data.user,data.role); - break; - case delete: - hd.memo = hdRole.memo = memo - ? String.format("%s by %s", override[0], hd.user) - : String.format("%s removed from %s",data.user,data.role); - try { - hd.reconstruct = hdRole.reconstruct = data.bytify(); - } catch (IOException e) { - trans.warn().log(e,"Deleted UserRole could not be serialized"); - } - break; - default: - hd.memo = hdRole.memo = memo - ? String.format("%s by %s", override[0], hd.user) - : "n/a"; - } + hd.action = modified.name(); + // Modifying User/Role is an Update to Role, not a Create. Jonathan, 07-14-2015 + hdRole.action = CRUD.update.name(); + hd.target = TABLE; + hdRole.target = RoleDAO.TABLE; + hd.subject = subject?override[1] : (data.user + '|'+data.role); + hdRole.subject = data.role; + switch(modified) { + case create: + hd.memo = hdRole.memo = memo + ? String.format("%s by %s", override[0], hd.user) + : String.format("%s added to %s",data.user,data.role); + break; + case update: + hd.memo = hdRole.memo = memo + ? String.format("%s by %s", override[0], hd.user) + : String.format("%s - %s was updated",data.user,data.role); + break; + case delete: + hd.memo = hdRole.memo = memo + ? String.format("%s by %s", override[0], hd.user) + : String.format("%s removed from %s",data.user,data.role); + try { + hd.reconstruct = hdRole.reconstruct = data.bytify(); + } catch (IOException e) { + trans.warn().log(e,"Deleted UserRole could not be serialized"); + } + break; + default: + hd.memo = hdRole.memo = memo + ? String.format("%s by %s", override[0], hd.user) + : "n/a"; + } - if(historyDAO.create(trans, hd).status!=Status.OK) { - trans.error().log("Cannot log to History"); - } - - if(historyDAO.create(trans, hdRole).status!=Status.OK) { - trans.error().log("Cannot log to History"); - } - // uses User as Segment + if(historyDAO.create(trans, hd).status!=Status.OK) { + trans.error().log("Cannot log to History"); + } + + if(historyDAO.create(trans, hdRole).status!=Status.OK) { + trans.error().log("Cannot log to History"); + } + // uses User as Segment if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { - trans.error().log("Cannot touch CacheInfo"); + trans.error().log("Cannot touch CacheInfo"); } - } + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java index 1979db28..f0a59582 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java @@ -29,45 +29,45 @@ import org.onap.aaf.auth.org.Executor; public class CassExecutor implements Executor { - private Question q; - private Function f; - private AuthzTrans trans; + private Question q; + private Function f; + private AuthzTrans trans; - public CassExecutor(AuthzTrans trans, Function f) { - this.trans = trans; - this.f = f; - this.q = this.f.q; - } + public CassExecutor(AuthzTrans trans, Function f) { + this.trans = trans; + this.f = f; + this.q = this.f.q; + } - @Override - public boolean hasPermission(String user, String ns, String type, String instance, String action) { - return isGranted(user, ns, type, instance, action); - } + @Override + public boolean hasPermission(String user, String ns, String type, String instance, String action) { + return isGranted(user, ns, type, instance, action); + } - @Override - public boolean inRole(String name) { - Result nss = q.deriveNsSplit(trans, name); - if(nss.notOK())return false; - return q.roleDAO.read(trans, nss.value.ns,nss.value.name).isOKhasData(); - } + @Override + public boolean inRole(String name) { + Result nss = q.deriveNsSplit(trans, name); + if(nss.notOK())return false; + return q.roleDAO.read(trans, nss.value.ns,nss.value.name).isOKhasData(); + } - public boolean isGranted(String user, String ns, String type, String instance, String action) { - return q.isGranted(trans, user, ns, type, instance,action); - } + public boolean isGranted(String user, String ns, String type, String instance, String action) { + return q.isGranted(trans, user, ns, type, instance,action); + } - @Override - public String namespace() throws Exception { - Result res = q.validNSOfDomain(trans,trans.user()); - if(res.isOK()) { - String user[] = trans.user().split("\\."); - return user[user.length-1] + '.' + user[user.length-2]; - } - throw new Exception(res.status + ' ' + res.details); - } + @Override + public String namespace() throws Exception { + Result res = q.validNSOfDomain(trans,trans.user()); + if(res.isOK()) { + String user[] = trans.user().split("\\."); + return user[user.length-1] + '.' + user[user.length-2]; + } + throw new Exception(res.status + ' ' + res.details); + } - @Override - public String id() { - return trans.user(); - } + @Override + public String id() { + return trans.user(); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java index 8529ce87..f3aae2ec 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java @@ -60,1733 +60,1733 @@ import org.onap.aaf.auth.org.OrganizationException; public class Function { - private static final String CANNOT_BE_THE_OWNER_OF_A_NAMESPACE = "%s(%s) cannot be the owner of the namespace '%s'. Owners %s."; - - public enum FUTURE_OP { - C("Create"),U("Update"),D("Delete"),G("Grant"),UG("UnGrant"),A("Approval"); - - private String desc; - - private FUTURE_OP(String desc) { - this.desc = desc; - } - - public String desc() { - return desc; - } - - /** - * Same as valueOf(), but passes back null instead of throwing Exception - * @param value - * @return - */ - public static FUTURE_OP toFO(String value) { - if(value!=null) { - for(FUTURE_OP fo : values()) { - if(fo.name().equals(value)){ - return fo; - } - } - } - return null; - } - } - - public enum OP_STATUS { - E("Executed"),D("Denied"),P("Pending"),L("Lapsed"); - - private String desc; - public final static Result RE = Result.ok(OP_STATUS.E); - public final static Result RD = Result.ok(OP_STATUS.D); - public final static Result RP = Result.ok(OP_STATUS.P); - public final static Result RL = Result.ok(OP_STATUS.L); - - private OP_STATUS(String desc) { - this.desc = desc; - } - - public String desc() { - return desc; - } - - } - - public static final String FOP_CRED = "cred"; - public static final String FOP_DELEGATE = "delegate"; - public static final String FOP_NS = "ns"; - public static final String FOP_PERM = "perm"; - public static final String FOP_ROLE = "role"; - public static final String FOP_USER_ROLE = "user_role"; - private static final List NO_ADDL_APPROVE = new ArrayList<>(); - private static final String ROOT_NS = Define.ROOT_NS(); - // First Action should ALWAYS be "write", see "CreateRole" - public final Question q; - - public Function(AuthzTrans trans, Question question) { - q = question; - } - - private class ErrBuilder { - private StringBuilder sb; - private List ao; - - public void log(Result result) { - if (result.notOK()) { - if (sb == null) { - sb = new StringBuilder(); - ao = new ArrayList<>(); - } - sb.append(result.details); - sb.append('\n'); - for (String s : result.variables) { - ao.add(s); - } - } - } - - public String[] vars() { - String[] rv = new String[ao.size()]; - ao.toArray(rv); - return rv; - } - - public boolean hasErr() { - return sb != null; - } - - @Override - public String toString() { - return sb == null ? "" : String.format(sb.toString(), ao); - } - } - - /** - * createNS - * - * Create Namespace - * - * @param trans - * @param org - * @param ns - * @param user - * @return - * @throws DAOException - * - * To create an NS, you need to: 1) validate permission to - * modify parent NS 2) Does NS exist already? 3) Create NS with - * a) "user" as owner. NOTE: Per 10-15 request for AAF 1.0 4) - * Loop through Roles with Parent NS, and map any that start - * with this NS into this one 5) Loop through Perms with Parent - * NS, and map any that start with this NS into this one - */ - public Result createNS(AuthzTrans trans, Namespace namespace, boolean fromApproval) { - Result rq; -// if (namespace.name.endsWith(Question.DOT_ADMIN) -// || namespace.name.endsWith(Question.DOT_OWNER)) { -// return Result.err(Status.ERR_BadData, -// "'admin' and 'owner' are reserved names in AAF"); -// } - - try { - for (String u : namespace.owner) { - Organization org = trans.org(); - Identity orgUser = org.getIdentity(trans, u); - String reason; - if (orgUser == null) { - return Result.err(Status.ERR_Policy,"%s is not a valid user at %s",u,org.getName()); - } else if((reason=orgUser.mayOwn())!=null) { - if (org.isTestEnv()) { - String reason2; - if((reason2=org.validate(trans, Policy.AS_RESPONSIBLE,new CassExecutor(trans, this), u))!=null) { // can masquerade as responsible - trans.debug().log(reason2); - return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,orgUser.fullName(),orgUser.id(),namespace.name,reason); - } - // a null means ok - } else { - if(orgUser.isFound()) { - return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,orgUser.fullName(),orgUser.id(),namespace.name, reason); - } else { - return Result.err(Status.ERR_Policy,u + " is an invalid Identity"); - } - } - } - } - } catch (Exception e) { - trans.error().log(e, - "Could not contact Organization for User Validation"); - } - - String user = trans.user(); - // 1) May Change Parent? - int idx = namespace.name.lastIndexOf('.'); - String parent; - if (idx < 0) { - if (!q.isGranted(trans, user, ROOT_NS,Question.NS, ".", "create")) { - return Result.err(Result.ERR_Security, - "%s may not create Root Namespaces", user); - } - parent = null; - fromApproval = true; - } else { - parent = namespace.name.substring(0, idx); // get Parent String - } - - Result rparent = q.deriveNs(trans, parent); - if (rparent.notOK()) { - return Result.err(rparent); - } - if (!fromApproval) { - rparent = q.mayUser(trans, user, rparent.value, Access.write); - if (rparent.notOK()) { - return Result.err(rparent); - } - } - parent = namespace.parent = rparent.value.name; // Correct Namespace from real data - - // 2) Does requested NS exist - if (q.nsDAO.read(trans, namespace.name).isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, - "Target Namespace already exists"); - } - - // Someone must be responsible. - if (namespace.owner == null || namespace.owner.isEmpty()) { - return Result - .err(Status.ERR_Policy, - "Namespaces must be assigned at least one responsible party"); - } - - // 3) Create NS - Date now = new Date(); - - Result r; - // 3a) Admin - - try { - // Originally, added the enterer as Admin, but that's not necessary, - // or helpful for Operations folks.. - // Admins can be empty, because they can be changed by lower level - // NSs - // if(ns.admin(false).isEmpty()) { - // ns.admin(true).add(user); - // } - if (namespace.admin != null) { - for (String u : namespace.admin) { - if ((r = checkValidID(trans, now, u)).notOK()) { - return r; - } - } - } - - // 3b) Responsible - Organization org = trans.org(); - for (String u : namespace.owner) { - Identity orgUser = org.getIdentity(trans, u); - if (orgUser == null) { - return Result - .err(Status.ERR_BadData, - "NS must be created with an %s approved Responsible Party", - org.getName()); - } - } - } catch (Exception e) { - return Result.err(Status.ERR_UserNotFound, e.getMessage()); - } - - // VALIDATIONS done... Add NS - if ((rq = q.nsDAO.create(trans, namespace.data())).notOK()) { - return Result.err(rq); - } - - // Since Namespace is now created, we need to grab all subsequent errors - ErrBuilder eb = new ErrBuilder(); - - // Add UserRole(s) - UserRoleDAO.Data urdd = new UserRoleDAO.Data(); - urdd.expires = trans.org().expiration(null, Expiration.UserInRole).getTime(); - urdd.role(namespace.name, Question.ADMIN); - for (String admin : namespace.admin) { - urdd.user = admin; - eb.log(q.userRoleDAO.create(trans, urdd)); - } - urdd.role(namespace.name,Question.OWNER); - for (String owner : namespace.owner) { - urdd.user = owner; - eb.log(q.userRoleDAO.create(trans, urdd)); - } - - addNSAdminRolesPerms(trans, eb, namespace.name); - - addNSOwnerRolesPerms(trans, eb, namespace.name); - - if (parent != null) { - // Build up with any errors - - String targetNs = rparent.value.name; // Get the Parent Namespace, - // not target - String targetName = namespace.name.substring(targetNs.length() + 1); // Remove the Parent Namespace from the - // Target + a dot, and you'll get the name - int targetNameDot = targetName.length() + 1; - - // 4) Change any roles with children matching this NS, and - Result> rrdc = q.roleDAO.readChildren(trans, targetNs, targetName); - if (rrdc.isOKhasData()) { - for (RoleDAO.Data rdd : rrdc.value) { - // Remove old Role from Perms, save them off - List lpdd = new ArrayList<>(); - for(String p : rdd.perms(false)) { - Result rpdd = PermDAO.Data.decode(trans,q,p); - if(rpdd.isOKhasData()) { - PermDAO.Data pdd = rpdd.value; - lpdd.add(pdd); - q.permDAO.delRole(trans, pdd, rdd); - } else{ - trans.error().log(rpdd.errorString()); - } - } - - // Save off Old keys - String delP1 = rdd.ns; - String delP2 = rdd.name; - - // Write in new key - rdd.ns = namespace.name; - rdd.name = (delP2.length() > targetNameDot) ? delP2 - .substring(targetNameDot) : ""; - - // Need to use non-cached, because switching namespaces, not - // "create" per se - if ((rq = q.roleDAO.create(trans, rdd)).isOK()) { - // Put Role back into Perm, with correct info - for(PermDAO.Data pdd : lpdd) { - q.permDAO.addRole(trans, pdd, rdd); - } - // Change data for User Roles - Result> rurd = q.userRoleDAO.readByRole(trans, rdd.fullName()); - if(rurd.isOKhasData()) { - for(UserRoleDAO.Data urd : rurd.value) { - urd.ns = rdd.ns; - urd.rname = rdd.name; - q.userRoleDAO.update(trans, urd); - } - } - // Now delete old one - rdd.ns = delP1; - rdd.name = delP2; - if ((rq = q.roleDAO.delete(trans, rdd, false)).notOK()) { - eb.log(rq); - } - } else { - eb.log(rq); - } - } - } - - // 4) Change any Permissions with children matching this NS, and - Result> rpdc = q.permDAO.readChildren(trans,targetNs, targetName); - if (rpdc.isOKhasData()) { - for (PermDAO.Data pdd : rpdc.value) { - // Remove old Perm from Roles, save them off - List lrdd = new ArrayList<>(); - - for(String rl : pdd.roles(false)) { - Result rrdd = RoleDAO.Data.decode(trans,q,rl); - if(rrdd.isOKhasData()) { - RoleDAO.Data rdd = rrdd.value; - lrdd.add(rdd); - q.roleDAO.delPerm(trans, rdd, pdd); - } else{ - trans.error().log(rrdd.errorString()); - } - } - - // Save off Old keys - String delP1 = pdd.ns; - String delP2 = pdd.type; - pdd.ns = namespace.name; - pdd.type = (delP2.length() > targetNameDot) ? delP2 - .substring(targetNameDot) : ""; - if ((rq = q.permDAO.create(trans, pdd)).isOK()) { - // Put Role back into Perm, with correct info - for(RoleDAO.Data rdd : lrdd) { - q.roleDAO.addPerm(trans, rdd, pdd); - } - - pdd.ns = delP1; - pdd.type = delP2; - if ((rq = q.permDAO.delete(trans, pdd, false)).notOK()) { - eb.log(rq); - // } else { - // Need to invalidate directly, because we're - // switching places in NS, not normal cache behavior - // q.permDAO.invalidate(trans,pdd); - } - } else { - eb.log(rq); - } - } - } - if (eb.hasErr()) { - return Result.err(Status.ERR_ActionNotCompleted,eb.sb.toString(), eb.vars()); - } - } - return Result.ok(); - } - - private void addNSAdminRolesPerms(AuthzTrans trans, ErrBuilder eb, String ns) { - // Admin Role/Perm - RoleDAO.Data rd = new RoleDAO.Data(); - rd.ns = ns; - rd.name = "admin"; - rd.description = "AAF Namespace Administrators"; - - PermDAO.Data pd = new PermDAO.Data(); - pd.ns = ns; - pd.type = "access"; - pd.instance = Question.ASTERIX; - pd.action = Question.ASTERIX; - pd.description = "AAF Namespace Write Access"; - - rd.perms = new HashSet<>(); - rd.perms.add(pd.encode()); - eb.log(q.roleDAO.create(trans, rd)); - - pd.roles = new HashSet<>(); - pd.roles.add(rd.encode()); - eb.log(q.permDAO.create(trans, pd)); - } - - private void addNSOwnerRolesPerms(AuthzTrans trans, ErrBuilder eb, String ns) { - RoleDAO.Data rd = new RoleDAO.Data(); - rd.ns = ns; - rd.name = "owner"; - rd.description = "AAF Namespace Owners"; - - PermDAO.Data pd = new PermDAO.Data(); - pd.ns = ns; - pd.type = "access"; - pd.instance = Question.ASTERIX; - pd.action = Question.READ; - pd.description = "AAF Namespace Read Access"; - - rd.perms = new HashSet<>(); - rd.perms.add(pd.encode()); - eb.log(q.roleDAO.create(trans, rd)); - - pd.roles = new HashSet<>(); - pd.roles.add(rd.encode()); - eb.log(q.permDAO.create(trans, pd)); - } - - /** - * deleteNS - * - * Delete Namespace - * - * @param trans - * @param org - * @param ns - * @param force - * @param user - * @return - * @throws DAOException - * - * - * To delete an NS, you need to: 1) validate permission to - * modify this NS 2) Find all Roles with this NS, and 2a) if - * Force, delete them, else modify to Parent NS 3) Find all - * Perms with this NS, and modify to Parent NS 3a) if Force, - * delete them, else modify to Parent NS 4) Find all IDs - * associated to this NS, and deny if exists. 5) Remove NS - */ - public Result deleteNS(AuthzTrans trans, String ns) { - boolean force = trans.requested(REQD_TYPE.force); - boolean move = trans.requested(REQD_TYPE.move); - // 1) Validate - Result> nsl; - if ((nsl = q.nsDAO.read(trans, ns)).notOKorIsEmpty()) { - return Result.err(Status.ERR_NsNotFound, "%s does not exist", ns); - } - NsDAO.Data nsd = nsl.value.get(0); - NsType nt; - if (move && !q.canMove(nt = NsType.fromType(nsd.type))) { - return Result.err(Status.ERR_Denied, "Namespace Force=move not permitted for Type %s",nt.name()); - } - - Result dnr = q.mayUser(trans, trans.user(), nsd, Access.write); - if (dnr.status != Status.OK) { - return Result.err(dnr); - } - - // 2) Find Parent - String user = trans.user(); - int idx = ns.lastIndexOf('.'); - NsDAO.Data parent; - if (idx < 0) { - if (!q.isGranted(trans, user, ROOT_NS,Question.NS, ".", "delete")) { - return Result.err(Result.ERR_Security, - "%s may not delete Root Namespaces", user); - } - parent = null; - } else { - Result rlparent = q.deriveNs(trans, ns.substring(0, idx)); - if (rlparent.notOKorIsEmpty()) { - return Result.err(rlparent); - } - parent = rlparent.value; - } - - // Build up with any errors - // If sb != null below is an indication of error - StringBuilder sb = null; - ErrBuilder er = new ErrBuilder(); - - // 2a) Deny if any IDs on Namespace - Result> creds = q.credDAO.readNS(trans, ns); - if (creds.isOKhasData()) { - if (force || move) { - for (CredDAO.Data cd : creds.value) { - er.log(q.credDAO.delete(trans, cd, false)); - // Since we're deleting all the creds, we should delete all - // the user Roles for that Cred - Result> rlurd = q.userRoleDAO - .readByUser(trans, cd.id); - if (rlurd.isOK()) { - for (UserRoleDAO.Data data : rlurd.value) { - q.userRoleDAO.delete(trans, data, false); - } - } - - } - } else { - // first possible StringBuilder Create. - sb = new StringBuilder(); - sb.append('['); - sb.append(ns); - sb.append("] contains users"); - } - } - - // 2b) Find (or delete if forced flag is set) dependencies - // First, find if NS Perms are the only ones - Result> rpdc = q.permDAO.readNS(trans, ns); - if (rpdc.isOKhasData()) { - // Since there are now NS perms, we have to count NON-NS perms. - // FYI, if we delete them now, and the NS is not deleted, it is in - // an inconsistent state. - boolean nonaccess = false; - for (PermDAO.Data pdd : rpdc.value) { - if (!"access".equals(pdd.type)) { - nonaccess = true; - break; - } - } - if (nonaccess && !force && !move) { - if (sb == null) { - sb = new StringBuilder(); - sb.append('['); - sb.append(ns); - sb.append("] contains "); - } else { - sb.append(", "); - } - sb.append("permissions"); - } - } - - Result> rrdc = q.roleDAO.readNS(trans, ns); - if (rrdc.isOKhasData()) { - // Since there are now NS roles, we have to count NON-NS roles. - // FYI, if we delete th)em now, and the NS is not deleted, it is in - // an inconsistent state. - int count = rrdc.value.size(); - for (RoleDAO.Data rdd : rrdc.value) { - if ("admin".equals(rdd.name) || "owner".equals(rdd.name)) { - --count; - } - } - if (count > 0 && !force && !move) { - if (sb == null) { - sb = new StringBuilder(); - sb.append('['); - sb.append(ns); - sb.append("] contains "); - } else { - sb.append(", "); - } - sb.append("roles"); - } - } - - // 2c) Deny if dependencies exist that would be moved to root level - // parent is root level parent here. Need to find closest parent ns that - // exists - if (sb != null) { - if (!force && !move) { - sb.append(".\n Delete dependencies and try again. Note: using \"force=true\" will delete all. \"force=move\" will delete Creds, but move Roles and Perms to parent."); - return Result.err(Status.ERR_DependencyExists, sb.toString()); - } - - if (move && (parent == null || parent.type == NsType.COMPANY.type)) { - return Result - .err(Status.ERR_DependencyExists, - "Cannot move users, roles or permissions to [%s].\nDelete dependencies and try again", - parent.name); - } - } else if (move && parent != null) { - sb = new StringBuilder(); - // 3) Change any roles with children matching this NS, and - moveRoles(trans, parent, sb, rrdc); - // 4) Change any Perms with children matching this NS, and - movePerms(trans, parent, sb, rpdc); - } - - if (sb != null && sb.length() > 0) { - return Result.err(Status.ERR_DependencyExists, sb.toString()); - } - - if (er.hasErr()) { - if (trans.debug().isLoggable()) { - trans.debug().log(er.toString()); - } - return Result.err(Status.ERR_DependencyExists, - "Namespace members cannot be deleted for %s", ns); - } - - // 5) OK... good to go for NS Deletion... - if (!rpdc.isEmpty()) { - for (PermDAO.Data perm : rpdc.value) { - deletePerm(trans, perm, true, true); - } - } - if (!rrdc.isEmpty()) { - for (RoleDAO.Data role : rrdc.value) { - deleteRole(trans, role, true, true); - } - } - - return q.nsDAO.delete(trans, nsd, false); - } - - public Result> getOwners(AuthzTrans trans, String ns, - boolean includeExpired) { - return getUsersByRole(trans, ns + Question.DOT_OWNER, includeExpired); - } - - private Result mayAddOwner(AuthzTrans trans, String ns, String id) { - Result rq = q.deriveNs(trans, ns); - if (rq.notOK()) { - return Result.err(rq); - } - - rq = q.mayUser(trans, trans.user(), rq.value, Access.write); - if (rq.notOK()) { - return Result.err(rq); - } - - Identity user; - Organization org = trans.org(); - try { - if ((user = org.getIdentity(trans, id)) == null) { - return Result.err(Status.ERR_Policy, - "%s reports that this is not a valid credential", - org.getName()); - } - String reason; - if ((reason=user.mayOwn())==null) { - return Result.ok(); - } else { - if (org.isTestEnv()) { - String reason2; - if((reason2 = org.validate(trans, Policy.AS_RESPONSIBLE, new CassExecutor(trans, this), id))==null) { - return Result.ok(); - } else { - trans.debug().log(reason2); - } - } - return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,user.fullName(),user.id(),ns, reason); - } - } catch (Exception e) { - return Result.err(e); - } - } - - private Result mayAddAdmin(AuthzTrans trans, String ns, String id) { - // Does NS Exist? - Result r = checkValidID(trans, new Date(), id); - if (r.notOK()) { - return r; - } - // Is id able to be an Admin - Result rq = q.deriveNs(trans, ns); - if (rq.notOK()) { - return Result.err(rq); - } - - rq = q.mayUser(trans, trans.user(), rq.value, Access.write); - if (rq.notOK()) { - Result> ruinr = q.userRoleDAO.readUserInRole(trans, trans.user(),ns+".owner"); - if(!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { - return Result.err(rq); - } - } - return r; - } - - private Result checkValidID(AuthzTrans trans, Date now, String user) { - Organization org = trans.org(); - if (org.supportsRealm(user)) { - try { - if (org.getIdentity(trans, user) == null) { - return Result.err(Status.ERR_Denied, - "%s reports that %s is a faulty ID", org.getName(), - user); - } - return Result.ok(); - } catch (Exception e) { - return Result.err(Result.ERR_Security, - "%s is not a valid %s Credential", user, org.getName()); - } - //TODO find out how to make sure good ALTERNATE OAUTH DOMAIN USER -// } else if(user.endsWith(ALTERNATE OAUTH DOMAIN)) { -// return Result.ok(); - } else { - Result> cdr = q.credDAO.readID(trans, user); - if (cdr.notOKorIsEmpty()) { - return Result.err(Status.ERR_Security, - "%s is not a valid AAF Credential", user); - } - - for (CredDAO.Data cd : cdr.value) { - if (cd.expires.after(now)) { - return Result.ok(); - } - } - } - return Result.err(Result.ERR_Security, "%s has expired", user); - } - - public Result delOwner(AuthzTrans trans, String ns, String id) { - Result rq = q.deriveNs(trans, ns); - if (rq.notOK()) { - return Result.err(rq); - } - - rq = q.mayUser(trans, trans.user(), rq.value, Access.write); - if (rq.notOK()) { - return Result.err(rq); - } - - return delUserRole(trans, id, ns,Question.OWNER); - } - - public Result> getAdmins(AuthzTrans trans, String ns, boolean includeExpired) { - return getUsersByRole(trans, ns + Question.DOT_ADMIN, includeExpired); - } - - public Result delAdmin(AuthzTrans trans, String ns, String id) { - Result rq = q.deriveNs(trans, ns); - if (rq.notOK()) { - return Result.err(rq); - } - - rq = q.mayUser(trans, trans.user(), rq.value, Access.write); - if (rq.notOK()) { - // Even though not a "writer", Owners still determine who gets to be an Admin - Result> ruinr = q.userRoleDAO.readUserInRole(trans, trans.user(),ns+".owner"); - if(!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { - return Result.err(rq); - } - } - - return delUserRole(trans, id, ns, Question.ADMIN); - } - - /** - * Helper function that moves permissions from a namespace being deleted to - * its parent namespace - * - * @param trans - * @param parent - * @param sb - * @param rpdc - * - list of permissions in namespace being deleted - */ - private void movePerms(AuthzTrans trans, NsDAO.Data parent, - StringBuilder sb, Result> rpdc) { - - Result rv; - Result pd; - - if (rpdc.isOKhasData()) { - for (PermDAO.Data pdd : rpdc.value) { - String delP2 = pdd.type; - if ("access".equals(delP2)) { - continue; - } - // Remove old Perm from Roles, save them off - List lrdd = new ArrayList<>(); - - for(String rl : pdd.roles(false)) { - Result rrdd = RoleDAO.Data.decode(trans,q,rl); - if(rrdd.isOKhasData()) { - RoleDAO.Data rdd = rrdd.value; - lrdd.add(rdd); - q.roleDAO.delPerm(trans, rdd, pdd); - } else{ - trans.error().log(rrdd.errorString()); - } - } - - // Save off Old keys - String delP1 = pdd.ns; - NsSplit nss = new NsSplit(parent, pdd.fullType()); - pdd.ns = nss.ns; - pdd.type = nss.name; - // Use direct Create/Delete, because switching namespaces - if ((pd = q.permDAO.create(trans, pdd)).isOK()) { - // Put Role back into Perm, with correct info - for(RoleDAO.Data rdd : lrdd) { - q.roleDAO.addPerm(trans, rdd, pdd); - } - - pdd.ns = delP1; - pdd.type = delP2; - if ((rv = q.permDAO.delete(trans, pdd, false)).notOK()) { - sb.append(rv.details); - sb.append('\n'); - // } else { - // Need to invalidate directly, because we're switching - // places in NS, not normal cache behavior - // q.permDAO.invalidate(trans,pdd); - } - } else { - sb.append(pd.details); - sb.append('\n'); - } - } - } - } - - /** - * Helper function that moves roles from a namespace being deleted to its - * parent namespace - * - * @param trans - * @param parent - * @param sb - * @param rrdc - * - list of roles in namespace being deleted - */ - private void moveRoles(AuthzTrans trans, NsDAO.Data parent, - StringBuilder sb, Result> rrdc) { - - Result rv; - Result rd; - - if (rrdc.isOKhasData()) { - for (RoleDAO.Data rdd : rrdc.value) { - String delP2 = rdd.name; - if ("admin".equals(delP2) || "owner".equals(delP2)) { - continue; - } - // Remove old Role from Perms, save them off - List lpdd = new ArrayList<>(); - for(String p : rdd.perms(false)) { - Result rpdd = PermDAO.Data.decode(trans,q,p); - if(rpdd.isOKhasData()) { - PermDAO.Data pdd = rpdd.value; - lpdd.add(pdd); - q.permDAO.delRole(trans, pdd, rdd); - } else{ - trans.error().log(rpdd.errorString()); - } - } - - // Save off Old keys - String delP1 = rdd.ns; - - NsSplit nss = new NsSplit(parent, rdd.fullName()); - rdd.ns = nss.ns; - rdd.name = nss.name; - // Use direct Create/Delete, because switching namespaces - if ((rd = q.roleDAO.create(trans, rdd)).isOK()) { - // Put Role back into Perm, with correct info - for(PermDAO.Data pdd : lpdd) { - q.permDAO.addRole(trans, pdd, rdd); - } - - rdd.ns = delP1; - rdd.name = delP2; - if ((rv = q.roleDAO.delete(trans, rdd, true)).notOK()) { - sb.append(rv.details); - sb.append('\n'); - // } else { - // Need to invalidate directly, because we're switching - // places in NS, not normal cache behavior - // q.roleDAO.invalidate(trans,rdd); - } - } else { - sb.append(rd.details); - sb.append('\n'); - } - } - } - } - - /** - * Create Permission (and any missing Permission between this and Parent) if - * we have permission - * - * Pass in the desired Management Permission for this Permission - * - * If Force is set, then Roles listed will be created, if allowed, - * pre-granted. - */ - public Result createPerm(AuthzTrans trans, PermDAO.Data perm, boolean fromApproval) { - String user = trans.user(); - // Next, see if User is allowed to Manage Parent Permission - - Result rnsd; - if (!fromApproval) { - rnsd = q.mayUser(trans, user, perm, Access.write); - if (rnsd.notOK()) { - return Result.err(rnsd); - } - } else { - rnsd = q.deriveNs(trans, perm.ns); - } - - // Does Child exist? - if (!trans.requested(REQD_TYPE.force)) { - if (q.permDAO.read(trans, perm).isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, - "Permission [%s.%s|%s|%s] already exists.", perm.ns, - perm.type, perm.instance, perm.action); - } - } - - // Attempt to add perms to roles, creating as possible - Set roles; - String pstring = perm.encode(); - - // For each Role - for (String role : roles = perm.roles(true)) { - Result rdd = RoleDAO.Data.decode(trans,q,role); - if(rdd.isOKhasData()) { - RoleDAO.Data rd = rdd.value; - if (!fromApproval) { - // May User write to the Role in question. - Result rns = q.mayUser(trans, user, rd, - Access.write); - if (rns.notOK()) { - // Remove the role from Add, because - roles.remove(role); // Don't allow adding - trans.warn() - .log("User [%s] does not have permission to relate Permissions to Role [%s]", - user, role); - } - } - - Result> rlrd; - if ((rlrd = q.roleDAO.read(trans, rd)).notOKorIsEmpty()) { - rd.perms(true).add(pstring); - if (q.roleDAO.create(trans, rd).notOK()) { - roles.remove(role); // Role doesn't exist, and can't be - // created - } - } else { - rd = rlrd.value.get(0); - if (!rd.perms.contains(pstring)) { - q.roleDAO.addPerm(trans, rd, perm); - } - } - } - } - - Result pdr = q.permDAO.create(trans, perm); - if (pdr.isOK()) { - return Result.ok(); - } else { - return Result.err(pdr); - } - } - - public Result deletePerm(final AuthzTrans trans, final PermDAO.Data perm, boolean force, boolean fromApproval) { - String user = trans.user(); - - // Next, see if User is allowed to Manage Permission - Result rnsd; - if (!fromApproval) { - rnsd = q.mayUser(trans, user, perm, Access.write); - if (rnsd.notOK()) { - return Result.err(rnsd); - } - } - // Does Perm exist? - Result> pdr = q.permDAO.read(trans, perm); - if (pdr.notOKorIsEmpty()) { - return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist.", - perm.ns,perm.type, perm.instance, perm.action); - } - // Get perm, but with rest of data. - PermDAO.Data fullperm = pdr.value.get(0); - - // Attached to any Roles? - if (fullperm.roles != null) { - if (force) { - for (String role : fullperm.roles) { - Result rv = null; - Result rrdd = RoleDAO.Data.decode(trans, q, role); - if(rrdd.isOKhasData()) { - trans.debug().log("Removing", role, "from", fullperm, "on Perm Delete"); - if ((rv = q.roleDAO.delPerm(trans, rrdd.value, fullperm)).notOK()) { - if (rv.notOK()) { - trans.error().log("Error removing Role during delFromPermRole: ", - trans.getUserPrincipal(), - rv.errorString()); - } - } - } else { - return Result.err(rrdd); - } - } - } else if (!fullperm.roles.isEmpty()) { - return Result - .err(Status.ERR_DependencyExists, - "Permission [%s.%s|%s|%s] cannot be deleted as it is attached to 1 or more roles.", - fullperm.ns, fullperm.type, fullperm.instance, fullperm.action); - } - } - - return q.permDAO.delete(trans, fullperm, false); - } - - public Result deleteRole(final AuthzTrans trans, final RoleDAO.Data role, boolean force, boolean fromApproval) { - String user = trans.user(); - - // Next, see if User is allowed to Manage Role - Result rnsd; - if (!fromApproval) { - rnsd = q.mayUser(trans, user, role, Access.write); - if (rnsd.notOK()) { - return Result.err(rnsd); - } - } - - // Are there any Users Attached to Role? - Result> urdr = q.userRoleDAO.readByRole(trans,role.fullName()); - if (force) { - if (urdr.isOKhasData()) { - for (UserRoleDAO.Data urd : urdr.value) { - q.userRoleDAO.delete(trans, urd, false); - } - } - } else if (urdr.isOKhasData()) { - return Result.err(Status.ERR_DependencyExists, - "Role [%s.%s] cannot be deleted as it is used by 1 or more Users.", - role.ns, role.name); - } - - // Does Role exist? - Result> rdr = q.roleDAO.read(trans, role); - if (rdr.notOKorIsEmpty()) { - return Result.err(Status.ERR_RoleNotFound, - "Role [%s.%s] does not exist", role.ns, role.name); - } - RoleDAO.Data fullrole = rdr.value.get(0); // full key search - - // Remove Self from Permissions... always, force or not. Force only applies to Dependencies (Users) - if (fullrole.perms != null) { - for (String perm : fullrole.perms(false)) { - Result rpd = PermDAO.Data.decode(trans,q,perm); - if (rpd.isOK()) { - trans.debug().log("Removing", perm, "from", fullrole,"on Role Delete"); - - Result r = q.permDAO.delRole(trans, rpd.value, fullrole); - if (r.notOK()) { - trans.error().log("ERR_FDR1 unable to remove",fullrole,"from",perm,':',r.status,'-',r.details); - } - } else { - trans.error().log("ERR_FDR2 Could not remove",perm,"from",fullrole); - } - } - } - return q.roleDAO.delete(trans, fullrole, false); - } - - /** - * Only owner of Permission may add to Role - * - * If force set, however, Role will be created before Grant, if User is - * allowed to create. - * - * @param trans - * @param role - * @param pd - * @return - */ - public Result addPermToRole(AuthzTrans trans, RoleDAO.Data role,PermDAO.Data pd, boolean fromApproval) { - String user = trans.user(); - - if (!fromApproval) { - Result rRoleCo = q.deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - if(rRoleCo.notOK()) { - return Result.err(rRoleCo); - } - Result rPermCo = q.deriveFirstNsForType(trans, pd.ns, NsType.COMPANY); - if(rPermCo.notOK()) { - return Result.err(rPermCo); - } - - // Not from same company - if(!rRoleCo.value.name.equals(rPermCo.value.name)) { - Result r; - // Only grant if User ALSO has Write ability in Other Company - if((r = q.mayUser(trans, user, role, Access.write)).notOK()) { - return Result.err(r); - } - } - - - // Must be Perm Admin, or Granted Special Permission - Result ucp = q.mayUser(trans, user, pd, Access.write); - if (ucp.notOK()) { - // Don't allow CLI potential Grantees to change their own AAF - // Perms, - if ((ROOT_NS.equals(pd.ns) && Question.NS.equals(pd.type)) - || !q.isGranted(trans, trans.user(),ROOT_NS,Question.PERM, rPermCo.value.name, "grant")) { - // Not otherwise granted - // TODO Needed? - return Result.err(ucp); - } - // Final Check... Don't allow Grantees to add to Roles they are - // part of - Result> rlurd = q.userRoleDAO - .readByUser(trans, trans.user()); - if (rlurd.isOK()) { - for (UserRoleDAO.Data ur : rlurd.value) { - if (role.ns.equals(ur.ns) && role.name.equals(ur.rname)) { - return Result.err(ucp); - } - } - } - } - } - - Result> rlpd = q.permDAO.read(trans, pd); - if (rlpd.notOKorIsEmpty()) { - return Result.err(Status.ERR_PermissionNotFound, - "Permission must exist to add to Role"); - } - - Result> rlrd = q.roleDAO.read(trans, role); // Already - // Checked - // for - // can - // change - // Role - Result rv; - - if (rlrd.notOKorIsEmpty()) { - if (trans.requested(REQD_TYPE.force)) { - Result ucr = q.mayUser(trans, user, role, - Access.write); - if (ucr.notOK()) { - return Result - .err(Status.ERR_Denied, - "Role [%s.%s] does not exist. User [%s] cannot create.", - role.ns, role.name, user); - } - - role.perms(true).add(pd.encode()); - Result rdd = q.roleDAO.create(trans, role); - if (rdd.isOK()) { - rv = Result.ok(); - } else { - rv = Result.err(rdd); - } - } else { - return Result.err(Status.ERR_RoleNotFound, - "Role [%s.%s] does not exist.", role.ns, role.name); - } - } else { - role = rlrd.value.get(0); - if (role.perms(false).contains(pd.encode())) { - return Result.err(Status.ERR_ConflictAlreadyExists, - "Permission [%s.%s] is already a member of role [%s,%s]", - pd.ns, pd.type, role.ns, role.name); - } - role.perms(true).add(pd.encode()); // this is added for Caching - // access purposes... doesn't - // affect addPerm - rv = q.roleDAO.addPerm(trans, role, pd); - } - if (rv.status == Status.OK) { - return q.permDAO.addRole(trans, pd, role); - // exploring how to add information message to successful http - // request - } - return rv; - } - - /** - * Either Owner of Role or Permission may delete from Role - * - * @param trans - * @param role - * @param pd - * @return - */ - public Result delPermFromRole(AuthzTrans trans, RoleDAO.Data role,PermDAO.Data pd, boolean fromApproval) { - String user = trans.user(); - if (!fromApproval) { - Result ucr = q.mayUser(trans, user, role, Access.write); - Result ucp = q.mayUser(trans, user, pd, Access.write); - - // If Can't change either Role or Perm, then deny - if (ucr.notOK() && ucp.notOK()) { - return Result.err(Status.ERR_Denied, - "User [" + trans.user() - + "] does not have permission to delete [" - + pd.encode() + "] from Role [" - + role.fullName() + ']'); - } - } - - Result> rlr = q.roleDAO.read(trans, role); - if (rlr.notOKorIsEmpty()) { - // If Bad Data, clean out - Result> rlp = q.permDAO.read(trans, pd); - if (rlp.isOKhasData()) { - for (PermDAO.Data pv : rlp.value) { - q.permDAO.delRole(trans, pv, role); - } - } - return Result.err(rlr); - } - String perm1 = pd.encode(); - boolean notFound; - if (trans.requested(REQD_TYPE.force)) { - notFound = false; - } else { // only check if force not set. - notFound = true; - for (RoleDAO.Data r : rlr.value) { - if (r.perms != null) { - for (String perm : r.perms) { - if (perm1.equals(perm)) { - notFound = false; - break; - } - } - if(!notFound) { - break; - } - } - } - } - if (notFound) { // Need to check both, in case of corruption - return Result.err(Status.ERR_PermissionNotFound, - "Permission [%s.%s|%s|%s] not associated with any Role", - pd.ns,pd.type,pd.instance,pd.action); - } - - // Read Perm for full data - Result> rlp = q.permDAO.read(trans, pd); - Result rv = null; - if (rlp.isOKhasData()) { - for (PermDAO.Data pv : rlp.value) { - if ((rv = q.permDAO.delRole(trans, pv, role)).isOK()) { - if ((rv = q.roleDAO.delPerm(trans, role, pv)).notOK()) { - trans.error().log( - "Error removing Perm during delFromPermRole:", - trans.getUserPrincipal(), rv.errorString()); - } - } else { - trans.error().log( - "Error removing Role during delFromPermRole:", - trans.getUserPrincipal(), rv.errorString()); - } - } - } else { - rv = q.roleDAO.delPerm(trans, role, pd); - if (rv.notOK()) { - trans.error().log("Error removing Role during delFromPermRole", - rv.errorString()); - } - } - return rv == null ? Result.ok() : rv; - } - - public Result delPermFromRole(AuthzTrans trans, String role,PermDAO.Data pd) { - Result nss = q.deriveNsSplit(trans, role); - if (nss.notOK()) { - return Result.err(nss); - } - RoleDAO.Data rd = new RoleDAO.Data(); - rd.ns = nss.value.ns; - rd.name = nss.value.name; - return delPermFromRole(trans, rd, pd, false); - } - - /** - * Add a User to Role - * - * 1) Role must exist 2) User must be a known Credential (i.e. mechID ok if - * Credential) or known Organizational User - * - * @param trans - * @param org - * @param urData - * @return - * @throws DAOException - */ - public Result addUserRole(AuthzTrans trans,UserRoleDAO.Data urData) { - Result rv; - if(Question.ADMIN.equals(urData.rname)) { - rv = mayAddAdmin(trans, urData.ns, urData.user); - } else if(Question.OWNER.equals(urData.rname)) { - rv = mayAddOwner(trans, urData.ns, urData.user); - } else { - rv = checkValidID(trans, new Date(), urData.user); - } - if(rv.notOK()) { - return rv; - } - - // Check if record exists - if (q.userRoleDAO.read(trans, urData).isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, - "User Role exists"); - } - if (q.roleDAO.read(trans, urData.ns, urData.rname).notOKorIsEmpty()) { - return Result.err(Status.ERR_RoleNotFound, - "Role [%s.%s] does not exist", urData.ns, urData.rname); - } - - urData.expires = trans.org().expiration(null, Expiration.UserInRole, urData.user).getTime(); - - - Result udr = q.userRoleDAO.create(trans, urData); - switch (udr.status) { - case OK: - return Result.ok(); - default: - return Result.err(udr); - } - } - - public Result addUserRole(AuthzTrans trans, String user, String ns, String rname) { - try { - if(trans.org().getIdentity(trans, user)==null) { - return Result.err(Result.ERR_BadData,user+" is an Invalid Identity for " + trans.org().getName()); - } - } catch (OrganizationException e) { - return Result.err(e); - } - UserRoleDAO.Data urdd = new UserRoleDAO.Data(); - urdd.ns = ns; - urdd.role(ns, rname); - urdd.user = user; - return addUserRole(trans,urdd); - } - - /** - * Extend User Role. - * - * extend the Expiration data, according to Organization rules. - * - * @param trans - * @param org - * @param urData - * @return - */ - public Result extendUserRole(AuthzTrans trans, UserRoleDAO.Data urData, boolean checkForExist) { - // Check if record still exists - if (checkForExist && q.userRoleDAO.read(trans, urData).notOKorIsEmpty()) { - return Result.err(Status.ERR_UserRoleNotFound, - "User Role does not exist"); - } - - if (q.roleDAO.read(trans, urData.ns, urData.rname).notOKorIsEmpty()) { - return Result.err(Status.ERR_RoleNotFound, - "Role [%s.%s] does not exist", urData.ns,urData.rname); - } - // Special case for "Admin" roles. Issue brought forward with Prod - // problem 9/26 - Date now = new Date(); - GregorianCalendar gc = new GregorianCalendar(); - gc.setTime(now.after(urData.expires)?now:urData.expires); - urData.expires = trans.org().expiration(gc, Expiration.UserInRole).getTime(); // get - // Full - // time - // starting - // today - return q.userRoleDAO.update(trans, urData); - } - - // //////////////////////////////////////////////////// - // Special User Role Functions - // These exist, because User Roles have Expiration dates, which must be - // accounted for - // Also, as of July, 2015, Namespace Owners and Admins are now regular User - // Roles - // //////////////////////////////////////////////////// - public Result> getUsersByRole(AuthzTrans trans, String role, boolean includeExpired) { - Result> rurdd = q.userRoleDAO.readByRole(trans,role); - if (rurdd.notOK()) { - return Result.err(rurdd); - } - Date now = new Date(); - List list = rurdd.value; - List rv = new ArrayList<>(list.size()); // presize - for (UserRoleDAO.Data urdd : rurdd.value) { - if (includeExpired || urdd.expires.after(now)) { - rv.add(urdd.user); - } - } - return Result.ok(rv); - } - - public Result delUserRole(AuthzTrans trans, String user, String ns, String rname) { - UserRoleDAO.Data urdd = new UserRoleDAO.Data(); - urdd.user = user; - urdd.role(ns,rname); - Result> r = q.userRoleDAO.read(trans, urdd); - if (r.status == 404 || r.isEmpty()) { - return Result.err(Status.ERR_UserRoleNotFound, - "UserRole [%s] [%s.%s]", user, ns, rname); - } - if (r.notOK()) { - return Result.err(r); - } - - return q.userRoleDAO.delete(trans, urdd, false); - } - - public Result createFuture(AuthzTrans trans, FutureDAO.Data data, String id, String user, - NsDAO.Data nsd, FUTURE_OP op) { - StringBuilder sb = new StringBuilder(); - try { - Organization org = trans.org(); - // For Reapproval, only check Owners.. Do Supervisors, etc, separately - List approvers = op.equals(FUTURE_OP.A)?NO_ADDL_APPROVE:org.getApprovers(trans, user); - List owners = new ArrayList<>(); - if (nsd != null) { - Result> rrbr = q.userRoleDAO - .readByRole(trans, nsd.name + Question.DOT_OWNER); - if (rrbr.isOKhasData()) { - for(UserRoleDAO.Data urd : rrbr.value) { - Identity owner = org.getIdentity(trans, urd.user); - if(owner==null) { - return Result.err(Result.ERR_NotFound,urd.user + " is not a Valid Owner of " + nsd.name); - } else { - owners.add(owner); - } - } - } - } - - if(owners.isEmpty()) { - return Result.err(Result.ERR_NotFound,"No Owners found for " + nsd.name); - } - - // Create Future Object - - Result fr = q.futureDAO.create(trans, data, id); - if (fr.isOK()) { - sb.append("Created Future: "); - sb.append(data.id); - // User Future ID as ticket for Approvals - final UUID ticket = fr.value.id; - sb.append(", Approvals: "); - Boolean first[] = new Boolean[]{true}; - if(op!=FUTURE_OP.A) { - for (Identity u : approvers) { - Result r = addIdentity(trans,sb,first,user,data.memo,op,u,ticket,org.getApproverType()); - if(r.notOK()) { - return Result.err(r); - } - } - } - for (Identity u : owners) { - Result r = addIdentity(trans,sb,first,user,data.memo,op,u,ticket,"owner"); - if(r.notOK()) { - return Result.err(r); - } - } - } - } catch (Exception e) { - return Result.err(e); - } - - return Result.ok(sb.toString()); - } - - /* - * This interface is to allow performFutureOps with either Realtime Data, or Batched lookups (See Expiring) - */ - public interface Lookup { - T get(AuthzTrans trans, Object ... keys); - } - - public Lookup urDBLookup = new Lookup() { - @Override - public UserRoleDAO.Data get(AuthzTrans trans, Object ... keys) { - Result> r = q.userRoleDAO.read(trans, keys); - if(r.isOKhasData()) { - return r.value.get(0); - } else { - return null; - } - } - }; - - /** - * Note: if "allApprovals for Ticket is null, it will be looked up. - * if "fdd" is null, it will be looked up, but - * - * They can be passed for performance reasons. - * - * @param trans - * @param cd - * @param allApprovalsForTicket - * @return - */ - public Result performFutureOp(final AuthzTrans trans, FUTURE_OP fop, FutureDAO.Data curr, Lookup> la, Lookup lur) { - // Pre-Evaluate if ReApproval is already done. - UserRoleDAO.Data urdd = null; - if(fop.equals(FUTURE_OP.A) && curr.target.equals(FOP_USER_ROLE) && curr.construct!=null) { - try { - // Get Expected UserRole from Future - urdd = new UserRoleDAO.Data(); - urdd.reconstitute(curr.construct); - // Get Current UserRole from lookup - UserRoleDAO.Data lurdd = lur.get(trans, urdd.user,urdd.role); - if(lurdd==null) { - q.futureDAO.delete(trans, curr, false); - return OP_STATUS.RL; - } else { - if(curr.expires.compareTo(lurdd.expires)<0) { - q.futureDAO.delete(trans, curr, false); - return OP_STATUS.RL; - } - } - } catch (IOException e) { - return Result.err(Result.ERR_BadData,"Cannot reconstitute %1",curr.memo); - } - } - - boolean aDenial = false; - int cntSuper=0, appSuper=0,cntOwner=0, appOwner=0; - for(ApprovalDAO.Data add : la.get(trans)) { - switch(add.status) { - case "approved": - if("owner".equals(add.type)) { - ++cntOwner; - ++appOwner; - } else if("supervisor".equals(add.type)) { - ++cntSuper; - ++appSuper; - } - break; - case "pending": - if("owner".equals(add.type)) { - ++cntOwner; - } else if("supervisor".equals(add.type)) { - ++cntSuper; - } - break; - case "denied": - aDenial=true; - break; - } - } - - Result ros=null; - if(aDenial) { - // Note: Denial will be Audit-logged. -// for (ApprovalDAO.Data ad : allApprovalsForTicket.value) { -// q.approvalDAO.delete(trans, ad, false); -// } - ros = OP_STATUS.RD; - if(q.futureDAO.delete(trans, curr, false).notOK()) { - trans.info().printf("Future %s could not be deleted", curr.id.toString()); - } else { - if (FOP_USER_ROLE.equalsIgnoreCase(curr.target)) { - // A Denial means we must remove UserRole - if(fop.equals(FUTURE_OP.U) || fop.equals(FUTURE_OP.A)) { - UserRoleDAO.Data data = new UserRoleDAO.Data(); - try { - data.reconstitute(curr.construct); - } catch (IOException e) { - trans.error().log("Cannot reconstitue",curr.memo); - } - ros = set(OP_STATUS.RD,delUserRole(trans, data.user, data.ns, data.rname)); - } - } - } - } - - // Decision: If not Denied, and at least owner, if exists, and at least one Super, if exists - boolean goDecision = (cntOwner>0?appOwner>0:true) && (cntSuper>0?appSuper>0:true); - - if(goDecision) { - // should check if any other pendings before performing - // actions - try { - if (FOP_ROLE.equalsIgnoreCase(curr.target)) { - RoleDAO.Data data = new RoleDAO.Data(); - data.reconstitute(curr.construct); - switch(fop) { - case C: - ros = set(OP_STATUS.RE,q.roleDAO.dao().create(trans, data)); - break; - case D: - ros = set(OP_STATUS.RE,deleteRole(trans, data, true, true)); - break; - default: - } - } else if (FOP_PERM.equalsIgnoreCase(curr.target)) { - PermDAO.Data pdd = new PermDAO.Data(); - pdd.reconstitute(curr.construct); - Set roles; - Result rrdd; - switch(fop) { - case C: - ros = set(OP_STATUS.RE,createPerm(trans, pdd, true)); - break; - case D: - ros = set(OP_STATUS.RE,deletePerm(trans, pdd, true, true)); - break; - case G: - roles = pdd.roles(true); - for (String roleStr : roles) { - rrdd = RoleDAO.Data.decode(trans, q, roleStr); - if (rrdd.isOKhasData()) { - ros = set(OP_STATUS.RE,addPermToRole(trans, rrdd.value, pdd, true)); - } else { - trans.error().log(rrdd.errorString()); - } - } - break; - case UG: - roles = pdd.roles(true); - for (String roleStr : roles) { - rrdd = RoleDAO.Data.decode(trans, q, roleStr); - if (rrdd.isOKhasData()) { - ros = set(OP_STATUS.RE,delPermFromRole(trans, rrdd.value, pdd, true)); - } else { - trans.error().log(rrdd.errorString()); - } - } - break; - default: - } - } else if (FOP_USER_ROLE.equalsIgnoreCase(curr.target)) { - if(urdd==null) { - urdd = new UserRoleDAO.Data(); - urdd.reconstitute(curr.construct); - } - // if I am the last to approve, create user role - switch(fop) { - case C: - ros = set(OP_STATUS.RE,addUserRole(trans, urdd)); - break; - case U: - case A: - ros = set(OP_STATUS.RE,extendUserRole(trans,urdd,true)); - break; - default: - } - } else if (FOP_NS.equalsIgnoreCase(curr.target)) { - Namespace namespace = new Namespace(); - namespace.reconstitute(curr.construct); - switch(fop) { - case C: - ros = set(OP_STATUS.RE,createNS(trans, namespace, true)); - break; - default: - } - } else if (FOP_DELEGATE.equalsIgnoreCase(curr.target)) { - DelegateDAO.Data data = new DelegateDAO.Data(); - data.reconstitute(curr.construct); - switch(fop) { - case C: - ros = set(OP_STATUS.RE,q.delegateDAO.create(trans, data)); - break; - case U: - ros = set(OP_STATUS.RE,q.delegateDAO.update(trans, data)); - break; - default: - } - } else if (FOP_CRED.equalsIgnoreCase(curr.target)) { - CredDAO.Data data = new CredDAO.Data(); - data.reconstitute(curr.construct); - switch(fop) { - case C: - ros = set(OP_STATUS.RE,q.credDAO.dao().create(trans, data)); - break; - default: - } - } - } catch (Exception e) { - trans.error().log("Exception: ", e.getMessage(), - " \n occurred while performing", curr.memo, - " from Ticket ", curr.id.toString()); - } - q.futureDAO.delete(trans, curr, false); - } // end for goDecision - if(ros==null) { - //return Result.err(Status.ACC_Future, "Full Approvals not obtained: No action taken"); - ros = OP_STATUS.RP; - } - - return ros; - } - - // Convenience method for setting OPSTatus Results - private Result set(Result rs, Result orig) { - if(orig.isOK()) { - return rs; - } else { - return Result.err(orig); - } - } - - private Result addIdentity(AuthzTrans trans, StringBuilder sb, - Boolean[] first, String user, String memo, FUTURE_OP op, Identity u, UUID ticket, String type) throws OrganizationException { - ApprovalDAO.Data ad = new ApprovalDAO.Data(); - // Note ad.id is set by ApprovalDAO Create - ad.ticket = ticket; - ad.user = user; - ad.approver = u.fullID(); - ad.status = ApprovalDAO.PENDING; - ad.memo = memo; - ad.type = type; - ad.operation = op.name(); - // Note ad.updated is created in System - Result r = q.approvalDAO.create(trans,ad); - if(r.isOK()) { - if(first[0]) { - first[0] = false; - } else { - sb.append(", "); - } - sb.append(r.value.user); - sb.append(':'); - sb.append(r.value.ticket); - return r; - } else { - return Result.err(Status.ERR_ActionNotCompleted, - "Approval for %s, %s could not be created: %s", - ad.user, ad.approver, - r.details, sb.toString()); - } - } - - public Executor newExecutor(AuthzTrans trans) { - return new CassExecutor(trans, this); - } + private static final String CANNOT_BE_THE_OWNER_OF_A_NAMESPACE = "%s(%s) cannot be the owner of the namespace '%s'. Owners %s."; + + public enum FUTURE_OP { + C("Create"),U("Update"),D("Delete"),G("Grant"),UG("UnGrant"),A("Approval"); + + private String desc; + + private FUTURE_OP(String desc) { + this.desc = desc; + } + + public String desc() { + return desc; + } + + /** + * Same as valueOf(), but passes back null instead of throwing Exception + * @param value + * @return + */ + public static FUTURE_OP toFO(String value) { + if(value!=null) { + for(FUTURE_OP fo : values()) { + if(fo.name().equals(value)){ + return fo; + } + } + } + return null; + } + } + + public enum OP_STATUS { + E("Executed"),D("Denied"),P("Pending"),L("Lapsed"); + + private String desc; + public final static Result RE = Result.ok(OP_STATUS.E); + public final static Result RD = Result.ok(OP_STATUS.D); + public final static Result RP = Result.ok(OP_STATUS.P); + public final static Result RL = Result.ok(OP_STATUS.L); + + private OP_STATUS(String desc) { + this.desc = desc; + } + + public String desc() { + return desc; + } + + } + + public static final String FOP_CRED = "cred"; + public static final String FOP_DELEGATE = "delegate"; + public static final String FOP_NS = "ns"; + public static final String FOP_PERM = "perm"; + public static final String FOP_ROLE = "role"; + public static final String FOP_USER_ROLE = "user_role"; + private static final List NO_ADDL_APPROVE = new ArrayList<>(); + private static final String ROOT_NS = Define.ROOT_NS(); + // First Action should ALWAYS be "write", see "CreateRole" + public final Question q; + + public Function(AuthzTrans trans, Question question) { + q = question; + } + + private class ErrBuilder { + private StringBuilder sb; + private List ao; + + public void log(Result result) { + if (result.notOK()) { + if (sb == null) { + sb = new StringBuilder(); + ao = new ArrayList<>(); + } + sb.append(result.details); + sb.append('\n'); + for (String s : result.variables) { + ao.add(s); + } + } + } + + public String[] vars() { + String[] rv = new String[ao.size()]; + ao.toArray(rv); + return rv; + } + + public boolean hasErr() { + return sb != null; + } + + @Override + public String toString() { + return sb == null ? "" : String.format(sb.toString(), ao); + } + } + + /** + * createNS + * + * Create Namespace + * + * @param trans + * @param org + * @param ns + * @param user + * @return + * @throws DAOException + * + * To create an NS, you need to: 1) validate permission to + * modify parent NS 2) Does NS exist already? 3) Create NS with + * a) "user" as owner. NOTE: Per 10-15 request for AAF 1.0 4) + * Loop through Roles with Parent NS, and map any that start + * with this NS into this one 5) Loop through Perms with Parent + * NS, and map any that start with this NS into this one + */ + public Result createNS(AuthzTrans trans, Namespace namespace, boolean fromApproval) { + Result rq; +// if (namespace.name.endsWith(Question.DOT_ADMIN) +// || namespace.name.endsWith(Question.DOT_OWNER)) { +// return Result.err(Status.ERR_BadData, +// "'admin' and 'owner' are reserved names in AAF"); +// } + + try { + for (String u : namespace.owner) { + Organization org = trans.org(); + Identity orgUser = org.getIdentity(trans, u); + String reason; + if (orgUser == null) { + return Result.err(Status.ERR_Policy,"%s is not a valid user at %s",u,org.getName()); + } else if((reason=orgUser.mayOwn())!=null) { + if (org.isTestEnv()) { + String reason2; + if((reason2=org.validate(trans, Policy.AS_RESPONSIBLE,new CassExecutor(trans, this), u))!=null) { // can masquerade as responsible + trans.debug().log(reason2); + return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,orgUser.fullName(),orgUser.id(),namespace.name,reason); + } + // a null means ok + } else { + if(orgUser.isFound()) { + return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,orgUser.fullName(),orgUser.id(),namespace.name, reason); + } else { + return Result.err(Status.ERR_Policy,u + " is an invalid Identity"); + } + } + } + } + } catch (Exception e) { + trans.error().log(e, + "Could not contact Organization for User Validation"); + } + + String user = trans.user(); + // 1) May Change Parent? + int idx = namespace.name.lastIndexOf('.'); + String parent; + if (idx < 0) { + if (!q.isGranted(trans, user, ROOT_NS,Question.NS, ".", "create")) { + return Result.err(Result.ERR_Security, + "%s may not create Root Namespaces", user); + } + parent = null; + fromApproval = true; + } else { + parent = namespace.name.substring(0, idx); // get Parent String + } + + Result rparent = q.deriveNs(trans, parent); + if (rparent.notOK()) { + return Result.err(rparent); + } + if (!fromApproval) { + rparent = q.mayUser(trans, user, rparent.value, Access.write); + if (rparent.notOK()) { + return Result.err(rparent); + } + } + parent = namespace.parent = rparent.value.name; // Correct Namespace from real data + + // 2) Does requested NS exist + if (q.nsDAO.read(trans, namespace.name).isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, + "Target Namespace already exists"); + } + + // Someone must be responsible. + if (namespace.owner == null || namespace.owner.isEmpty()) { + return Result + .err(Status.ERR_Policy, + "Namespaces must be assigned at least one responsible party"); + } + + // 3) Create NS + Date now = new Date(); + + Result r; + // 3a) Admin + + try { + // Originally, added the enterer as Admin, but that's not necessary, + // or helpful for Operations folks.. + // Admins can be empty, because they can be changed by lower level + // NSs + // if(ns.admin(false).isEmpty()) { + // ns.admin(true).add(user); + // } + if (namespace.admin != null) { + for (String u : namespace.admin) { + if ((r = checkValidID(trans, now, u)).notOK()) { + return r; + } + } + } + + // 3b) Responsible + Organization org = trans.org(); + for (String u : namespace.owner) { + Identity orgUser = org.getIdentity(trans, u); + if (orgUser == null) { + return Result + .err(Status.ERR_BadData, + "NS must be created with an %s approved Responsible Party", + org.getName()); + } + } + } catch (Exception e) { + return Result.err(Status.ERR_UserNotFound, e.getMessage()); + } + + // VALIDATIONS done... Add NS + if ((rq = q.nsDAO.create(trans, namespace.data())).notOK()) { + return Result.err(rq); + } + + // Since Namespace is now created, we need to grab all subsequent errors + ErrBuilder eb = new ErrBuilder(); + + // Add UserRole(s) + UserRoleDAO.Data urdd = new UserRoleDAO.Data(); + urdd.expires = trans.org().expiration(null, Expiration.UserInRole).getTime(); + urdd.role(namespace.name, Question.ADMIN); + for (String admin : namespace.admin) { + urdd.user = admin; + eb.log(q.userRoleDAO.create(trans, urdd)); + } + urdd.role(namespace.name,Question.OWNER); + for (String owner : namespace.owner) { + urdd.user = owner; + eb.log(q.userRoleDAO.create(trans, urdd)); + } + + addNSAdminRolesPerms(trans, eb, namespace.name); + + addNSOwnerRolesPerms(trans, eb, namespace.name); + + if (parent != null) { + // Build up with any errors + + String targetNs = rparent.value.name; // Get the Parent Namespace, + // not target + String targetName = namespace.name.substring(targetNs.length() + 1); // Remove the Parent Namespace from the + // Target + a dot, and you'll get the name + int targetNameDot = targetName.length() + 1; + + // 4) Change any roles with children matching this NS, and + Result> rrdc = q.roleDAO.readChildren(trans, targetNs, targetName); + if (rrdc.isOKhasData()) { + for (RoleDAO.Data rdd : rrdc.value) { + // Remove old Role from Perms, save them off + List lpdd = new ArrayList<>(); + for(String p : rdd.perms(false)) { + Result rpdd = PermDAO.Data.decode(trans,q,p); + if(rpdd.isOKhasData()) { + PermDAO.Data pdd = rpdd.value; + lpdd.add(pdd); + q.permDAO.delRole(trans, pdd, rdd); + } else{ + trans.error().log(rpdd.errorString()); + } + } + + // Save off Old keys + String delP1 = rdd.ns; + String delP2 = rdd.name; + + // Write in new key + rdd.ns = namespace.name; + rdd.name = (delP2.length() > targetNameDot) ? delP2 + .substring(targetNameDot) : ""; + + // Need to use non-cached, because switching namespaces, not + // "create" per se + if ((rq = q.roleDAO.create(trans, rdd)).isOK()) { + // Put Role back into Perm, with correct info + for(PermDAO.Data pdd : lpdd) { + q.permDAO.addRole(trans, pdd, rdd); + } + // Change data for User Roles + Result> rurd = q.userRoleDAO.readByRole(trans, rdd.fullName()); + if(rurd.isOKhasData()) { + for(UserRoleDAO.Data urd : rurd.value) { + urd.ns = rdd.ns; + urd.rname = rdd.name; + q.userRoleDAO.update(trans, urd); + } + } + // Now delete old one + rdd.ns = delP1; + rdd.name = delP2; + if ((rq = q.roleDAO.delete(trans, rdd, false)).notOK()) { + eb.log(rq); + } + } else { + eb.log(rq); + } + } + } + + // 4) Change any Permissions with children matching this NS, and + Result> rpdc = q.permDAO.readChildren(trans,targetNs, targetName); + if (rpdc.isOKhasData()) { + for (PermDAO.Data pdd : rpdc.value) { + // Remove old Perm from Roles, save them off + List lrdd = new ArrayList<>(); + + for(String rl : pdd.roles(false)) { + Result rrdd = RoleDAO.Data.decode(trans,q,rl); + if(rrdd.isOKhasData()) { + RoleDAO.Data rdd = rrdd.value; + lrdd.add(rdd); + q.roleDAO.delPerm(trans, rdd, pdd); + } else{ + trans.error().log(rrdd.errorString()); + } + } + + // Save off Old keys + String delP1 = pdd.ns; + String delP2 = pdd.type; + pdd.ns = namespace.name; + pdd.type = (delP2.length() > targetNameDot) ? delP2 + .substring(targetNameDot) : ""; + if ((rq = q.permDAO.create(trans, pdd)).isOK()) { + // Put Role back into Perm, with correct info + for(RoleDAO.Data rdd : lrdd) { + q.roleDAO.addPerm(trans, rdd, pdd); + } + + pdd.ns = delP1; + pdd.type = delP2; + if ((rq = q.permDAO.delete(trans, pdd, false)).notOK()) { + eb.log(rq); + // } else { + // Need to invalidate directly, because we're + // switching places in NS, not normal cache behavior + // q.permDAO.invalidate(trans,pdd); + } + } else { + eb.log(rq); + } + } + } + if (eb.hasErr()) { + return Result.err(Status.ERR_ActionNotCompleted,eb.sb.toString(), eb.vars()); + } + } + return Result.ok(); + } + + private void addNSAdminRolesPerms(AuthzTrans trans, ErrBuilder eb, String ns) { + // Admin Role/Perm + RoleDAO.Data rd = new RoleDAO.Data(); + rd.ns = ns; + rd.name = "admin"; + rd.description = "AAF Namespace Administrators"; + + PermDAO.Data pd = new PermDAO.Data(); + pd.ns = ns; + pd.type = "access"; + pd.instance = Question.ASTERIX; + pd.action = Question.ASTERIX; + pd.description = "AAF Namespace Write Access"; + + rd.perms = new HashSet<>(); + rd.perms.add(pd.encode()); + eb.log(q.roleDAO.create(trans, rd)); + + pd.roles = new HashSet<>(); + pd.roles.add(rd.encode()); + eb.log(q.permDAO.create(trans, pd)); + } + + private void addNSOwnerRolesPerms(AuthzTrans trans, ErrBuilder eb, String ns) { + RoleDAO.Data rd = new RoleDAO.Data(); + rd.ns = ns; + rd.name = "owner"; + rd.description = "AAF Namespace Owners"; + + PermDAO.Data pd = new PermDAO.Data(); + pd.ns = ns; + pd.type = "access"; + pd.instance = Question.ASTERIX; + pd.action = Question.READ; + pd.description = "AAF Namespace Read Access"; + + rd.perms = new HashSet<>(); + rd.perms.add(pd.encode()); + eb.log(q.roleDAO.create(trans, rd)); + + pd.roles = new HashSet<>(); + pd.roles.add(rd.encode()); + eb.log(q.permDAO.create(trans, pd)); + } + + /** + * deleteNS + * + * Delete Namespace + * + * @param trans + * @param org + * @param ns + * @param force + * @param user + * @return + * @throws DAOException + * + * + * To delete an NS, you need to: 1) validate permission to + * modify this NS 2) Find all Roles with this NS, and 2a) if + * Force, delete them, else modify to Parent NS 3) Find all + * Perms with this NS, and modify to Parent NS 3a) if Force, + * delete them, else modify to Parent NS 4) Find all IDs + * associated to this NS, and deny if exists. 5) Remove NS + */ + public Result deleteNS(AuthzTrans trans, String ns) { + boolean force = trans.requested(REQD_TYPE.force); + boolean move = trans.requested(REQD_TYPE.move); + // 1) Validate + Result> nsl; + if ((nsl = q.nsDAO.read(trans, ns)).notOKorIsEmpty()) { + return Result.err(Status.ERR_NsNotFound, "%s does not exist", ns); + } + NsDAO.Data nsd = nsl.value.get(0); + NsType nt; + if (move && !q.canMove(nt = NsType.fromType(nsd.type))) { + return Result.err(Status.ERR_Denied, "Namespace Force=move not permitted for Type %s",nt.name()); + } + + Result dnr = q.mayUser(trans, trans.user(), nsd, Access.write); + if (dnr.status != Status.OK) { + return Result.err(dnr); + } + + // 2) Find Parent + String user = trans.user(); + int idx = ns.lastIndexOf('.'); + NsDAO.Data parent; + if (idx < 0) { + if (!q.isGranted(trans, user, ROOT_NS,Question.NS, ".", "delete")) { + return Result.err(Result.ERR_Security, + "%s may not delete Root Namespaces", user); + } + parent = null; + } else { + Result rlparent = q.deriveNs(trans, ns.substring(0, idx)); + if (rlparent.notOKorIsEmpty()) { + return Result.err(rlparent); + } + parent = rlparent.value; + } + + // Build up with any errors + // If sb != null below is an indication of error + StringBuilder sb = null; + ErrBuilder er = new ErrBuilder(); + + // 2a) Deny if any IDs on Namespace + Result> creds = q.credDAO.readNS(trans, ns); + if (creds.isOKhasData()) { + if (force || move) { + for (CredDAO.Data cd : creds.value) { + er.log(q.credDAO.delete(trans, cd, false)); + // Since we're deleting all the creds, we should delete all + // the user Roles for that Cred + Result> rlurd = q.userRoleDAO + .readByUser(trans, cd.id); + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { + q.userRoleDAO.delete(trans, data, false); + } + } + + } + } else { + // first possible StringBuilder Create. + sb = new StringBuilder(); + sb.append('['); + sb.append(ns); + sb.append("] contains users"); + } + } + + // 2b) Find (or delete if forced flag is set) dependencies + // First, find if NS Perms are the only ones + Result> rpdc = q.permDAO.readNS(trans, ns); + if (rpdc.isOKhasData()) { + // Since there are now NS perms, we have to count NON-NS perms. + // FYI, if we delete them now, and the NS is not deleted, it is in + // an inconsistent state. + boolean nonaccess = false; + for (PermDAO.Data pdd : rpdc.value) { + if (!"access".equals(pdd.type)) { + nonaccess = true; + break; + } + } + if (nonaccess && !force && !move) { + if (sb == null) { + sb = new StringBuilder(); + sb.append('['); + sb.append(ns); + sb.append("] contains "); + } else { + sb.append(", "); + } + sb.append("permissions"); + } + } + + Result> rrdc = q.roleDAO.readNS(trans, ns); + if (rrdc.isOKhasData()) { + // Since there are now NS roles, we have to count NON-NS roles. + // FYI, if we delete th)em now, and the NS is not deleted, it is in + // an inconsistent state. + int count = rrdc.value.size(); + for (RoleDAO.Data rdd : rrdc.value) { + if ("admin".equals(rdd.name) || "owner".equals(rdd.name)) { + --count; + } + } + if (count > 0 && !force && !move) { + if (sb == null) { + sb = new StringBuilder(); + sb.append('['); + sb.append(ns); + sb.append("] contains "); + } else { + sb.append(", "); + } + sb.append("roles"); + } + } + + // 2c) Deny if dependencies exist that would be moved to root level + // parent is root level parent here. Need to find closest parent ns that + // exists + if (sb != null) { + if (!force && !move) { + sb.append(".\n Delete dependencies and try again. Note: using \"force=true\" will delete all. \"force=move\" will delete Creds, but move Roles and Perms to parent."); + return Result.err(Status.ERR_DependencyExists, sb.toString()); + } + + if (move && (parent == null || parent.type == NsType.COMPANY.type)) { + return Result + .err(Status.ERR_DependencyExists, + "Cannot move users, roles or permissions to [%s].\nDelete dependencies and try again", + parent.name); + } + } else if (move && parent != null) { + sb = new StringBuilder(); + // 3) Change any roles with children matching this NS, and + moveRoles(trans, parent, sb, rrdc); + // 4) Change any Perms with children matching this NS, and + movePerms(trans, parent, sb, rpdc); + } + + if (sb != null && sb.length() > 0) { + return Result.err(Status.ERR_DependencyExists, sb.toString()); + } + + if (er.hasErr()) { + if (trans.debug().isLoggable()) { + trans.debug().log(er.toString()); + } + return Result.err(Status.ERR_DependencyExists, + "Namespace members cannot be deleted for %s", ns); + } + + // 5) OK... good to go for NS Deletion... + if (!rpdc.isEmpty()) { + for (PermDAO.Data perm : rpdc.value) { + deletePerm(trans, perm, true, true); + } + } + if (!rrdc.isEmpty()) { + for (RoleDAO.Data role : rrdc.value) { + deleteRole(trans, role, true, true); + } + } + + return q.nsDAO.delete(trans, nsd, false); + } + + public Result> getOwners(AuthzTrans trans, String ns, + boolean includeExpired) { + return getUsersByRole(trans, ns + Question.DOT_OWNER, includeExpired); + } + + private Result mayAddOwner(AuthzTrans trans, String ns, String id) { + Result rq = q.deriveNs(trans, ns); + if (rq.notOK()) { + return Result.err(rq); + } + + rq = q.mayUser(trans, trans.user(), rq.value, Access.write); + if (rq.notOK()) { + return Result.err(rq); + } + + Identity user; + Organization org = trans.org(); + try { + if ((user = org.getIdentity(trans, id)) == null) { + return Result.err(Status.ERR_Policy, + "%s reports that this is not a valid credential", + org.getName()); + } + String reason; + if ((reason=user.mayOwn())==null) { + return Result.ok(); + } else { + if (org.isTestEnv()) { + String reason2; + if((reason2 = org.validate(trans, Policy.AS_RESPONSIBLE, new CassExecutor(trans, this), id))==null) { + return Result.ok(); + } else { + trans.debug().log(reason2); + } + } + return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,user.fullName(),user.id(),ns, reason); + } + } catch (Exception e) { + return Result.err(e); + } + } + + private Result mayAddAdmin(AuthzTrans trans, String ns, String id) { + // Does NS Exist? + Result r = checkValidID(trans, new Date(), id); + if (r.notOK()) { + return r; + } + // Is id able to be an Admin + Result rq = q.deriveNs(trans, ns); + if (rq.notOK()) { + return Result.err(rq); + } + + rq = q.mayUser(trans, trans.user(), rq.value, Access.write); + if (rq.notOK()) { + Result> ruinr = q.userRoleDAO.readUserInRole(trans, trans.user(),ns+".owner"); + if(!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { + return Result.err(rq); + } + } + return r; + } + + private Result checkValidID(AuthzTrans trans, Date now, String user) { + Organization org = trans.org(); + if (org.supportsRealm(user)) { + try { + if (org.getIdentity(trans, user) == null) { + return Result.err(Status.ERR_Denied, + "%s reports that %s is a faulty ID", org.getName(), + user); + } + return Result.ok(); + } catch (Exception e) { + return Result.err(Result.ERR_Security, + "%s is not a valid %s Credential", user, org.getName()); + } + //TODO find out how to make sure good ALTERNATE OAUTH DOMAIN USER +// } else if(user.endsWith(ALTERNATE OAUTH DOMAIN)) { +// return Result.ok(); + } else { + Result> cdr = q.credDAO.readID(trans, user); + if (cdr.notOKorIsEmpty()) { + return Result.err(Status.ERR_Security, + "%s is not a valid AAF Credential", user); + } + + for (CredDAO.Data cd : cdr.value) { + if (cd.expires.after(now)) { + return Result.ok(); + } + } + } + return Result.err(Result.ERR_Security, "%s has expired", user); + } + + public Result delOwner(AuthzTrans trans, String ns, String id) { + Result rq = q.deriveNs(trans, ns); + if (rq.notOK()) { + return Result.err(rq); + } + + rq = q.mayUser(trans, trans.user(), rq.value, Access.write); + if (rq.notOK()) { + return Result.err(rq); + } + + return delUserRole(trans, id, ns,Question.OWNER); + } + + public Result> getAdmins(AuthzTrans trans, String ns, boolean includeExpired) { + return getUsersByRole(trans, ns + Question.DOT_ADMIN, includeExpired); + } + + public Result delAdmin(AuthzTrans trans, String ns, String id) { + Result rq = q.deriveNs(trans, ns); + if (rq.notOK()) { + return Result.err(rq); + } + + rq = q.mayUser(trans, trans.user(), rq.value, Access.write); + if (rq.notOK()) { + // Even though not a "writer", Owners still determine who gets to be an Admin + Result> ruinr = q.userRoleDAO.readUserInRole(trans, trans.user(),ns+".owner"); + if(!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { + return Result.err(rq); + } + } + + return delUserRole(trans, id, ns, Question.ADMIN); + } + + /** + * Helper function that moves permissions from a namespace being deleted to + * its parent namespace + * + * @param trans + * @param parent + * @param sb + * @param rpdc + * - list of permissions in namespace being deleted + */ + private void movePerms(AuthzTrans trans, NsDAO.Data parent, + StringBuilder sb, Result> rpdc) { + + Result rv; + Result pd; + + if (rpdc.isOKhasData()) { + for (PermDAO.Data pdd : rpdc.value) { + String delP2 = pdd.type; + if ("access".equals(delP2)) { + continue; + } + // Remove old Perm from Roles, save them off + List lrdd = new ArrayList<>(); + + for(String rl : pdd.roles(false)) { + Result rrdd = RoleDAO.Data.decode(trans,q,rl); + if(rrdd.isOKhasData()) { + RoleDAO.Data rdd = rrdd.value; + lrdd.add(rdd); + q.roleDAO.delPerm(trans, rdd, pdd); + } else{ + trans.error().log(rrdd.errorString()); + } + } + + // Save off Old keys + String delP1 = pdd.ns; + NsSplit nss = new NsSplit(parent, pdd.fullType()); + pdd.ns = nss.ns; + pdd.type = nss.name; + // Use direct Create/Delete, because switching namespaces + if ((pd = q.permDAO.create(trans, pdd)).isOK()) { + // Put Role back into Perm, with correct info + for(RoleDAO.Data rdd : lrdd) { + q.roleDAO.addPerm(trans, rdd, pdd); + } + + pdd.ns = delP1; + pdd.type = delP2; + if ((rv = q.permDAO.delete(trans, pdd, false)).notOK()) { + sb.append(rv.details); + sb.append('\n'); + // } else { + // Need to invalidate directly, because we're switching + // places in NS, not normal cache behavior + // q.permDAO.invalidate(trans,pdd); + } + } else { + sb.append(pd.details); + sb.append('\n'); + } + } + } + } + + /** + * Helper function that moves roles from a namespace being deleted to its + * parent namespace + * + * @param trans + * @param parent + * @param sb + * @param rrdc + * - list of roles in namespace being deleted + */ + private void moveRoles(AuthzTrans trans, NsDAO.Data parent, + StringBuilder sb, Result> rrdc) { + + Result rv; + Result rd; + + if (rrdc.isOKhasData()) { + for (RoleDAO.Data rdd : rrdc.value) { + String delP2 = rdd.name; + if ("admin".equals(delP2) || "owner".equals(delP2)) { + continue; + } + // Remove old Role from Perms, save them off + List lpdd = new ArrayList<>(); + for(String p : rdd.perms(false)) { + Result rpdd = PermDAO.Data.decode(trans,q,p); + if(rpdd.isOKhasData()) { + PermDAO.Data pdd = rpdd.value; + lpdd.add(pdd); + q.permDAO.delRole(trans, pdd, rdd); + } else{ + trans.error().log(rpdd.errorString()); + } + } + + // Save off Old keys + String delP1 = rdd.ns; + + NsSplit nss = new NsSplit(parent, rdd.fullName()); + rdd.ns = nss.ns; + rdd.name = nss.name; + // Use direct Create/Delete, because switching namespaces + if ((rd = q.roleDAO.create(trans, rdd)).isOK()) { + // Put Role back into Perm, with correct info + for(PermDAO.Data pdd : lpdd) { + q.permDAO.addRole(trans, pdd, rdd); + } + + rdd.ns = delP1; + rdd.name = delP2; + if ((rv = q.roleDAO.delete(trans, rdd, true)).notOK()) { + sb.append(rv.details); + sb.append('\n'); + // } else { + // Need to invalidate directly, because we're switching + // places in NS, not normal cache behavior + // q.roleDAO.invalidate(trans,rdd); + } + } else { + sb.append(rd.details); + sb.append('\n'); + } + } + } + } + + /** + * Create Permission (and any missing Permission between this and Parent) if + * we have permission + * + * Pass in the desired Management Permission for this Permission + * + * If Force is set, then Roles listed will be created, if allowed, + * pre-granted. + */ + public Result createPerm(AuthzTrans trans, PermDAO.Data perm, boolean fromApproval) { + String user = trans.user(); + // Next, see if User is allowed to Manage Parent Permission + + Result rnsd; + if (!fromApproval) { + rnsd = q.mayUser(trans, user, perm, Access.write); + if (rnsd.notOK()) { + return Result.err(rnsd); + } + } else { + rnsd = q.deriveNs(trans, perm.ns); + } + + // Does Child exist? + if (!trans.requested(REQD_TYPE.force)) { + if (q.permDAO.read(trans, perm).isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, + "Permission [%s.%s|%s|%s] already exists.", perm.ns, + perm.type, perm.instance, perm.action); + } + } + + // Attempt to add perms to roles, creating as possible + Set roles; + String pstring = perm.encode(); + + // For each Role + for (String role : roles = perm.roles(true)) { + Result rdd = RoleDAO.Data.decode(trans,q,role); + if(rdd.isOKhasData()) { + RoleDAO.Data rd = rdd.value; + if (!fromApproval) { + // May User write to the Role in question. + Result rns = q.mayUser(trans, user, rd, + Access.write); + if (rns.notOK()) { + // Remove the role from Add, because + roles.remove(role); // Don't allow adding + trans.warn() + .log("User [%s] does not have permission to relate Permissions to Role [%s]", + user, role); + } + } + + Result> rlrd; + if ((rlrd = q.roleDAO.read(trans, rd)).notOKorIsEmpty()) { + rd.perms(true).add(pstring); + if (q.roleDAO.create(trans, rd).notOK()) { + roles.remove(role); // Role doesn't exist, and can't be + // created + } + } else { + rd = rlrd.value.get(0); + if (!rd.perms.contains(pstring)) { + q.roleDAO.addPerm(trans, rd, perm); + } + } + } + } + + Result pdr = q.permDAO.create(trans, perm); + if (pdr.isOK()) { + return Result.ok(); + } else { + return Result.err(pdr); + } + } + + public Result deletePerm(final AuthzTrans trans, final PermDAO.Data perm, boolean force, boolean fromApproval) { + String user = trans.user(); + + // Next, see if User is allowed to Manage Permission + Result rnsd; + if (!fromApproval) { + rnsd = q.mayUser(trans, user, perm, Access.write); + if (rnsd.notOK()) { + return Result.err(rnsd); + } + } + // Does Perm exist? + Result> pdr = q.permDAO.read(trans, perm); + if (pdr.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist.", + perm.ns,perm.type, perm.instance, perm.action); + } + // Get perm, but with rest of data. + PermDAO.Data fullperm = pdr.value.get(0); + + // Attached to any Roles? + if (fullperm.roles != null) { + if (force) { + for (String role : fullperm.roles) { + Result rv = null; + Result rrdd = RoleDAO.Data.decode(trans, q, role); + if(rrdd.isOKhasData()) { + trans.debug().log("Removing", role, "from", fullperm, "on Perm Delete"); + if ((rv = q.roleDAO.delPerm(trans, rrdd.value, fullperm)).notOK()) { + if (rv.notOK()) { + trans.error().log("Error removing Role during delFromPermRole: ", + trans.getUserPrincipal(), + rv.errorString()); + } + } + } else { + return Result.err(rrdd); + } + } + } else if (!fullperm.roles.isEmpty()) { + return Result + .err(Status.ERR_DependencyExists, + "Permission [%s.%s|%s|%s] cannot be deleted as it is attached to 1 or more roles.", + fullperm.ns, fullperm.type, fullperm.instance, fullperm.action); + } + } + + return q.permDAO.delete(trans, fullperm, false); + } + + public Result deleteRole(final AuthzTrans trans, final RoleDAO.Data role, boolean force, boolean fromApproval) { + String user = trans.user(); + + // Next, see if User is allowed to Manage Role + Result rnsd; + if (!fromApproval) { + rnsd = q.mayUser(trans, user, role, Access.write); + if (rnsd.notOK()) { + return Result.err(rnsd); + } + } + + // Are there any Users Attached to Role? + Result> urdr = q.userRoleDAO.readByRole(trans,role.fullName()); + if (force) { + if (urdr.isOKhasData()) { + for (UserRoleDAO.Data urd : urdr.value) { + q.userRoleDAO.delete(trans, urd, false); + } + } + } else if (urdr.isOKhasData()) { + return Result.err(Status.ERR_DependencyExists, + "Role [%s.%s] cannot be deleted as it is used by 1 or more Users.", + role.ns, role.name); + } + + // Does Role exist? + Result> rdr = q.roleDAO.read(trans, role); + if (rdr.notOKorIsEmpty()) { + return Result.err(Status.ERR_RoleNotFound, + "Role [%s.%s] does not exist", role.ns, role.name); + } + RoleDAO.Data fullrole = rdr.value.get(0); // full key search + + // Remove Self from Permissions... always, force or not. Force only applies to Dependencies (Users) + if (fullrole.perms != null) { + for (String perm : fullrole.perms(false)) { + Result rpd = PermDAO.Data.decode(trans,q,perm); + if (rpd.isOK()) { + trans.debug().log("Removing", perm, "from", fullrole,"on Role Delete"); + + Result r = q.permDAO.delRole(trans, rpd.value, fullrole); + if (r.notOK()) { + trans.error().log("ERR_FDR1 unable to remove",fullrole,"from",perm,':',r.status,'-',r.details); + } + } else { + trans.error().log("ERR_FDR2 Could not remove",perm,"from",fullrole); + } + } + } + return q.roleDAO.delete(trans, fullrole, false); + } + + /** + * Only owner of Permission may add to Role + * + * If force set, however, Role will be created before Grant, if User is + * allowed to create. + * + * @param trans + * @param role + * @param pd + * @return + */ + public Result addPermToRole(AuthzTrans trans, RoleDAO.Data role,PermDAO.Data pd, boolean fromApproval) { + String user = trans.user(); + + if (!fromApproval) { + Result rRoleCo = q.deriveFirstNsForType(trans, role.ns, NsType.COMPANY); + if(rRoleCo.notOK()) { + return Result.err(rRoleCo); + } + Result rPermCo = q.deriveFirstNsForType(trans, pd.ns, NsType.COMPANY); + if(rPermCo.notOK()) { + return Result.err(rPermCo); + } + + // Not from same company + if(!rRoleCo.value.name.equals(rPermCo.value.name)) { + Result r; + // Only grant if User ALSO has Write ability in Other Company + if((r = q.mayUser(trans, user, role, Access.write)).notOK()) { + return Result.err(r); + } + } + + + // Must be Perm Admin, or Granted Special Permission + Result ucp = q.mayUser(trans, user, pd, Access.write); + if (ucp.notOK()) { + // Don't allow CLI potential Grantees to change their own AAF + // Perms, + if ((ROOT_NS.equals(pd.ns) && Question.NS.equals(pd.type)) + || !q.isGranted(trans, trans.user(),ROOT_NS,Question.PERM, rPermCo.value.name, "grant")) { + // Not otherwise granted + // TODO Needed? + return Result.err(ucp); + } + // Final Check... Don't allow Grantees to add to Roles they are + // part of + Result> rlurd = q.userRoleDAO + .readByUser(trans, trans.user()); + if (rlurd.isOK()) { + for (UserRoleDAO.Data ur : rlurd.value) { + if (role.ns.equals(ur.ns) && role.name.equals(ur.rname)) { + return Result.err(ucp); + } + } + } + } + } + + Result> rlpd = q.permDAO.read(trans, pd); + if (rlpd.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission must exist to add to Role"); + } + + Result> rlrd = q.roleDAO.read(trans, role); // Already + // Checked + // for + // can + // change + // Role + Result rv; + + if (rlrd.notOKorIsEmpty()) { + if (trans.requested(REQD_TYPE.force)) { + Result ucr = q.mayUser(trans, user, role, + Access.write); + if (ucr.notOK()) { + return Result + .err(Status.ERR_Denied, + "Role [%s.%s] does not exist. User [%s] cannot create.", + role.ns, role.name, user); + } + + role.perms(true).add(pd.encode()); + Result rdd = q.roleDAO.create(trans, role); + if (rdd.isOK()) { + rv = Result.ok(); + } else { + rv = Result.err(rdd); + } + } else { + return Result.err(Status.ERR_RoleNotFound, + "Role [%s.%s] does not exist.", role.ns, role.name); + } + } else { + role = rlrd.value.get(0); + if (role.perms(false).contains(pd.encode())) { + return Result.err(Status.ERR_ConflictAlreadyExists, + "Permission [%s.%s] is already a member of role [%s,%s]", + pd.ns, pd.type, role.ns, role.name); + } + role.perms(true).add(pd.encode()); // this is added for Caching + // access purposes... doesn't + // affect addPerm + rv = q.roleDAO.addPerm(trans, role, pd); + } + if (rv.status == Status.OK) { + return q.permDAO.addRole(trans, pd, role); + // exploring how to add information message to successful http + // request + } + return rv; + } + + /** + * Either Owner of Role or Permission may delete from Role + * + * @param trans + * @param role + * @param pd + * @return + */ + public Result delPermFromRole(AuthzTrans trans, RoleDAO.Data role,PermDAO.Data pd, boolean fromApproval) { + String user = trans.user(); + if (!fromApproval) { + Result ucr = q.mayUser(trans, user, role, Access.write); + Result ucp = q.mayUser(trans, user, pd, Access.write); + + // If Can't change either Role or Perm, then deny + if (ucr.notOK() && ucp.notOK()) { + return Result.err(Status.ERR_Denied, + "User [" + trans.user() + + "] does not have permission to delete [" + + pd.encode() + "] from Role [" + + role.fullName() + ']'); + } + } + + Result> rlr = q.roleDAO.read(trans, role); + if (rlr.notOKorIsEmpty()) { + // If Bad Data, clean out + Result> rlp = q.permDAO.read(trans, pd); + if (rlp.isOKhasData()) { + for (PermDAO.Data pv : rlp.value) { + q.permDAO.delRole(trans, pv, role); + } + } + return Result.err(rlr); + } + String perm1 = pd.encode(); + boolean notFound; + if (trans.requested(REQD_TYPE.force)) { + notFound = false; + } else { // only check if force not set. + notFound = true; + for (RoleDAO.Data r : rlr.value) { + if (r.perms != null) { + for (String perm : r.perms) { + if (perm1.equals(perm)) { + notFound = false; + break; + } + } + if(!notFound) { + break; + } + } + } + } + if (notFound) { // Need to check both, in case of corruption + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s.%s|%s|%s] not associated with any Role", + pd.ns,pd.type,pd.instance,pd.action); + } + + // Read Perm for full data + Result> rlp = q.permDAO.read(trans, pd); + Result rv = null; + if (rlp.isOKhasData()) { + for (PermDAO.Data pv : rlp.value) { + if ((rv = q.permDAO.delRole(trans, pv, role)).isOK()) { + if ((rv = q.roleDAO.delPerm(trans, role, pv)).notOK()) { + trans.error().log( + "Error removing Perm during delFromPermRole:", + trans.getUserPrincipal(), rv.errorString()); + } + } else { + trans.error().log( + "Error removing Role during delFromPermRole:", + trans.getUserPrincipal(), rv.errorString()); + } + } + } else { + rv = q.roleDAO.delPerm(trans, role, pd); + if (rv.notOK()) { + trans.error().log("Error removing Role during delFromPermRole", + rv.errorString()); + } + } + return rv == null ? Result.ok() : rv; + } + + public Result delPermFromRole(AuthzTrans trans, String role,PermDAO.Data pd) { + Result nss = q.deriveNsSplit(trans, role); + if (nss.notOK()) { + return Result.err(nss); + } + RoleDAO.Data rd = new RoleDAO.Data(); + rd.ns = nss.value.ns; + rd.name = nss.value.name; + return delPermFromRole(trans, rd, pd, false); + } + + /** + * Add a User to Role + * + * 1) Role must exist 2) User must be a known Credential (i.e. mechID ok if + * Credential) or known Organizational User + * + * @param trans + * @param org + * @param urData + * @return + * @throws DAOException + */ + public Result addUserRole(AuthzTrans trans,UserRoleDAO.Data urData) { + Result rv; + if(Question.ADMIN.equals(urData.rname)) { + rv = mayAddAdmin(trans, urData.ns, urData.user); + } else if(Question.OWNER.equals(urData.rname)) { + rv = mayAddOwner(trans, urData.ns, urData.user); + } else { + rv = checkValidID(trans, new Date(), urData.user); + } + if(rv.notOK()) { + return rv; + } + + // Check if record exists + if (q.userRoleDAO.read(trans, urData).isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, + "User Role exists"); + } + if (q.roleDAO.read(trans, urData.ns, urData.rname).notOKorIsEmpty()) { + return Result.err(Status.ERR_RoleNotFound, + "Role [%s.%s] does not exist", urData.ns, urData.rname); + } + + urData.expires = trans.org().expiration(null, Expiration.UserInRole, urData.user).getTime(); + + + Result udr = q.userRoleDAO.create(trans, urData); + switch (udr.status) { + case OK: + return Result.ok(); + default: + return Result.err(udr); + } + } + + public Result addUserRole(AuthzTrans trans, String user, String ns, String rname) { + try { + if(trans.org().getIdentity(trans, user)==null) { + return Result.err(Result.ERR_BadData,user+" is an Invalid Identity for " + trans.org().getName()); + } + } catch (OrganizationException e) { + return Result.err(e); + } + UserRoleDAO.Data urdd = new UserRoleDAO.Data(); + urdd.ns = ns; + urdd.role(ns, rname); + urdd.user = user; + return addUserRole(trans,urdd); + } + + /** + * Extend User Role. + * + * extend the Expiration data, according to Organization rules. + * + * @param trans + * @param org + * @param urData + * @return + */ + public Result extendUserRole(AuthzTrans trans, UserRoleDAO.Data urData, boolean checkForExist) { + // Check if record still exists + if (checkForExist && q.userRoleDAO.read(trans, urData).notOKorIsEmpty()) { + return Result.err(Status.ERR_UserRoleNotFound, + "User Role does not exist"); + } + + if (q.roleDAO.read(trans, urData.ns, urData.rname).notOKorIsEmpty()) { + return Result.err(Status.ERR_RoleNotFound, + "Role [%s.%s] does not exist", urData.ns,urData.rname); + } + // Special case for "Admin" roles. Issue brought forward with Prod + // problem 9/26 + Date now = new Date(); + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(now.after(urData.expires)?now:urData.expires); + urData.expires = trans.org().expiration(gc, Expiration.UserInRole).getTime(); // get + // Full + // time + // starting + // today + return q.userRoleDAO.update(trans, urData); + } + + // //////////////////////////////////////////////////// + // Special User Role Functions + // These exist, because User Roles have Expiration dates, which must be + // accounted for + // Also, as of July, 2015, Namespace Owners and Admins are now regular User + // Roles + // //////////////////////////////////////////////////// + public Result> getUsersByRole(AuthzTrans trans, String role, boolean includeExpired) { + Result> rurdd = q.userRoleDAO.readByRole(trans,role); + if (rurdd.notOK()) { + return Result.err(rurdd); + } + Date now = new Date(); + List list = rurdd.value; + List rv = new ArrayList<>(list.size()); // presize + for (UserRoleDAO.Data urdd : rurdd.value) { + if (includeExpired || urdd.expires.after(now)) { + rv.add(urdd.user); + } + } + return Result.ok(rv); + } + + public Result delUserRole(AuthzTrans trans, String user, String ns, String rname) { + UserRoleDAO.Data urdd = new UserRoleDAO.Data(); + urdd.user = user; + urdd.role(ns,rname); + Result> r = q.userRoleDAO.read(trans, urdd); + if (r.status == 404 || r.isEmpty()) { + return Result.err(Status.ERR_UserRoleNotFound, + "UserRole [%s] [%s.%s]", user, ns, rname); + } + if (r.notOK()) { + return Result.err(r); + } + + return q.userRoleDAO.delete(trans, urdd, false); + } + + public Result createFuture(AuthzTrans trans, FutureDAO.Data data, String id, String user, + NsDAO.Data nsd, FUTURE_OP op) { + StringBuilder sb = new StringBuilder(); + try { + Organization org = trans.org(); + // For Reapproval, only check Owners.. Do Supervisors, etc, separately + List approvers = op.equals(FUTURE_OP.A)?NO_ADDL_APPROVE:org.getApprovers(trans, user); + List owners = new ArrayList<>(); + if (nsd != null) { + Result> rrbr = q.userRoleDAO + .readByRole(trans, nsd.name + Question.DOT_OWNER); + if (rrbr.isOKhasData()) { + for(UserRoleDAO.Data urd : rrbr.value) { + Identity owner = org.getIdentity(trans, urd.user); + if(owner==null) { + return Result.err(Result.ERR_NotFound,urd.user + " is not a Valid Owner of " + nsd.name); + } else { + owners.add(owner); + } + } + } + } + + if(owners.isEmpty()) { + return Result.err(Result.ERR_NotFound,"No Owners found for " + nsd.name); + } + + // Create Future Object + + Result fr = q.futureDAO.create(trans, data, id); + if (fr.isOK()) { + sb.append("Created Future: "); + sb.append(data.id); + // User Future ID as ticket for Approvals + final UUID ticket = fr.value.id; + sb.append(", Approvals: "); + Boolean first[] = new Boolean[]{true}; + if(op!=FUTURE_OP.A) { + for (Identity u : approvers) { + Result r = addIdentity(trans,sb,first,user,data.memo,op,u,ticket,org.getApproverType()); + if(r.notOK()) { + return Result.err(r); + } + } + } + for (Identity u : owners) { + Result r = addIdentity(trans,sb,first,user,data.memo,op,u,ticket,"owner"); + if(r.notOK()) { + return Result.err(r); + } + } + } + } catch (Exception e) { + return Result.err(e); + } + + return Result.ok(sb.toString()); + } + + /* + * This interface is to allow performFutureOps with either Realtime Data, or Batched lookups (See Expiring) + */ + public interface Lookup { + T get(AuthzTrans trans, Object ... keys); + } + + public Lookup urDBLookup = new Lookup() { + @Override + public UserRoleDAO.Data get(AuthzTrans trans, Object ... keys) { + Result> r = q.userRoleDAO.read(trans, keys); + if(r.isOKhasData()) { + return r.value.get(0); + } else { + return null; + } + } + }; + + /** + * Note: if "allApprovals for Ticket is null, it will be looked up. + * if "fdd" is null, it will be looked up, but + * + * They can be passed for performance reasons. + * + * @param trans + * @param cd + * @param allApprovalsForTicket + * @return + */ + public Result performFutureOp(final AuthzTrans trans, FUTURE_OP fop, FutureDAO.Data curr, Lookup> la, Lookup lur) { + // Pre-Evaluate if ReApproval is already done. + UserRoleDAO.Data urdd = null; + if(fop.equals(FUTURE_OP.A) && curr.target.equals(FOP_USER_ROLE) && curr.construct!=null) { + try { + // Get Expected UserRole from Future + urdd = new UserRoleDAO.Data(); + urdd.reconstitute(curr.construct); + // Get Current UserRole from lookup + UserRoleDAO.Data lurdd = lur.get(trans, urdd.user,urdd.role); + if(lurdd==null) { + q.futureDAO.delete(trans, curr, false); + return OP_STATUS.RL; + } else { + if(curr.expires.compareTo(lurdd.expires)<0) { + q.futureDAO.delete(trans, curr, false); + return OP_STATUS.RL; + } + } + } catch (IOException e) { + return Result.err(Result.ERR_BadData,"Cannot reconstitute %1",curr.memo); + } + } + + boolean aDenial = false; + int cntSuper=0, appSuper=0,cntOwner=0, appOwner=0; + for(ApprovalDAO.Data add : la.get(trans)) { + switch(add.status) { + case "approved": + if("owner".equals(add.type)) { + ++cntOwner; + ++appOwner; + } else if("supervisor".equals(add.type)) { + ++cntSuper; + ++appSuper; + } + break; + case "pending": + if("owner".equals(add.type)) { + ++cntOwner; + } else if("supervisor".equals(add.type)) { + ++cntSuper; + } + break; + case "denied": + aDenial=true; + break; + } + } + + Result ros=null; + if(aDenial) { + // Note: Denial will be Audit-logged. +// for (ApprovalDAO.Data ad : allApprovalsForTicket.value) { +// q.approvalDAO.delete(trans, ad, false); +// } + ros = OP_STATUS.RD; + if(q.futureDAO.delete(trans, curr, false).notOK()) { + trans.info().printf("Future %s could not be deleted", curr.id.toString()); + } else { + if (FOP_USER_ROLE.equalsIgnoreCase(curr.target)) { + // A Denial means we must remove UserRole + if(fop.equals(FUTURE_OP.U) || fop.equals(FUTURE_OP.A)) { + UserRoleDAO.Data data = new UserRoleDAO.Data(); + try { + data.reconstitute(curr.construct); + } catch (IOException e) { + trans.error().log("Cannot reconstitue",curr.memo); + } + ros = set(OP_STATUS.RD,delUserRole(trans, data.user, data.ns, data.rname)); + } + } + } + } + + // Decision: If not Denied, and at least owner, if exists, and at least one Super, if exists + boolean goDecision = (cntOwner>0?appOwner>0:true) && (cntSuper>0?appSuper>0:true); + + if(goDecision) { + // should check if any other pendings before performing + // actions + try { + if (FOP_ROLE.equalsIgnoreCase(curr.target)) { + RoleDAO.Data data = new RoleDAO.Data(); + data.reconstitute(curr.construct); + switch(fop) { + case C: + ros = set(OP_STATUS.RE,q.roleDAO.dao().create(trans, data)); + break; + case D: + ros = set(OP_STATUS.RE,deleteRole(trans, data, true, true)); + break; + default: + } + } else if (FOP_PERM.equalsIgnoreCase(curr.target)) { + PermDAO.Data pdd = new PermDAO.Data(); + pdd.reconstitute(curr.construct); + Set roles; + Result rrdd; + switch(fop) { + case C: + ros = set(OP_STATUS.RE,createPerm(trans, pdd, true)); + break; + case D: + ros = set(OP_STATUS.RE,deletePerm(trans, pdd, true, true)); + break; + case G: + roles = pdd.roles(true); + for (String roleStr : roles) { + rrdd = RoleDAO.Data.decode(trans, q, roleStr); + if (rrdd.isOKhasData()) { + ros = set(OP_STATUS.RE,addPermToRole(trans, rrdd.value, pdd, true)); + } else { + trans.error().log(rrdd.errorString()); + } + } + break; + case UG: + roles = pdd.roles(true); + for (String roleStr : roles) { + rrdd = RoleDAO.Data.decode(trans, q, roleStr); + if (rrdd.isOKhasData()) { + ros = set(OP_STATUS.RE,delPermFromRole(trans, rrdd.value, pdd, true)); + } else { + trans.error().log(rrdd.errorString()); + } + } + break; + default: + } + } else if (FOP_USER_ROLE.equalsIgnoreCase(curr.target)) { + if(urdd==null) { + urdd = new UserRoleDAO.Data(); + urdd.reconstitute(curr.construct); + } + // if I am the last to approve, create user role + switch(fop) { + case C: + ros = set(OP_STATUS.RE,addUserRole(trans, urdd)); + break; + case U: + case A: + ros = set(OP_STATUS.RE,extendUserRole(trans,urdd,true)); + break; + default: + } + } else if (FOP_NS.equalsIgnoreCase(curr.target)) { + Namespace namespace = new Namespace(); + namespace.reconstitute(curr.construct); + switch(fop) { + case C: + ros = set(OP_STATUS.RE,createNS(trans, namespace, true)); + break; + default: + } + } else if (FOP_DELEGATE.equalsIgnoreCase(curr.target)) { + DelegateDAO.Data data = new DelegateDAO.Data(); + data.reconstitute(curr.construct); + switch(fop) { + case C: + ros = set(OP_STATUS.RE,q.delegateDAO.create(trans, data)); + break; + case U: + ros = set(OP_STATUS.RE,q.delegateDAO.update(trans, data)); + break; + default: + } + } else if (FOP_CRED.equalsIgnoreCase(curr.target)) { + CredDAO.Data data = new CredDAO.Data(); + data.reconstitute(curr.construct); + switch(fop) { + case C: + ros = set(OP_STATUS.RE,q.credDAO.dao().create(trans, data)); + break; + default: + } + } + } catch (Exception e) { + trans.error().log("Exception: ", e.getMessage(), + " \n occurred while performing", curr.memo, + " from Ticket ", curr.id.toString()); + } + q.futureDAO.delete(trans, curr, false); + } // end for goDecision + if(ros==null) { + //return Result.err(Status.ACC_Future, "Full Approvals not obtained: No action taken"); + ros = OP_STATUS.RP; + } + + return ros; + } + + // Convenience method for setting OPSTatus Results + private Result set(Result rs, Result orig) { + if(orig.isOK()) { + return rs; + } else { + return Result.err(orig); + } + } + + private Result addIdentity(AuthzTrans trans, StringBuilder sb, + Boolean[] first, String user, String memo, FUTURE_OP op, Identity u, UUID ticket, String type) throws OrganizationException { + ApprovalDAO.Data ad = new ApprovalDAO.Data(); + // Note ad.id is set by ApprovalDAO Create + ad.ticket = ticket; + ad.user = user; + ad.approver = u.fullID(); + ad.status = ApprovalDAO.PENDING; + ad.memo = memo; + ad.type = type; + ad.operation = op.name(); + // Note ad.updated is created in System + Result r = q.approvalDAO.create(trans,ad); + if(r.isOK()) { + if(first[0]) { + first[0] = false; + } else { + sb.append(", "); + } + sb.append(r.value.user); + sb.append(':'); + sb.append(r.value.ticket); + return r; + } else { + return Result.err(Status.ERR_ActionNotCompleted, + "Approval for %s, %s could not be created: %s", + ad.user, ad.approver, + r.details, sb.toString()); + } + } + + public Executor newExecutor(AuthzTrans trans) { + return new CassExecutor(trans, this); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java index 1544aab8..6bb440ad 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java @@ -45,141 +45,141 @@ import org.onap.aaf.auth.layer.Result; */ // Package on purpose class PermLookup { - private AuthzTrans trans; - private String user; - private Question q; - private Result> userRoles = null; - private Result> roles = null; - private Result> permNames = null; - private Result> perms = null; - - private PermLookup() {} - - static PermLookup get(AuthzTrans trans, Question q, String user) { - PermLookup lp=null; - Map permMap = trans.get(Question.PERMS, null); - if (permMap == null) { - trans.put(Question.PERMS, permMap = new HashMap<>()); - } else { - lp = permMap.get(user); - } + private AuthzTrans trans; + private String user; + private Question q; + private Result> userRoles = null; + private Result> roles = null; + private Result> permNames = null; + private Result> perms = null; + + private PermLookup() {} + + static PermLookup get(AuthzTrans trans, Question q, String user) { + PermLookup lp=null; + Map permMap = trans.get(Question.PERMS, null); + if (permMap == null) { + trans.put(Question.PERMS, permMap = new HashMap<>()); + } else { + lp = permMap.get(user); + } - if (lp == null) { - lp = new PermLookup(); - lp.trans = trans; - lp.user = user; - lp.q = q; - permMap.put(user, lp); - } - return lp; - } - - public Result> getUserRoles() { - if(userRoles==null) { - userRoles = q.userRoleDAO.readByUser(trans,user); - if(userRoles.isOKhasData()) { - List lurdd = new ArrayList<>(); - Date now = new Date(); - for(UserRoleDAO.Data urdd : userRoles.value) { - if(urdd.expires.after(now)) { // Remove Expired - lurdd.add(urdd); - } - } - if(lurdd.size()==0) { - return userRoles = Result.err(Status.ERR_UserNotFound, - "%s not found or not associated with any Roles: ", - user); - } else { - return userRoles = Result.ok(lurdd); - } - } else { - return userRoles; - } - } else { - return userRoles; - } - } + if (lp == null) { + lp = new PermLookup(); + lp.trans = trans; + lp.user = user; + lp.q = q; + permMap.put(user, lp); + } + return lp; + } + + public Result> getUserRoles() { + if(userRoles==null) { + userRoles = q.userRoleDAO.readByUser(trans,user); + if(userRoles.isOKhasData()) { + List lurdd = new ArrayList<>(); + Date now = new Date(); + for(UserRoleDAO.Data urdd : userRoles.value) { + if(urdd.expires.after(now)) { // Remove Expired + lurdd.add(urdd); + } + } + if(lurdd.size()==0) { + return userRoles = Result.err(Status.ERR_UserNotFound, + "%s not found or not associated with any Roles: ", + user); + } else { + return userRoles = Result.ok(lurdd); + } + } else { + return userRoles; + } + } else { + return userRoles; + } + } - public Result> getRoles() { - if(roles==null) { - Result> rur = getUserRoles(); - if(rur.isOK()) { - List lrdd = new ArrayList<>(); - for (UserRoleDAO.Data urdata : rur.value) { - // Gather all permissions from all Roles - if(urdata.ns==null || urdata.rname==null) { - return Result.err(Status.ERR_BadData,"DB Content Error: nulls in User Role %s %s", urdata.user,urdata.role); - } else { - Result> rlrd = q.roleDAO.read( - trans, urdata.ns, urdata.rname); - if(rlrd.isOK()) { - lrdd.addAll(rlrd.value); - } - } - } - return roles = Result.ok(lrdd); - } else { - return roles = Result.err(rur); - } - } else { - return roles; - } - } + public Result> getRoles() { + if(roles==null) { + Result> rur = getUserRoles(); + if(rur.isOK()) { + List lrdd = new ArrayList<>(); + for (UserRoleDAO.Data urdata : rur.value) { + // Gather all permissions from all Roles + if(urdata.ns==null || urdata.rname==null) { + return Result.err(Status.ERR_BadData,"DB Content Error: nulls in User Role %s %s", urdata.user,urdata.role); + } else { + Result> rlrd = q.roleDAO.read( + trans, urdata.ns, urdata.rname); + if(rlrd.isOK()) { + lrdd.addAll(rlrd.value); + } + } + } + return roles = Result.ok(lrdd); + } else { + return roles = Result.err(rur); + } + } else { + return roles; + } + } - public Result> getPermNames() { - if(permNames==null) { - Result> rlrd = getRoles(); - if (rlrd.isOK()) { - Set pns = new TreeSet<>(); - for (RoleDAO.Data rdata : rlrd.value) { - pns.addAll(rdata.perms(false)); - } - return permNames = Result.ok(pns); - } else { - return permNames = Result.err(rlrd); - } - } else { - return permNames; - } - } - - public Result> getPerms(boolean lookup) { - if(perms==null) { - // Note: It should be ok for a Valid user to have no permissions - - // Jonathan 8/12/2013 - Result> rss = getPermNames(); - if(rss.isOK()) { - List lpdd = new ArrayList<>(); - for (String perm : rss.value) { - if(lookup) { - Result ap = PermDAO.Data.decodeToArray(trans, q, perm); - if(ap.isOK()) { - - Result> rlpd = q.permDAO.read(perm,trans,ap.value); - if (rlpd.isOKhasData()) { - for (PermDAO.Data pData : rlpd.value) { - lpdd.add(pData); - } - } - } else { - trans.error().log("In getPermsByUser, for", user, perm); - } - } else { - Result pr = PermDAO.Data.decode(trans, q, perm); - if (pr.notOK()) { - trans.error().log("In getPermsByUser, for", user, pr.errorString()); - } else { - lpdd.add(pr.value); - } - } + public Result> getPermNames() { + if(permNames==null) { + Result> rlrd = getRoles(); + if (rlrd.isOK()) { + Set pns = new TreeSet<>(); + for (RoleDAO.Data rdata : rlrd.value) { + pns.addAll(rdata.perms(false)); + } + return permNames = Result.ok(pns); + } else { + return permNames = Result.err(rlrd); + } + } else { + return permNames; + } + } + + public Result> getPerms(boolean lookup) { + if(perms==null) { + // Note: It should be ok for a Valid user to have no permissions - + // Jonathan 8/12/2013 + Result> rss = getPermNames(); + if(rss.isOK()) { + List lpdd = new ArrayList<>(); + for (String perm : rss.value) { + if(lookup) { + Result ap = PermDAO.Data.decodeToArray(trans, q, perm); + if(ap.isOK()) { + + Result> rlpd = q.permDAO.read(perm,trans,ap.value); + if (rlpd.isOKhasData()) { + for (PermDAO.Data pData : rlpd.value) { + lpdd.add(pData); + } + } + } else { + trans.error().log("In getPermsByUser, for", user, perm); + } + } else { + Result pr = PermDAO.Data.decode(trans, q, perm); + if (pr.notOK()) { + trans.error().log("In getPermsByUser, for", user, pr.errorString()); + } else { + lpdd.add(pr.value); + } + } - } - return perms = Result.ok(lpdd); - } else { - return perms = Result.err(rss); - } - } else { - return perms; - } - } + } + return perms = Result.ok(lpdd); + } else { + return perms = Result.err(rss); + } + } else { + return perms; + } + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java index 8d148ec1..152412a2 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java @@ -88,1065 +88,1065 @@ import com.datastax.driver.core.Cluster; */ public class Question { - // DON'T CHANGE FROM lower Case!!! - public static enum Type { - ns, role, perm, cred - }; - - public static final String OWNER="owner"; - public static final String ADMIN="admin"; - public static final String DOT_OWNER=".owner"; - public static final String DOT_ADMIN=".admin"; - public static final String ACCESS = "access"; - - static final String ASTERIX = "*"; - - public static enum Access { - read, write, create - }; - - public static final String READ = Access.read.name(); - public static final String WRITE = Access.write.name(); - public static final String CREATE = Access.create.name(); - - public static final String ROLE = Type.role.name(); - public static final String PERM = Type.perm.name(); - public static final String NS = Type.ns.name(); - public static final String CRED = Type.cred.name(); - private static final String DELG = "delg"; - public static final String ROOT_NS = Define.isInitialized() ? Define.ROOT_NS() : "undefined"; - public static final String ATTRIB = "attrib"; - - - public static final int MAX_SCOPE = 10; - public static final int APP_SCOPE = 3; - public static final int COMPANY_SCOPE = 2; - static Slot PERMS; - - private static Set specialLog = null; - public static final Random random = new SecureRandom(); - private static long traceID = random.nextLong(); - private static Slot specialLogSlot = null; - private static Slot transIDSlot = null; - - - public final HistoryDAO historyDAO; - public final CachedNSDAO nsDAO; - public final CachedRoleDAO roleDAO; - public final CachedPermDAO permDAO; - public final CachedUserRoleDAO userRoleDAO; - public final CachedCredDAO credDAO; - public final CachedCertDAO certDAO; - public final DelegateDAO delegateDAO; - public final FutureDAO futureDAO; - public final ApprovalDAO approvalDAO; - private final CacheInfoDAO cacheInfoDAO; - public final LocateDAO locateDAO; - - public Question(AuthzTrans trans, Cluster cluster, String keyspace, boolean startClean) throws APIException, IOException { - PERMS = trans.slot("USER_PERMS"); - trans.init().log("Instantiating DAOs"); - long expiresIn = Long.parseLong(trans.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF)); - historyDAO = new HistoryDAO(trans, cluster, keyspace); - - // Deal with Cached Entries - cacheInfoDAO = new CacheInfoDAO(trans, historyDAO); - - nsDAO = new CachedNSDAO(new NsDAO(trans, historyDAO, cacheInfoDAO),cacheInfoDAO, expiresIn); - permDAO = new CachedPermDAO(new PermDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); - roleDAO = new CachedRoleDAO(new RoleDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); - userRoleDAO = new CachedUserRoleDAO(new UserRoleDAO(trans, historyDAO,cacheInfoDAO), cacheInfoDAO, expiresIn); - credDAO = new CachedCredDAO(new CredDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); - certDAO = new CachedCertDAO(new CertDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); - - locateDAO = new LocateDAO(trans,historyDAO); - futureDAO = new FutureDAO(trans, historyDAO); - delegateDAO = new DelegateDAO(trans, historyDAO); - approvalDAO = new ApprovalDAO(trans, historyDAO); - - // Only want to aggressively cleanse User related Caches... The others, - // just normal refresh - if(startClean) { - CachedDAO.startCleansing(trans.env(), credDAO, userRoleDAO); - CachedDAO.startRefresh(trans.env(), cacheInfoDAO); - } - // Set a Timer to Check Caches to send messages for Caching changes - - if(specialLogSlot==null) { - specialLogSlot = trans.slot(AuthzTransFilter.SPECIAL_LOG_SLOT); - } - - if(transIDSlot==null) { - transIDSlot = trans.slot(AuthzTransFilter.TRANS_ID_SLOT); - } - - AbsCassDAO.primePSIs(trans); - } - - - public void close(AuthzTrans trans) { - historyDAO.close(trans); - cacheInfoDAO.close(trans); - nsDAO.close(trans); - permDAO.close(trans); - roleDAO.close(trans); - userRoleDAO.close(trans); - credDAO.close(trans); - certDAO.close(trans); - delegateDAO.close(trans); - futureDAO.close(trans); - approvalDAO.close(trans); - } - - public Result permFrom(AuthzTrans trans, String type, - String instance, String action) { - Result rnd = deriveNs(trans, type); - if (rnd.isOK()) { - return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type), - instance, action)); - } else { - return Result.err(rnd); - } - } - - /** - * getPermsByUser - * - * Because this call is frequently called internally, AND because we already - * look for it in the initial Call, we cache within the Transaction - * - * @param trans - * @param user - * @return - */ - public Result> getPermsByUser(AuthzTrans trans, String user, boolean lookup) { - return PermLookup.get(trans, this, user).getPerms(lookup); - } - - public Result> getPermsByUserFromRolesFilter(AuthzTrans trans, String user, String forUser) { - PermLookup plUser = PermLookup.get(trans, this, user); - Result> plPermNames = plUser.getPermNames(); - if(plPermNames.notOK()) { - return Result.err(plPermNames); - } - - Set nss; - if(forUser.equals(user)) { - nss = null; - } else { - // Setup a TreeSet to check on Namespaces to - nss = new TreeSet<>(); - PermLookup fUser = PermLookup.get(trans, this, forUser); - Result> forUpn = fUser.getPermNames(); - if(forUpn.notOK()) { - return Result.err(forUpn); - } - - for(String pn : forUpn.value) { - Result decoded = PermDAO.Data.decodeToArray(trans, this, pn); - if(decoded.isOKhasData()) { - nss.add(decoded.value[0]); - } else { - trans.error().log(pn,", derived from a Role, is invalid:",decoded.errorString()); - } - } - } - - List rlpUser = new ArrayList<>(); - Result rpdd; - PermDAO.Data pdd; - for(String pn : plPermNames.value) { - rpdd = PermDAO.Data.decode(trans, this, pn); - if(rpdd.isOKhasData()) { - pdd=rpdd.value; - if(nss==null || nss.contains(pdd.ns)) { - rlpUser.add(pdd); - } - } else { - trans.error().log(pn,", derived from a Role, is invalid. Run Data Cleanup:",rpdd.errorString()); - } - } - return Result.ok(rlpUser); - } - - public Result> getPermsByType(AuthzTrans trans, String perm) { - Result nss = deriveNsSplit(trans, perm); - if (nss.notOK()) { - return Result.err(nss); - } - return permDAO.readByType(trans, nss.value.ns, nss.value.name); - } - - public Result> getPermsByName(AuthzTrans trans, - String type, String instance, String action) { - Result nss = deriveNsSplit(trans, type); - if (nss.notOK()) { - return Result.err(nss); - } - return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action); - } - - public Result> getPermsByRole(AuthzTrans trans, String role, boolean lookup) { - Result nss = deriveNsSplit(trans, role); - if (nss.notOK()) { - return Result.err(nss); - } - - Result> rlrd = roleDAO.read(trans, nss.value.ns, - nss.value.name); - if (rlrd.notOKorIsEmpty()) { - return Result.err(rlrd); - } - // Using Set to avoid duplicates - Set permNames = new HashSet<>(); - if (rlrd.isOKhasData()) { - for (RoleDAO.Data drr : rlrd.value) { - permNames.addAll(drr.perms(false)); - } - } - - // Note: It should be ok for a Valid user to have no permissions - - // Jonathan 8/12/2013 - List perms = new ArrayList<>(); - for (String perm : permNames) { - Result pr = PermDAO.Data.decode(trans, this, perm); - if (pr.notOK()) { - return Result.err(pr); - } - - if(lookup) { - Result> rlpd = permDAO.read(trans, pr.value); - if (rlpd.isOKhasData()) { - for (PermDAO.Data pData : rlpd.value) { - perms.add(pData); - } - } - } else { - perms.add(pr.value); - } - } - - return Result.ok(perms); - } - - public Result> getRolesByName(AuthzTrans trans, - String role) { - Result nss = deriveNsSplit(trans, role); - if (nss.notOK()) { - return Result.err(nss); - } - String r = nss.value.name; - if (r.endsWith(".*")) { // do children Search - return roleDAO.readChildren(trans, nss.value.ns, - r.substring(0, r.length() - 2)); - } else if (ASTERIX.equals(r)) { - return roleDAO.readChildren(trans, nss.value.ns, ASTERIX); - } else { - return roleDAO.read(trans, nss.value.ns, r); - } - } - - /** - * Derive NS - * - * Given a Child Namespace, figure out what the best Namespace parent is. - * - * For instance, if in the NS table, the parent "org.osaaf" exists, but not - * "org.osaaf.child" or "org.osaaf.a.b.c", then passing in either - * "org.osaaf.child" or "org.osaaf.a.b.c" will return "org.osaaf" - * - * Uses recursive search on Cached DAO data - * - * @param trans - * @param child - * @return - */ - public Result deriveNs(AuthzTrans trans, String child) { - Result> r = nsDAO.read(trans, child); - - if (r.isOKhasData()) { - return Result.ok(r.value.get(0)); - } else { - int dot; - if(child==null) { - return Result.err(Status.ERR_NsNotFound, "No Namespace"); - } else { - dot = child.lastIndexOf('.'); - } - if (dot < 0) { - return Result.err(Status.ERR_NsNotFound, "No Namespace for [%s]", child); - } else { - return deriveNs(trans, child.substring(0, dot)); - } - } - } - - public Result deriveFirstNsForType(AuthzTrans trans, String str, NsType type) { - NsDAO.Data nsd; - - for(String lookup = str;!".".equals(lookup) && lookup!=null;) { - Result> rld = nsDAO.read(trans, lookup); - if(rld.isOKhasData()) { - nsd=rld.value.get(0); - lookup = nsd.parent; - if(type.type == nsd.type) { - return Result.ok(nsd); - } - } else { - return Result.err(Status.ERR_NsNotFound,"There is no valid Company Namespace for %s",str); - } - } - return Result.err(Status.ERR_NotFound, str + " does not contain type " + type.name()); - } - - public Result deriveNsSplit(AuthzTrans trans, String child) { - Result ndd = deriveNs(trans, child); - if (ndd.isOK()) { - NsSplit nss = new NsSplit(ndd.value, child); - if (nss.isOK()) { - return Result.ok(nss); - } else { - return Result.err(Status.ERR_NsNotFound, - "Cannot split [%s] into valid namespace elements", - child); - } - } - return Result.err(ndd); - } - - /** - * Translate an ID into it's domain - * - * i.e. myid1234@aaf.att.com results in domain of com.att.aaf - * - * @param id - * @return - */ - public static String domain2ns(String id) { - int at = id.indexOf('@'); - if (at >= 0) { - String[] domain = id.substring(at + 1).split("\\."); - StringBuilder ns = new StringBuilder(id.length()); - boolean first = true; - for (int i = domain.length - 1; i >= 0; --i) { - if (first) { - first = false; - } else { - ns.append('.'); - } - ns.append(domain[i]); - } - return ns.toString(); - } else { - return ""; - } - - } - - /** - * Validate Namespace of ID@Domain - * - * Namespace is reverse order of Domain. - * - * @param trans - * @param id - * @return - */ - public Result validNSOfDomain(AuthzTrans trans, String id) { - // Take domain, reverse order, and check on NS - String ns; - if(id.indexOf('@')<0) { // it's already an ns, not an ID - ns = id; - } else { - ns = domain2ns(id); - } - if (ns.length() > 0) { - if(!trans.org().getDomain().equals(ns)) { - Result> rlnsd = nsDAO.read(trans, ns); - if (rlnsd.isOKhasData()) { - return Result.ok(rlnsd.value.get(0)); - } - } - } - return Result.err(Status.ERR_NsNotFound, - "A Namespace is not available for %s", id); - } - - public Result mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, Access access) { - // .access|:role:| - String ns = ndd.name; - int last; - do { - if (isGranted(trans, user, ns, ACCESS, ":ns", access.name())) { - return Result.ok(ndd); - } - if ((last = ns.lastIndexOf('.')) >= 0) { - ns = ns.substring(0, last); - } - } while (last >= 0); - // com.att.aaf.ns|::ns| - // AAF-724 - Make consistent response for May User", and not take the - // last check... too confusing. - Result rv = mayUserVirtueOfNS(trans, user, ndd, ":" + ndd.name + ":ns", access.name()); - if (rv.isOK()) { - return rv; - } else if(rv.status==Result.ERR_Backend) { - return Result.err(rv); - } else { - return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]", - user, access.name(), ndd.name); - } - } - - public Result mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) { - Result rnsd = deriveNs(trans, rdd.ns); - if (rnsd.isOK()) { - return mayUser(trans, user, rnsd.value, rdd, access); - } - return rnsd; - } - - public Result mayUser(AuthzTrans trans, String user, NsDAO.Data ndd, RoleDAO.Data rdd, Access access) { - // 1) Is User in the Role? - Result> rurd = userRoleDAO.readUserInRole(trans, user, rdd.fullName()); - if (rurd.isOKhasData()) { - return Result.ok(ndd); - } - - String roleInst = ":role:" + rdd.name; - // .access|:role:| - String ns = rdd.ns; - int last; - do { - if (isGranted(trans, user, ns,ACCESS, roleInst, access.name())) { - return Result.ok(ndd); - } - if ((last = ns.lastIndexOf('.')) >= 0) { - ns = ns.substring(0, last); - } - } while (last >= 0); - - // Check if Access by Global Role perm - // com.att.aaf.ns|::role:name| - Result rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" - + rdd.ns + roleInst, access.name()); - if (rnsd.isOK()) { - return rnsd; - } else if(rnsd.status==Result.ERR_Backend) { - return Result.err(rnsd); - } - - // Check if Access to Whole NS - // AAF-724 - Make consistent response for May User", and not take the - // last check... too confusing. - Result rv = mayUserVirtueOfNS(trans, user, ndd, - ":" + rdd.ns + ":ns", access.name()); - if (rv.isOK()) { - return rv; - } else if(rnsd.status==Result.ERR_Backend) { - return Result.err(rnsd); - } else { - return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]", - user, access.name(), rdd.fullName()); - } - - } - - public Result mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) { - Result rnsd = deriveNs(trans, pdd.ns); - if (rnsd.isOK()) { - return mayUser(trans, user, rnsd.value, pdd, access); - } - return rnsd; - } - - public Result mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, PermDAO.Data pdd, Access access) { - if (isGranted(trans, user, pdd.ns, pdd.type, pdd.instance, pdd.action)) { - return Result.ok(ndd); - } - String permInst = ":perm:" + pdd.type + ':' + pdd.instance + ':' + pdd.action; - // .access|:role:| - String ns = ndd.name; - int last; - do { - if (isGranted(trans, user, ns, ACCESS, permInst, access.name())) { - return Result.ok(ndd); - } - if ((last = ns.lastIndexOf('.')) >= 0) { - ns = ns.substring(0, last); - } - } while (last >= 0); - - // Check if Access by NS perm - // com.att.aaf.ns|::role:name| - Result rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name()); - if (rnsd.isOK()) { - return rnsd; - } else if(rnsd.status==Result.ERR_Backend) { - return Result.err(rnsd); - } - - // Check if Access to Whole NS - // AAF-724 - Make consistent response for May User", and not take the - // last check... too confusing. - Result rv = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + ":ns", access.name()); - if (rv.isOK()) { - return rv; - } else { - return Result.err(Status.ERR_Denied, - "[%s] may not %s Perm [%s|%s|%s]", user, access.name(), - pdd.fullType(), pdd.instance, pdd.action); - } - - } - - public Result mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) { - try { - Result rnsd = deriveNs(trans, domain2ns(trans.user())); - if(rnsd.isOKhasData() && mayUserVirtueOfNS(trans,trans.user(),rnsd.value, ":" + rnsd.value.name + ":ns", access.name()).isOK()) { - return Result.ok(); - } - boolean isUser = trans.user().equals(dd.user); - boolean isDelegate = dd.delegate != null - && (dd.user.equals(dd.delegate) || trans.user().equals( - dd.delegate)); - Organization org = trans.org(); - switch (access) { - case create: - if (org.getIdentity(trans, dd.user) == null) { - return Result.err(Status.ERR_UserNotFound, - "[%s] is not a user in the company database.", - dd.user); - } - if (!dd.user.equals(dd.delegate) && org.getIdentity(trans, dd.delegate) == null) { - return Result.err(Status.ERR_UserNotFound, - "[%s] is not a user in the company database.", - dd.delegate); - } - if (!trans.requested(REQD_TYPE.force) && dd.user != null && dd.user.equals(dd.delegate)) { - return Result.err(Status.ERR_BadData, - "[%s] cannot be a delegate for self", dd.user); - } - if (!isUser && !isGranted(trans, trans.user(), ROOT_NS,DELG, - org.getDomain(), Question.CREATE)) { - return Result.err(Status.ERR_Denied, - "[%s] may not create a delegate for [%s]", - trans.user(), dd.user); - } - break; - case read: - case write: - if (!isUser && !isDelegate && - !isGranted(trans, trans.user(), ROOT_NS,DELG,org.getDomain(), access.name())) { - return Result.err(Status.ERR_Denied, - "[%s] may not %s delegates for [%s]", trans.user(), - access.name(), dd.user); - } - break; - default: - return Result.err(Status.ERR_BadData,"Unknown Access type [%s]", access.name()); - } - } catch (Exception e) { - return Result.err(e); - } - return Result.ok(); - } - - /* - * Check (recursively, if necessary), if able to do something based on NS - */ - private Result mayUserVirtueOfNS(AuthzTrans trans, String user, NsDAO.Data nsd, String ns_and_type, String access) { - String ns = nsd.name; - - // If an ADMIN of the Namespace, then allow - - Result> rurd; - if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) { - return Result.ok(nsd); - } else if(rurd.status==Result.ERR_Backend) { - return Result.err(rurd); - } - - // If Specially granted Global Permission - if (isGranted(trans, user, ROOT_NS,NS, ns_and_type, access)) { - return Result.ok(nsd); - } - - // Check recur - - int dot = ns.length(); - if ((dot = ns.lastIndexOf('.', dot - 1)) >= 0) { - Result rnsd = deriveNs(trans, ns.substring(0, dot)); - if (rnsd.isOK()) { - rnsd = mayUserVirtueOfNS(trans, user, rnsd.value, ns_and_type,access); - } else if(rnsd.status==Result.ERR_Backend) { - return Result.err(rnsd); - } - if (rnsd.isOK()) { - return Result.ok(nsd); - } else if(rnsd.status==Result.ERR_Backend) { - return Result.err(rnsd); - } - } - return Result.err(Status.ERR_Denied, "%s may not %s %s", user, access, - ns_and_type); - } - - - /** - * isGranted - * - * Important function - Check internal Permission Schemes for Permission to - * do things - * - * @param trans - * @param type - * @param instance - * @param action - * @return - */ - public boolean isGranted(AuthzTrans trans, String user, String ns, String type,String instance, String action) { - Result> perms = getPermsByUser(trans, user, false); - if (perms.isOK()) { - for (PermDAO.Data pd : perms.value) { - if (ns.equals(pd.ns)) { - if (type.equals(pd.type)) { - if (PermEval.evalInstance(pd.instance, instance)) { - if(PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action - return true; - } - } - } - } - } - } - return false; - } - - public Result doesUserCredMatch(AuthzTrans trans, String user, byte[] cred) throws DAOException { - Result> result; - TimeTaken tt = trans.start("Read DB Cred", Env.REMOTE); - try { - result = credDAO.readID(trans, user); - } finally { - tt.done(); - } - - Result rv = null; - if(result.isOK()) { - if (result.isEmpty()) { - rv = Result.err(Status.ERR_UserNotFound, user); - if (willSpecialLog(trans,user)) { - trans.audit().log("Special DEBUG:", user, " does not exist in DB"); - } - } else { - Date now = new Date();//long now = System.currentTimeMillis(); - // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues. - List cddl; - if(result.value.size() > 1) { - cddl = new ArrayList<>(result.value.size()); - for(CredDAO.Data old : result.value) { - if(old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) { - cddl.add(old); - } - } - if(cddl.size()>1) { - Collections.sort(cddl,new Comparator() { - @Override - public int compare(org.onap.aaf.auth.dao.cass.CredDAO.Data a, - org.onap.aaf.auth.dao.cass.CredDAO.Data b) { - return b.expires.compareTo(a.expires); - } - }); - } - } else { - cddl = result.value; - } - - Date expired = null; - StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null; - for (CredDAO.Data cdd : cddl) { - if(!cdd.id.equals(user)) { - trans.error().log("doesUserCredMatch DB call does not match for user: " + user); - } - if (cdd.expires.after(now)) { - byte[] dbcred = cdd.cred.array(); - - try { - switch(cdd.type) { - case CredDAO.BASIC_AUTH: - byte[] md5=Hash.hashMD5(cred); - if(Hash.compareTo(md5,dbcred)==0) { - checkLessThanDays(trans,7,now,cdd); - return Result.ok(cdd.expires); - } else if (debug!=null) { - load(debug, cdd); - } - break; - case CredDAO.BASIC_AUTH_SHA256: - ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.length); - bb.putInt(cdd.other); - bb.put(cred); - byte[] hash = Hash.hashSHA256(bb.array()); - - if(Hash.compareTo(hash,dbcred)==0) { - checkLessThanDays(trans,7,now,cdd); - return Result.ok(cdd.expires); - } else if (debug!=null) { - load(debug, cdd); - } - break; - default: - trans.error().log("Unknown Credential Type %s for %s, %s",Integer.toString(cdd.type),cdd.id, Chrono.dateTime(cdd.expires)); - } - } catch (NoSuchAlgorithmException e) { - trans.error().log(e); - } - } else { - if(expired==null || expired.before(cdd.expires)) { - expired = cdd.expires; - } - } - } // end for each - if(debug==null) { - trans.audit().printf("No cred matches ip=%s, user=%s\n",trans.ip(),user); - } else { - trans.audit().printf("No cred matches ip=%s, user=%s %s\n",trans.ip(),user,debug.toString()); - } - if(expired!=null) { - // Note: this is only returned if there are no good Credentials - rv = Result.err(Status.ERR_Security, - "Credentials %s from %s expired %s",trans.user(), trans.ip(), Chrono.dateTime(expired)); - } - } - } else { - return Result.err(result); - } - return rv == null ? Result.create((Date) null, Status.ERR_Security, "Wrong credential") : rv; - } - - - private void load(StringBuilder debug, Data cdd) { - debug.append("DB Entry: user="); - debug.append(cdd.id); - debug.append(",type="); - debug.append(cdd.type); - debug.append(",expires="); - debug.append(Chrono.dateTime(cdd.expires)); - debug.append('\n'); - } - - - private void checkLessThanDays(AuthzTrans trans, int days, Date now, Data cdd) { - long close = now.getTime() + (days * 86400000); - long cexp=cdd.expires.getTime(); - if(cexp userCredSetup(AuthzTrans trans, CredDAO.Data cred) { - if(cred.type==CredDAO.RAW) { - TimeTaken tt = trans.start("Hash Cred", Env.SUB); - try { - cred.type = CredDAO.BASIC_AUTH_SHA256; - cred.other = random.nextInt(); - ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.cred.capacity()); - bb.putInt(cred.other); - bb.put(cred.cred); - byte[] hash = Hash.hashSHA256(bb.array()); - cred.cred = ByteBuffer.wrap(hash); - return Result.ok(cred); - } catch (NoSuchAlgorithmException e) { - return Result.err(Status.ERR_General,e.getLocalizedMessage()); - } finally { - tt.done(); - } - - } - return Result.err(Status.ERR_Security,"invalid/unreadable credential"); - } - - public Result userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) { - TimeTaken tt = trans.start("CheckCred Cred", Env.SUB); - try { - switch(orig.type) { - case CredDAO.BASIC_AUTH_SHA256: - ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length); - bb.putInt(orig.other); - bb.put(raw); - return Result.ok(Hash.compareTo(orig.cred.array(),Hash.hashSHA256(bb.array()))==0); - case CredDAO.BASIC_AUTH: - return Result.ok( Hash.compareTo(orig.cred.array(), Hash.hashMD5(raw))==0); - default: - return Result.ok(false); - } - } catch (NoSuchAlgorithmException e) { - return Result.err(Status.ERR_General,e.getLocalizedMessage()); - } finally { - tt.done(); - } - } - - public static final String APPROVED = "APPROVE"; - public static final String REJECT = "REJECT"; - public static final String PENDING = "PENDING"; - - public Result canAddUser(AuthzTrans trans, UserRoleDAO.Data data, - List approvals) { - // get the approval policy for the organization - - // get the list of approvals with an accept status - - // validate the approvals against the policy - - // for now check if all approvals are received and return - // SUCCESS/FAILURE/SKIP - boolean bReject = false; - boolean bPending = false; - - for (ApprovalDAO.Data approval : approvals) { - if (approval.status.equals(REJECT)) { - bReject = true; - } else if (approval.status.equals(PENDING)) { - bPending = true; - } - } - if (bReject) { - return Result.err(Status.ERR_Policy, - "Approval Polocy not conformed"); - } - if (bPending) { - return Result.err(Status.ERR_ActionNotCompleted, - "Required Approvals not received"); - } - - return Result.ok(); - } - - private static final String NO_CACHE_NAME = "No Cache Data named %s"; - - public Result clearCache(AuthzTrans trans, String cname) { - boolean all = "all".equals(cname); - Result rv = null; - - if (all || NsDAO.TABLE.equals(cname)) { - int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, NsDAO.TABLE,i);} - rv = cacheInfoDAO.touch(trans, NsDAO.TABLE, seg); - } - if (all || PermDAO.TABLE.equals(cname)) { - int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, PermDAO.TABLE,i);} - rv = cacheInfoDAO.touch(trans, PermDAO.TABLE,seg); - } - if (all || RoleDAO.TABLE.equals(cname)) { - int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, RoleDAO.TABLE,i);} - rv = cacheInfoDAO.touch(trans, RoleDAO.TABLE,seg); - } - if (all || UserRoleDAO.TABLE.equals(cname)) { - int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, UserRoleDAO.TABLE,i);} - rv = cacheInfoDAO.touch(trans, UserRoleDAO.TABLE,seg); - } - if (all || CredDAO.TABLE.equals(cname)) { - int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, CredDAO.TABLE,i);} - rv = cacheInfoDAO.touch(trans, CredDAO.TABLE,seg); - } - if (all || CertDAO.TABLE.equals(cname)) { - int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, CertDAO.TABLE,i);} - rv = cacheInfoDAO.touch(trans, CertDAO.TABLE,seg); - } - - if (rv == null) { - rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname); - } - return rv; - } - - public Result cacheClear(AuthzTrans trans, String cname,Integer segment) { - Result rv; - if (NsDAO.TABLE.equals(cname)) { - rv = nsDAO.invalidate(segment); - } else if (PermDAO.TABLE.equals(cname)) { - rv = permDAO.invalidate(segment); - } else if (RoleDAO.TABLE.equals(cname)) { - rv = roleDAO.invalidate(segment); - } else if (UserRoleDAO.TABLE.equals(cname)) { - rv = userRoleDAO.invalidate(segment); - } else if (CredDAO.TABLE.equals(cname)) { - rv = credDAO.invalidate(segment); - } else if (CertDAO.TABLE.equals(cname)) { - rv = certDAO.invalidate(segment); - } else { - rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname); - } - return rv; - } - - private int[] series(int max) { - int[] series = new int[max]; - for (int i = 0; i < max; ++i) - series[i] = i; - return series; - } - - public boolean isDelegated(AuthzTrans trans, String user, String approver, Map>> rldd ) { - Result> userDelegatedFor = rldd.get(user); - if(userDelegatedFor==null) { - userDelegatedFor=delegateDAO.readByDelegate(trans, user); - rldd.put(user, userDelegatedFor); - } - if(userDelegatedFor.isOKhasData()) { - for (DelegateDAO.Data curr : userDelegatedFor.value) { - if (curr.user.equals(approver) && curr.delegate.equals(user) - && curr.expires.after(new Date())) { - return true; - } - } - } - return false; - } - - public static boolean willSpecialLog(AuthzTrans trans, String user) { - Boolean b = trans.get(specialLogSlot, null); - if(b==null) { // we haven't evaluated in this trans for Special Log yet - if(specialLog==null) { - return false; - } else { - b = specialLog.contains(user); - trans.put(specialLogSlot, b); - } - } - return b; - } - - public static void logEncryptTrace(AuthzTrans trans, String data) { - long ti; - trans.put(transIDSlot, ti=nextTraceID()); - trans.trace().log("id="+Long.toHexString(ti)+",data=\""+trans.env().encryptor().encrypt(data)+'"'); - } - - private synchronized static long nextTraceID() { - return ++traceID; - } - - public static synchronized boolean specialLogOn(AuthzTrans trans, String id) { - if (specialLog == null) { - specialLog = new HashSet<>(); - } - boolean rc = specialLog.add(id); - if(rc) { - trans.trace().printf("Trace on for %s requested by %s",id,trans.user()); - } - return rc; - } - - public static synchronized boolean specialLogOff(AuthzTrans trans, String id) { - if(specialLog==null) { - return false; - } - boolean rv = specialLog.remove(id); - if (specialLog.isEmpty()) { - specialLog = null; - } - if(rv) { - trans.trace().printf("Trace off for %s requested by %s",id,trans.user()); - } - return rv; - } - - /** - * canMove - * Which Types can be moved - * @param nsType - * @return - */ - public boolean canMove(NsType nsType) { - boolean rv; - switch(nsType) { - case DOT: - case ROOT: - case COMPANY: - case UNKNOWN: - rv = false; - break; - default: - rv = true; - } - return rv; - } - - public boolean isAdmin(AuthzTrans trans, String user, String ns) { - Date now = new Date(); - Result> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN); - if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ - if(urdd.expires.after(now)) { - return true; - } - }}; - return false; - } - - public boolean isOwner(AuthzTrans trans, String user, String ns) { - Result> rur = userRoleDAO.read(trans, user,ns+DOT_OWNER); - Date now = new Date(); - if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ - if(urdd.expires.after(now)) { - return true; - } - }}; - return false; - } - - public int countOwner(AuthzTrans trans, String ns) { - Result> rur = userRoleDAO.readByRole(trans,ns+DOT_OWNER); - Date now = new Date(); - int count = 0; - if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ - if(urdd.expires.after(now)) { - ++count; - } - }}; - return count; - } - - /** - * Return a Unique String, (same string, if it is already unique), with only - * lowercase letters, digits and the '.' character. - * - * @param name - * @return - * @throws IOException - */ - public static String toUnique(String name) throws IOException { - byte[] from = name.getBytes(); - StringBuilder sb = new StringBuilder(); - byte f; - for(int i=0;i>4)+0x61)); - sb.append((char)((f&0x0F)+0x61)); - } - return sb.toString(); - } - - public static String fromUnique(String name) throws IOException { - byte[] from = name.getBytes(); - StringBuilder sb = new StringBuilder(); - char c; - for(int i=0;i specialLog = null; + public static final Random random = new SecureRandom(); + private static long traceID = random.nextLong(); + private static Slot specialLogSlot = null; + private static Slot transIDSlot = null; + + + public final HistoryDAO historyDAO; + public final CachedNSDAO nsDAO; + public final CachedRoleDAO roleDAO; + public final CachedPermDAO permDAO; + public final CachedUserRoleDAO userRoleDAO; + public final CachedCredDAO credDAO; + public final CachedCertDAO certDAO; + public final DelegateDAO delegateDAO; + public final FutureDAO futureDAO; + public final ApprovalDAO approvalDAO; + private final CacheInfoDAO cacheInfoDAO; + public final LocateDAO locateDAO; + + public Question(AuthzTrans trans, Cluster cluster, String keyspace, boolean startClean) throws APIException, IOException { + PERMS = trans.slot("USER_PERMS"); + trans.init().log("Instantiating DAOs"); + long expiresIn = Long.parseLong(trans.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF)); + historyDAO = new HistoryDAO(trans, cluster, keyspace); + + // Deal with Cached Entries + cacheInfoDAO = new CacheInfoDAO(trans, historyDAO); + + nsDAO = new CachedNSDAO(new NsDAO(trans, historyDAO, cacheInfoDAO),cacheInfoDAO, expiresIn); + permDAO = new CachedPermDAO(new PermDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); + roleDAO = new CachedRoleDAO(new RoleDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); + userRoleDAO = new CachedUserRoleDAO(new UserRoleDAO(trans, historyDAO,cacheInfoDAO), cacheInfoDAO, expiresIn); + credDAO = new CachedCredDAO(new CredDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); + certDAO = new CachedCertDAO(new CertDAO(trans, historyDAO, cacheInfoDAO), cacheInfoDAO, expiresIn); + + locateDAO = new LocateDAO(trans,historyDAO); + futureDAO = new FutureDAO(trans, historyDAO); + delegateDAO = new DelegateDAO(trans, historyDAO); + approvalDAO = new ApprovalDAO(trans, historyDAO); + + // Only want to aggressively cleanse User related Caches... The others, + // just normal refresh + if(startClean) { + CachedDAO.startCleansing(trans.env(), credDAO, userRoleDAO); + CachedDAO.startRefresh(trans.env(), cacheInfoDAO); + } + // Set a Timer to Check Caches to send messages for Caching changes + + if(specialLogSlot==null) { + specialLogSlot = trans.slot(AuthzTransFilter.SPECIAL_LOG_SLOT); + } + + if(transIDSlot==null) { + transIDSlot = trans.slot(AuthzTransFilter.TRANS_ID_SLOT); + } + + AbsCassDAO.primePSIs(trans); + } + + + public void close(AuthzTrans trans) { + historyDAO.close(trans); + cacheInfoDAO.close(trans); + nsDAO.close(trans); + permDAO.close(trans); + roleDAO.close(trans); + userRoleDAO.close(trans); + credDAO.close(trans); + certDAO.close(trans); + delegateDAO.close(trans); + futureDAO.close(trans); + approvalDAO.close(trans); + } + + public Result permFrom(AuthzTrans trans, String type, + String instance, String action) { + Result rnd = deriveNs(trans, type); + if (rnd.isOK()) { + return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type), + instance, action)); + } else { + return Result.err(rnd); + } + } + + /** + * getPermsByUser + * + * Because this call is frequently called internally, AND because we already + * look for it in the initial Call, we cache within the Transaction + * + * @param trans + * @param user + * @return + */ + public Result> getPermsByUser(AuthzTrans trans, String user, boolean lookup) { + return PermLookup.get(trans, this, user).getPerms(lookup); + } + + public Result> getPermsByUserFromRolesFilter(AuthzTrans trans, String user, String forUser) { + PermLookup plUser = PermLookup.get(trans, this, user); + Result> plPermNames = plUser.getPermNames(); + if(plPermNames.notOK()) { + return Result.err(plPermNames); + } + + Set nss; + if(forUser.equals(user)) { + nss = null; + } else { + // Setup a TreeSet to check on Namespaces to + nss = new TreeSet<>(); + PermLookup fUser = PermLookup.get(trans, this, forUser); + Result> forUpn = fUser.getPermNames(); + if(forUpn.notOK()) { + return Result.err(forUpn); + } + + for(String pn : forUpn.value) { + Result decoded = PermDAO.Data.decodeToArray(trans, this, pn); + if(decoded.isOKhasData()) { + nss.add(decoded.value[0]); + } else { + trans.error().log(pn,", derived from a Role, is invalid:",decoded.errorString()); + } + } + } + + List rlpUser = new ArrayList<>(); + Result rpdd; + PermDAO.Data pdd; + for(String pn : plPermNames.value) { + rpdd = PermDAO.Data.decode(trans, this, pn); + if(rpdd.isOKhasData()) { + pdd=rpdd.value; + if(nss==null || nss.contains(pdd.ns)) { + rlpUser.add(pdd); + } + } else { + trans.error().log(pn,", derived from a Role, is invalid. Run Data Cleanup:",rpdd.errorString()); + } + } + return Result.ok(rlpUser); + } + + public Result> getPermsByType(AuthzTrans trans, String perm) { + Result nss = deriveNsSplit(trans, perm); + if (nss.notOK()) { + return Result.err(nss); + } + return permDAO.readByType(trans, nss.value.ns, nss.value.name); + } + + public Result> getPermsByName(AuthzTrans trans, + String type, String instance, String action) { + Result nss = deriveNsSplit(trans, type); + if (nss.notOK()) { + return Result.err(nss); + } + return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action); + } + + public Result> getPermsByRole(AuthzTrans trans, String role, boolean lookup) { + Result nss = deriveNsSplit(trans, role); + if (nss.notOK()) { + return Result.err(nss); + } + + Result> rlrd = roleDAO.read(trans, nss.value.ns, + nss.value.name); + if (rlrd.notOKorIsEmpty()) { + return Result.err(rlrd); + } + // Using Set to avoid duplicates + Set permNames = new HashSet<>(); + if (rlrd.isOKhasData()) { + for (RoleDAO.Data drr : rlrd.value) { + permNames.addAll(drr.perms(false)); + } + } + + // Note: It should be ok for a Valid user to have no permissions - + // Jonathan 8/12/2013 + List perms = new ArrayList<>(); + for (String perm : permNames) { + Result pr = PermDAO.Data.decode(trans, this, perm); + if (pr.notOK()) { + return Result.err(pr); + } + + if(lookup) { + Result> rlpd = permDAO.read(trans, pr.value); + if (rlpd.isOKhasData()) { + for (PermDAO.Data pData : rlpd.value) { + perms.add(pData); + } + } + } else { + perms.add(pr.value); + } + } + + return Result.ok(perms); + } + + public Result> getRolesByName(AuthzTrans trans, + String role) { + Result nss = deriveNsSplit(trans, role); + if (nss.notOK()) { + return Result.err(nss); + } + String r = nss.value.name; + if (r.endsWith(".*")) { // do children Search + return roleDAO.readChildren(trans, nss.value.ns, + r.substring(0, r.length() - 2)); + } else if (ASTERIX.equals(r)) { + return roleDAO.readChildren(trans, nss.value.ns, ASTERIX); + } else { + return roleDAO.read(trans, nss.value.ns, r); + } + } + + /** + * Derive NS + * + * Given a Child Namespace, figure out what the best Namespace parent is. + * + * For instance, if in the NS table, the parent "org.osaaf" exists, but not + * "org.osaaf.child" or "org.osaaf.a.b.c", then passing in either + * "org.osaaf.child" or "org.osaaf.a.b.c" will return "org.osaaf" + * + * Uses recursive search on Cached DAO data + * + * @param trans + * @param child + * @return + */ + public Result deriveNs(AuthzTrans trans, String child) { + Result> r = nsDAO.read(trans, child); + + if (r.isOKhasData()) { + return Result.ok(r.value.get(0)); + } else { + int dot; + if(child==null) { + return Result.err(Status.ERR_NsNotFound, "No Namespace"); + } else { + dot = child.lastIndexOf('.'); + } + if (dot < 0) { + return Result.err(Status.ERR_NsNotFound, "No Namespace for [%s]", child); + } else { + return deriveNs(trans, child.substring(0, dot)); + } + } + } + + public Result deriveFirstNsForType(AuthzTrans trans, String str, NsType type) { + NsDAO.Data nsd; + + for(String lookup = str;!".".equals(lookup) && lookup!=null;) { + Result> rld = nsDAO.read(trans, lookup); + if(rld.isOKhasData()) { + nsd=rld.value.get(0); + lookup = nsd.parent; + if(type.type == nsd.type) { + return Result.ok(nsd); + } + } else { + return Result.err(Status.ERR_NsNotFound,"There is no valid Company Namespace for %s",str); + } + } + return Result.err(Status.ERR_NotFound, str + " does not contain type " + type.name()); + } + + public Result deriveNsSplit(AuthzTrans trans, String child) { + Result ndd = deriveNs(trans, child); + if (ndd.isOK()) { + NsSplit nss = new NsSplit(ndd.value, child); + if (nss.isOK()) { + return Result.ok(nss); + } else { + return Result.err(Status.ERR_NsNotFound, + "Cannot split [%s] into valid namespace elements", + child); + } + } + return Result.err(ndd); + } + + /** + * Translate an ID into it's domain + * + * i.e. myid1234@aaf.att.com results in domain of com.att.aaf + * + * @param id + * @return + */ + public static String domain2ns(String id) { + int at = id.indexOf('@'); + if (at >= 0) { + String[] domain = id.substring(at + 1).split("\\."); + StringBuilder ns = new StringBuilder(id.length()); + boolean first = true; + for (int i = domain.length - 1; i >= 0; --i) { + if (first) { + first = false; + } else { + ns.append('.'); + } + ns.append(domain[i]); + } + return ns.toString(); + } else { + return ""; + } + + } + + /** + * Validate Namespace of ID@Domain + * + * Namespace is reverse order of Domain. + * + * @param trans + * @param id + * @return + */ + public Result validNSOfDomain(AuthzTrans trans, String id) { + // Take domain, reverse order, and check on NS + String ns; + if(id.indexOf('@')<0) { // it's already an ns, not an ID + ns = id; + } else { + ns = domain2ns(id); + } + if (ns.length() > 0) { + if(!trans.org().getDomain().equals(ns)) { + Result> rlnsd = nsDAO.read(trans, ns); + if (rlnsd.isOKhasData()) { + return Result.ok(rlnsd.value.get(0)); + } + } + } + return Result.err(Status.ERR_NsNotFound, + "A Namespace is not available for %s", id); + } + + public Result mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, Access access) { + // .access|:role:| + String ns = ndd.name; + int last; + do { + if (isGranted(trans, user, ns, ACCESS, ":ns", access.name())) { + return Result.ok(ndd); + } + if ((last = ns.lastIndexOf('.')) >= 0) { + ns = ns.substring(0, last); + } + } while (last >= 0); + // com.att.aaf.ns|::ns| + // AAF-724 - Make consistent response for May User", and not take the + // last check... too confusing. + Result rv = mayUserVirtueOfNS(trans, user, ndd, ":" + ndd.name + ":ns", access.name()); + if (rv.isOK()) { + return rv; + } else if(rv.status==Result.ERR_Backend) { + return Result.err(rv); + } else { + return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]", + user, access.name(), ndd.name); + } + } + + public Result mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) { + Result rnsd = deriveNs(trans, rdd.ns); + if (rnsd.isOK()) { + return mayUser(trans, user, rnsd.value, rdd, access); + } + return rnsd; + } + + public Result mayUser(AuthzTrans trans, String user, NsDAO.Data ndd, RoleDAO.Data rdd, Access access) { + // 1) Is User in the Role? + Result> rurd = userRoleDAO.readUserInRole(trans, user, rdd.fullName()); + if (rurd.isOKhasData()) { + return Result.ok(ndd); + } + + String roleInst = ":role:" + rdd.name; + // .access|:role:| + String ns = rdd.ns; + int last; + do { + if (isGranted(trans, user, ns,ACCESS, roleInst, access.name())) { + return Result.ok(ndd); + } + if ((last = ns.lastIndexOf('.')) >= 0) { + ns = ns.substring(0, last); + } + } while (last >= 0); + + // Check if Access by Global Role perm + // com.att.aaf.ns|::role:name| + Result rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + + rdd.ns + roleInst, access.name()); + if (rnsd.isOK()) { + return rnsd; + } else if(rnsd.status==Result.ERR_Backend) { + return Result.err(rnsd); + } + + // Check if Access to Whole NS + // AAF-724 - Make consistent response for May User", and not take the + // last check... too confusing. + Result rv = mayUserVirtueOfNS(trans, user, ndd, + ":" + rdd.ns + ":ns", access.name()); + if (rv.isOK()) { + return rv; + } else if(rnsd.status==Result.ERR_Backend) { + return Result.err(rnsd); + } else { + return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]", + user, access.name(), rdd.fullName()); + } + + } + + public Result mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) { + Result rnsd = deriveNs(trans, pdd.ns); + if (rnsd.isOK()) { + return mayUser(trans, user, rnsd.value, pdd, access); + } + return rnsd; + } + + public Result mayUser(AuthzTrans trans, String user,NsDAO.Data ndd, PermDAO.Data pdd, Access access) { + if (isGranted(trans, user, pdd.ns, pdd.type, pdd.instance, pdd.action)) { + return Result.ok(ndd); + } + String permInst = ":perm:" + pdd.type + ':' + pdd.instance + ':' + pdd.action; + // .access|:role:| + String ns = ndd.name; + int last; + do { + if (isGranted(trans, user, ns, ACCESS, permInst, access.name())) { + return Result.ok(ndd); + } + if ((last = ns.lastIndexOf('.')) >= 0) { + ns = ns.substring(0, last); + } + } while (last >= 0); + + // Check if Access by NS perm + // com.att.aaf.ns|::role:name| + Result rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name()); + if (rnsd.isOK()) { + return rnsd; + } else if(rnsd.status==Result.ERR_Backend) { + return Result.err(rnsd); + } + + // Check if Access to Whole NS + // AAF-724 - Make consistent response for May User", and not take the + // last check... too confusing. + Result rv = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + ":ns", access.name()); + if (rv.isOK()) { + return rv; + } else { + return Result.err(Status.ERR_Denied, + "[%s] may not %s Perm [%s|%s|%s]", user, access.name(), + pdd.fullType(), pdd.instance, pdd.action); + } + + } + + public Result mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) { + try { + Result rnsd = deriveNs(trans, domain2ns(trans.user())); + if(rnsd.isOKhasData() && mayUserVirtueOfNS(trans,trans.user(),rnsd.value, ":" + rnsd.value.name + ":ns", access.name()).isOK()) { + return Result.ok(); + } + boolean isUser = trans.user().equals(dd.user); + boolean isDelegate = dd.delegate != null + && (dd.user.equals(dd.delegate) || trans.user().equals( + dd.delegate)); + Organization org = trans.org(); + switch (access) { + case create: + if (org.getIdentity(trans, dd.user) == null) { + return Result.err(Status.ERR_UserNotFound, + "[%s] is not a user in the company database.", + dd.user); + } + if (!dd.user.equals(dd.delegate) && org.getIdentity(trans, dd.delegate) == null) { + return Result.err(Status.ERR_UserNotFound, + "[%s] is not a user in the company database.", + dd.delegate); + } + if (!trans.requested(REQD_TYPE.force) && dd.user != null && dd.user.equals(dd.delegate)) { + return Result.err(Status.ERR_BadData, + "[%s] cannot be a delegate for self", dd.user); + } + if (!isUser && !isGranted(trans, trans.user(), ROOT_NS,DELG, + org.getDomain(), Question.CREATE)) { + return Result.err(Status.ERR_Denied, + "[%s] may not create a delegate for [%s]", + trans.user(), dd.user); + } + break; + case read: + case write: + if (!isUser && !isDelegate && + !isGranted(trans, trans.user(), ROOT_NS,DELG,org.getDomain(), access.name())) { + return Result.err(Status.ERR_Denied, + "[%s] may not %s delegates for [%s]", trans.user(), + access.name(), dd.user); + } + break; + default: + return Result.err(Status.ERR_BadData,"Unknown Access type [%s]", access.name()); + } + } catch (Exception e) { + return Result.err(e); + } + return Result.ok(); + } + + /* + * Check (recursively, if necessary), if able to do something based on NS + */ + private Result mayUserVirtueOfNS(AuthzTrans trans, String user, NsDAO.Data nsd, String ns_and_type, String access) { + String ns = nsd.name; + + // If an ADMIN of the Namespace, then allow + + Result> rurd; + if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) { + return Result.ok(nsd); + } else if(rurd.status==Result.ERR_Backend) { + return Result.err(rurd); + } + + // If Specially granted Global Permission + if (isGranted(trans, user, ROOT_NS,NS, ns_and_type, access)) { + return Result.ok(nsd); + } + + // Check recur + + int dot = ns.length(); + if ((dot = ns.lastIndexOf('.', dot - 1)) >= 0) { + Result rnsd = deriveNs(trans, ns.substring(0, dot)); + if (rnsd.isOK()) { + rnsd = mayUserVirtueOfNS(trans, user, rnsd.value, ns_and_type,access); + } else if(rnsd.status==Result.ERR_Backend) { + return Result.err(rnsd); + } + if (rnsd.isOK()) { + return Result.ok(nsd); + } else if(rnsd.status==Result.ERR_Backend) { + return Result.err(rnsd); + } + } + return Result.err(Status.ERR_Denied, "%s may not %s %s", user, access, + ns_and_type); + } + + + /** + * isGranted + * + * Important function - Check internal Permission Schemes for Permission to + * do things + * + * @param trans + * @param type + * @param instance + * @param action + * @return + */ + public boolean isGranted(AuthzTrans trans, String user, String ns, String type,String instance, String action) { + Result> perms = getPermsByUser(trans, user, false); + if (perms.isOK()) { + for (PermDAO.Data pd : perms.value) { + if (ns.equals(pd.ns)) { + if (type.equals(pd.type)) { + if (PermEval.evalInstance(pd.instance, instance)) { + if(PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action + return true; + } + } + } + } + } + } + return false; + } + + public Result doesUserCredMatch(AuthzTrans trans, String user, byte[] cred) throws DAOException { + Result> result; + TimeTaken tt = trans.start("Read DB Cred", Env.REMOTE); + try { + result = credDAO.readID(trans, user); + } finally { + tt.done(); + } + + Result rv = null; + if(result.isOK()) { + if (result.isEmpty()) { + rv = Result.err(Status.ERR_UserNotFound, user); + if (willSpecialLog(trans,user)) { + trans.audit().log("Special DEBUG:", user, " does not exist in DB"); + } + } else { + Date now = new Date();//long now = System.currentTimeMillis(); + // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues. + List cddl; + if(result.value.size() > 1) { + cddl = new ArrayList<>(result.value.size()); + for(CredDAO.Data old : result.value) { + if(old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) { + cddl.add(old); + } + } + if(cddl.size()>1) { + Collections.sort(cddl,new Comparator() { + @Override + public int compare(org.onap.aaf.auth.dao.cass.CredDAO.Data a, + org.onap.aaf.auth.dao.cass.CredDAO.Data b) { + return b.expires.compareTo(a.expires); + } + }); + } + } else { + cddl = result.value; + } + + Date expired = null; + StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null; + for (CredDAO.Data cdd : cddl) { + if(!cdd.id.equals(user)) { + trans.error().log("doesUserCredMatch DB call does not match for user: " + user); + } + if (cdd.expires.after(now)) { + byte[] dbcred = cdd.cred.array(); + + try { + switch(cdd.type) { + case CredDAO.BASIC_AUTH: + byte[] md5=Hash.hashMD5(cred); + if(Hash.compareTo(md5,dbcred)==0) { + checkLessThanDays(trans,7,now,cdd); + return Result.ok(cdd.expires); + } else if (debug!=null) { + load(debug, cdd); + } + break; + case CredDAO.BASIC_AUTH_SHA256: + ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.length); + bb.putInt(cdd.other); + bb.put(cred); + byte[] hash = Hash.hashSHA256(bb.array()); + + if(Hash.compareTo(hash,dbcred)==0) { + checkLessThanDays(trans,7,now,cdd); + return Result.ok(cdd.expires); + } else if (debug!=null) { + load(debug, cdd); + } + break; + default: + trans.error().log("Unknown Credential Type %s for %s, %s",Integer.toString(cdd.type),cdd.id, Chrono.dateTime(cdd.expires)); + } + } catch (NoSuchAlgorithmException e) { + trans.error().log(e); + } + } else { + if(expired==null || expired.before(cdd.expires)) { + expired = cdd.expires; + } + } + } // end for each + if(debug==null) { + trans.audit().printf("No cred matches ip=%s, user=%s\n",trans.ip(),user); + } else { + trans.audit().printf("No cred matches ip=%s, user=%s %s\n",trans.ip(),user,debug.toString()); + } + if(expired!=null) { + // Note: this is only returned if there are no good Credentials + rv = Result.err(Status.ERR_Security, + "Credentials %s from %s expired %s",trans.user(), trans.ip(), Chrono.dateTime(expired)); + } + } + } else { + return Result.err(result); + } + return rv == null ? Result.create((Date) null, Status.ERR_Security, "Wrong credential") : rv; + } + + + private void load(StringBuilder debug, Data cdd) { + debug.append("DB Entry: user="); + debug.append(cdd.id); + debug.append(",type="); + debug.append(cdd.type); + debug.append(",expires="); + debug.append(Chrono.dateTime(cdd.expires)); + debug.append('\n'); + } + + + private void checkLessThanDays(AuthzTrans trans, int days, Date now, Data cdd) { + long close = now.getTime() + (days * 86400000); + long cexp=cdd.expires.getTime(); + if(cexp userCredSetup(AuthzTrans trans, CredDAO.Data cred) { + if(cred.type==CredDAO.RAW) { + TimeTaken tt = trans.start("Hash Cred", Env.SUB); + try { + cred.type = CredDAO.BASIC_AUTH_SHA256; + cred.other = random.nextInt(); + ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + cred.cred.capacity()); + bb.putInt(cred.other); + bb.put(cred.cred); + byte[] hash = Hash.hashSHA256(bb.array()); + cred.cred = ByteBuffer.wrap(hash); + return Result.ok(cred); + } catch (NoSuchAlgorithmException e) { + return Result.err(Status.ERR_General,e.getLocalizedMessage()); + } finally { + tt.done(); + } + + } + return Result.err(Status.ERR_Security,"invalid/unreadable credential"); + } + + public Result userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) { + TimeTaken tt = trans.start("CheckCred Cred", Env.SUB); + try { + switch(orig.type) { + case CredDAO.BASIC_AUTH_SHA256: + ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + raw.length); + bb.putInt(orig.other); + bb.put(raw); + return Result.ok(Hash.compareTo(orig.cred.array(),Hash.hashSHA256(bb.array()))==0); + case CredDAO.BASIC_AUTH: + return Result.ok( Hash.compareTo(orig.cred.array(), Hash.hashMD5(raw))==0); + default: + return Result.ok(false); + } + } catch (NoSuchAlgorithmException e) { + return Result.err(Status.ERR_General,e.getLocalizedMessage()); + } finally { + tt.done(); + } + } + + public static final String APPROVED = "APPROVE"; + public static final String REJECT = "REJECT"; + public static final String PENDING = "PENDING"; + + public Result canAddUser(AuthzTrans trans, UserRoleDAO.Data data, + List approvals) { + // get the approval policy for the organization + + // get the list of approvals with an accept status + + // validate the approvals against the policy + + // for now check if all approvals are received and return + // SUCCESS/FAILURE/SKIP + boolean bReject = false; + boolean bPending = false; + + for (ApprovalDAO.Data approval : approvals) { + if (approval.status.equals(REJECT)) { + bReject = true; + } else if (approval.status.equals(PENDING)) { + bPending = true; + } + } + if (bReject) { + return Result.err(Status.ERR_Policy, + "Approval Polocy not conformed"); + } + if (bPending) { + return Result.err(Status.ERR_ActionNotCompleted, + "Required Approvals not received"); + } + + return Result.ok(); + } + + private static final String NO_CACHE_NAME = "No Cache Data named %s"; + + public Result clearCache(AuthzTrans trans, String cname) { + boolean all = "all".equals(cname); + Result rv = null; + + if (all || NsDAO.TABLE.equals(cname)) { + int seg[] = series(NsDAO.CACHE_SEG); + for(int i: seg) {cacheClear(trans, NsDAO.TABLE,i);} + rv = cacheInfoDAO.touch(trans, NsDAO.TABLE, seg); + } + if (all || PermDAO.TABLE.equals(cname)) { + int seg[] = series(NsDAO.CACHE_SEG); + for(int i: seg) {cacheClear(trans, PermDAO.TABLE,i);} + rv = cacheInfoDAO.touch(trans, PermDAO.TABLE,seg); + } + if (all || RoleDAO.TABLE.equals(cname)) { + int seg[] = series(NsDAO.CACHE_SEG); + for(int i: seg) {cacheClear(trans, RoleDAO.TABLE,i);} + rv = cacheInfoDAO.touch(trans, RoleDAO.TABLE,seg); + } + if (all || UserRoleDAO.TABLE.equals(cname)) { + int seg[] = series(NsDAO.CACHE_SEG); + for(int i: seg) {cacheClear(trans, UserRoleDAO.TABLE,i);} + rv = cacheInfoDAO.touch(trans, UserRoleDAO.TABLE,seg); + } + if (all || CredDAO.TABLE.equals(cname)) { + int seg[] = series(NsDAO.CACHE_SEG); + for(int i: seg) {cacheClear(trans, CredDAO.TABLE,i);} + rv = cacheInfoDAO.touch(trans, CredDAO.TABLE,seg); + } + if (all || CertDAO.TABLE.equals(cname)) { + int seg[] = series(NsDAO.CACHE_SEG); + for(int i: seg) {cacheClear(trans, CertDAO.TABLE,i);} + rv = cacheInfoDAO.touch(trans, CertDAO.TABLE,seg); + } + + if (rv == null) { + rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname); + } + return rv; + } + + public Result cacheClear(AuthzTrans trans, String cname,Integer segment) { + Result rv; + if (NsDAO.TABLE.equals(cname)) { + rv = nsDAO.invalidate(segment); + } else if (PermDAO.TABLE.equals(cname)) { + rv = permDAO.invalidate(segment); + } else if (RoleDAO.TABLE.equals(cname)) { + rv = roleDAO.invalidate(segment); + } else if (UserRoleDAO.TABLE.equals(cname)) { + rv = userRoleDAO.invalidate(segment); + } else if (CredDAO.TABLE.equals(cname)) { + rv = credDAO.invalidate(segment); + } else if (CertDAO.TABLE.equals(cname)) { + rv = certDAO.invalidate(segment); + } else { + rv = Result.err(Status.ERR_BadData, NO_CACHE_NAME, cname); + } + return rv; + } + + private int[] series(int max) { + int[] series = new int[max]; + for (int i = 0; i < max; ++i) + series[i] = i; + return series; + } + + public boolean isDelegated(AuthzTrans trans, String user, String approver, Map>> rldd ) { + Result> userDelegatedFor = rldd.get(user); + if(userDelegatedFor==null) { + userDelegatedFor=delegateDAO.readByDelegate(trans, user); + rldd.put(user, userDelegatedFor); + } + if(userDelegatedFor.isOKhasData()) { + for (DelegateDAO.Data curr : userDelegatedFor.value) { + if (curr.user.equals(approver) && curr.delegate.equals(user) + && curr.expires.after(new Date())) { + return true; + } + } + } + return false; + } + + public static boolean willSpecialLog(AuthzTrans trans, String user) { + Boolean b = trans.get(specialLogSlot, null); + if(b==null) { // we haven't evaluated in this trans for Special Log yet + if(specialLog==null) { + return false; + } else { + b = specialLog.contains(user); + trans.put(specialLogSlot, b); + } + } + return b; + } + + public static void logEncryptTrace(AuthzTrans trans, String data) { + long ti; + trans.put(transIDSlot, ti=nextTraceID()); + trans.trace().log("id="+Long.toHexString(ti)+",data=\""+trans.env().encryptor().encrypt(data)+'"'); + } + + private synchronized static long nextTraceID() { + return ++traceID; + } + + public static synchronized boolean specialLogOn(AuthzTrans trans, String id) { + if (specialLog == null) { + specialLog = new HashSet<>(); + } + boolean rc = specialLog.add(id); + if(rc) { + trans.trace().printf("Trace on for %s requested by %s",id,trans.user()); + } + return rc; + } + + public static synchronized boolean specialLogOff(AuthzTrans trans, String id) { + if(specialLog==null) { + return false; + } + boolean rv = specialLog.remove(id); + if (specialLog.isEmpty()) { + specialLog = null; + } + if(rv) { + trans.trace().printf("Trace off for %s requested by %s",id,trans.user()); + } + return rv; + } + + /** + * canMove + * Which Types can be moved + * @param nsType + * @return + */ + public boolean canMove(NsType nsType) { + boolean rv; + switch(nsType) { + case DOT: + case ROOT: + case COMPANY: + case UNKNOWN: + rv = false; + break; + default: + rv = true; + } + return rv; + } + + public boolean isAdmin(AuthzTrans trans, String user, String ns) { + Date now = new Date(); + Result> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN); + if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ + if(urdd.expires.after(now)) { + return true; + } + }}; + return false; + } + + public boolean isOwner(AuthzTrans trans, String user, String ns) { + Result> rur = userRoleDAO.read(trans, user,ns+DOT_OWNER); + Date now = new Date(); + if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ + if(urdd.expires.after(now)) { + return true; + } + }}; + return false; + } + + public int countOwner(AuthzTrans trans, String ns) { + Result> rur = userRoleDAO.readByRole(trans,ns+DOT_OWNER); + Date now = new Date(); + int count = 0; + if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ + if(urdd.expires.after(now)) { + ++count; + } + }}; + return count; + } + + /** + * Return a Unique String, (same string, if it is already unique), with only + * lowercase letters, digits and the '.' character. + * + * @param name + * @return + * @throws IOException + */ + public static String toUnique(String name) throws IOException { + byte[] from = name.getBytes(); + StringBuilder sb = new StringBuilder(); + byte f; + for(int i=0;i>4)+0x61)); + sb.append((char)((f&0x0F)+0x61)); + } + return sb.toString(); + } + + public static String fromUnique(String name) throws IOException { + byte[] from = name.getBytes(); + StringBuilder sb = new StringBuilder(); + char c; + for(int i=0;i { - private LocateDAO ldao; - private int major=-1, minor=-1, patch=-1, pkg=-1; - private AuthzEnv env; - private final URI uri; + private LocateDAO ldao; + private int major=-1, minor=-1, patch=-1, pkg=-1; + private AuthzEnv env; + private final URI uri; - /** - * - * @param env - * @param ldao - * @param key must be one or more of service, version, other in that order - * @throws LocatorException - */ - public DirectAAFLocator(AuthzEnv env, LocateDAO ldao, String name, String version) throws LocatorException { - super(env.access(), name, 1000L /* Don't hit DB more than once a second */); - this.env = env; - this.ldao = ldao; - if(version!=null) { - try { - String[] v = Split.split('.',version); - if(v.length>0) {major = Integer.parseInt(v[0]);} - if(v.length>1) {minor = Integer.parseInt(v[1]);} - if(v.length>2) {patch = Integer.parseInt(v[2]);} - if(v.length>3) {pkg = Integer.parseInt(v[3]);} - } catch (NumberFormatException e) { - throw new LocatorException("Invalid Version String: " + version); - } - } - - try { - uri = new URI(access.getProperty(Config.AAF_LOCATE_URL, "localhost")+"/locate/"+name+':'+version); - } catch (URISyntaxException e) { - throw new LocatorException(e); - } - myhostname=null; - myport = 0; - } - - - @Override - public boolean refresh() { - AuthzTrans trans = env.newTransNoAvg(); - Result> rl = ldao.readByName(trans, name); - if(rl.isOK()) { - LinkedList epl = new LinkedList<>(); - for(Data d : rl.value) { -// if(myhostname!=null && d.port==myport && d.hostname.equals(myhostname)) { -// continue; -// } - if((major<0 || major==d.major) && - (minor<0 || minor<=d.minor) && - (patch<0 || patch==d.patch) && - (pkg<0 || pkg ==d.pkg)) { - Endpoint endpoint = new Endpoint(); - endpoint.setName(d.name); - endpoint.setHostname(d.hostname); - endpoint.setPort(d.port); - endpoint.setMajor(d.major); - endpoint.setMinor(d.minor); - endpoint.setPatch(d.patch); - endpoint.setPkg(d.pkg); - endpoint.setLatitude(d.latitude); - endpoint.setLongitude(d.longitude); - endpoint.setProtocol(d.protocol); - for(String s : d.subprotocol(false)) { - endpoint.getSubprotocol().add(s); - } - - try { - epl.add(new EP(endpoint,latitude,longitude)); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - } - } - Collections.sort(epl); - replace(epl); - return true; - } else { - access.log(Level.ERROR, rl.errorString()); - } - return false; - } + /** + * + * @param env + * @param ldao + * @param key must be one or more of service, version, other in that order + * @throws LocatorException + */ + public DirectAAFLocator(AuthzEnv env, LocateDAO ldao, String name, String version) throws LocatorException { + super(env.access(), name, 1000L /* Don't hit DB more than once a second */); + this.env = env; + this.ldao = ldao; + if(version!=null) { + try { + String[] v = Split.split('.',version); + if(v.length>0) {major = Integer.parseInt(v[0]);} + if(v.length>1) {minor = Integer.parseInt(v[1]);} + if(v.length>2) {patch = Integer.parseInt(v[2]);} + if(v.length>3) {pkg = Integer.parseInt(v[3]);} + } catch (NumberFormatException e) { + throw new LocatorException("Invalid Version String: " + version); + } + } + + try { + uri = new URI(access.getProperty(Config.AAF_LOCATE_URL, "localhost")+"/locate/"+name+':'+version); + } catch (URISyntaxException e) { + throw new LocatorException(e); + } + myhostname=null; + myport = 0; + } + + + @Override + public boolean refresh() { + AuthzTrans trans = env.newTransNoAvg(); + Result> rl = ldao.readByName(trans, name); + if(rl.isOK()) { + LinkedList epl = new LinkedList<>(); + for(Data d : rl.value) { +// if(myhostname!=null && d.port==myport && d.hostname.equals(myhostname)) { +// continue; +// } + if((major<0 || major==d.major) && + (minor<0 || minor<=d.minor) && + (patch<0 || patch==d.patch) && + (pkg<0 || pkg ==d.pkg)) { + Endpoint endpoint = new Endpoint(); + endpoint.setName(d.name); + endpoint.setHostname(d.hostname); + endpoint.setPort(d.port); + endpoint.setMajor(d.major); + endpoint.setMinor(d.minor); + endpoint.setPatch(d.patch); + endpoint.setPkg(d.pkg); + endpoint.setLatitude(d.latitude); + endpoint.setLongitude(d.longitude); + endpoint.setProtocol(d.protocol); + for(String s : d.subprotocol(false)) { + endpoint.getSubprotocol().add(s); + } + + try { + epl.add(new EP(endpoint,latitude,longitude)); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + } + } + Collections.sort(epl); + replace(epl); + return true; + } else { + access.log(Level.ERROR, rl.errorString()); + } + return false; + } - @Override - protected URI getURI() { - return uri; - } + @Override + protected URI getURI() { + return uri; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java index eb44e143..75f6c7a5 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java @@ -42,158 +42,158 @@ import org.onap.aaf.cadi.lur.LocalPermission; import org.onap.aaf.misc.env.util.Split; public class DirectAAFLur implements Lur { - private final AuthzEnv env; - private final Question question; - - public DirectAAFLur(AuthzEnv env, Question question/*, TokenMgr tm*/) { - this.env = env; - this.question = question; -// oauth = new OAuth2Lur(null); - } + private final AuthzEnv env; + private final Question question; + + public DirectAAFLur(AuthzEnv env, Question question/*, TokenMgr tm*/) { + this.env = env; + this.question = question; +// oauth = new OAuth2Lur(null); + } - @Override - public boolean fish(Principal bait, Permission ... pond) { - return fish(env.newTransNoAvg(),bait,pond); - } - - public boolean fish(AuthzTrans trans, Principal bait, Permission ... pond) { - boolean rv = false; - Result> pdr = question.getPermsByUser(trans, bait.getName(),false); - switch(pdr.status) { - case OK: - for(PermDAO.Data d : pdr.value) { - if(!rv) { - for (Permission p : pond) { - if(new PermPermission(d).match(p)) { - rv=true; - break; - } - } - } - } - break; - case Status.ERR_UserRoleNotFound: - case Status.ERR_BadData: - return false; - default: - trans.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-",pdr.details); - } - return rv; - } + @Override + public boolean fish(Principal bait, Permission ... pond) { + return fish(env.newTransNoAvg(),bait,pond); + } + + public boolean fish(AuthzTrans trans, Principal bait, Permission ... pond) { + boolean rv = false; + Result> pdr = question.getPermsByUser(trans, bait.getName(),false); + switch(pdr.status) { + case OK: + for(PermDAO.Data d : pdr.value) { + if(!rv) { + for (Permission p : pond) { + if(new PermPermission(d).match(p)) { + rv=true; + break; + } + } + } + } + break; + case Status.ERR_UserRoleNotFound: + case Status.ERR_BadData: + return false; + default: + trans.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-",pdr.details); + } + return rv; + } - @Override - public void fishAll(Principal bait, List permissions) { - Result> pdr = question.getPermsByUser(env.newTrans(), bait.getName(),false); - switch(pdr.status) { - case OK: - for(PermDAO.Data d : pdr.value) { - permissions.add(new PermPermission(d)); - } - break; - default: - env.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-", pdr.details); - } - } - - @Override - public void destroy() { - } + @Override + public void fishAll(Principal bait, List permissions) { + Result> pdr = question.getPermsByUser(env.newTrans(), bait.getName(),false); + switch(pdr.status) { + case OK: + for(PermDAO.Data d : pdr.value) { + permissions.add(new PermPermission(d)); + } + break; + default: + env.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-", pdr.details); + } + } + + @Override + public void destroy() { + } - @Override - public boolean handlesExclusively(Permission ... pond) { - return false; - } - - /** - * Small Class implementing CADI's Permission with Cassandra Data - * @author Jonathan - * - */ - public static class PermPermission implements Permission { - private PermDAO.Data data; - - public PermPermission(PermDAO.Data d) { - data = d; - } - - public PermPermission(AuthzTrans trans, Question q, String p) { - data = PermDAO.Data.create(trans, q, p); - } - - public PermPermission(String ns, String type, String instance, String action) { - data = new PermDAO.Data(); - data.ns = ns; - data.type = type; - data.instance = instance; - data.action = action; - } + @Override + public boolean handlesExclusively(Permission ... pond) { + return false; + } + + /** + * Small Class implementing CADI's Permission with Cassandra Data + * @author Jonathan + * + */ + public static class PermPermission implements Permission { + private PermDAO.Data data; + + public PermPermission(PermDAO.Data d) { + data = d; + } + + public PermPermission(AuthzTrans trans, Question q, String p) { + data = PermDAO.Data.create(trans, q, p); + } + + public PermPermission(String ns, String type, String instance, String action) { + data = new PermDAO.Data(); + data.ns = ns; + data.type = type; + data.instance = instance; + data.action = action; + } - @Override - public String getKey() { - return data.type; - } + @Override + public String getKey() { + return data.type; + } - @Override - public boolean match(Permission p) { - if(p==null) { - return false; - } - PermDAO.Data pd; - if(p instanceof DirectAAFLur.PermPermission) { - pd = ((DirectAAFLur.PermPermission)p).data; - if(data.ns.equals(pd.ns)) - if(data.type.equals(pd.type)) - if(data.instance!=null && (data.instance.equals(pd.instance) || "*".equals(data.instance))) - if(data.action!=null && (data.action.equals(pd.action) || "*".equals(data.action))) - return true; - } else{ - String[] lp = p.getKey().split("\\|"); - if(lp.length<3)return false; - if(data.fullType().equals(lp[0])) - if(data.instance!=null && (data.instance.equals(lp[1]) || "*".equals(data.instance))) - if(data.action!=null && (data.action.equals(lp[2]) || "*".equals(data.action))) - return true; - } - return false; - } + @Override + public boolean match(Permission p) { + if(p==null) { + return false; + } + PermDAO.Data pd; + if(p instanceof DirectAAFLur.PermPermission) { + pd = ((DirectAAFLur.PermPermission)p).data; + if(data.ns.equals(pd.ns)) + if(data.type.equals(pd.type)) + if(data.instance!=null && (data.instance.equals(pd.instance) || "*".equals(data.instance))) + if(data.action!=null && (data.action.equals(pd.action) || "*".equals(data.action))) + return true; + } else{ + String[] lp = p.getKey().split("\\|"); + if(lp.length<3)return false; + if(data.fullType().equals(lp[0])) + if(data.instance!=null && (data.instance.equals(lp[1]) || "*".equals(data.instance))) + if(data.action!=null && (data.action.equals(lp[2]) || "*".equals(data.action))) + return true; + } + return false; + } - @Override - public String permType() { - return "AAFLUR"; - } - - } - - public String toString() { - return "DirectAAFLur is enabled"; - - } + @Override + public String permType() { + return "AAFLUR"; + } + + } + + public String toString() { + return "DirectAAFLur is enabled"; + + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#handles(java.security.Principal) - */ - @Override - public boolean handles(Principal principal) { - return true; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#handles(java.security.Principal) + */ + @Override + public boolean handles(Principal principal) { + return true; + } - @Override - public Permission createPerm(String p) { - String[] params = Split.split('|', p); - if(params.length==3) { - Result nss = question.deriveNsSplit(NullTrans.singleton(), params[0]); - if(nss.isOK()) { - return new PermPermission(nss.value.ns,nss.value.name,params[1],params[2]); - } - } - return new LocalPermission(p); - } + @Override + public Permission createPerm(String p) { + String[] params = Split.split('|', p); + if(params.length==3) { + Result nss = question.deriveNsSplit(NullTrans.singleton(), params[0]); + if(nss.isOK()) { + return new PermPermission(nss.value.ns,nss.value.name,params[1],params[2]); + } + } + return new LocalPermission(p); + } - @Override - public void clear(Principal p, StringBuilder sb) { - AuthzTrans trans = env.newTrans(); - question.clearCache(trans,"all"); - env.log(Level.AUDIT, p.getName(), "has cleared Cache for",getClass().getSimpleName()); - trans.auditTrail(0, sb); - } + @Override + public void clear(Principal p, StringBuilder sb) { + AuthzTrans trans = env.newTrans(); + question.clearCache(trans,"all"); + env.log(Level.AUDIT, p.getName(), "has cleared Cache for",getClass().getSimpleName()); + trans.auditTrail(0, sb); + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java index f241cdf1..9d4cd05f 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java @@ -42,42 +42,42 @@ import org.onap.aaf.cadi.CredVal; * */ public class DirectAAFUserPass implements CredVal { - private final AuthzEnv env; - private final Question question; - - public DirectAAFUserPass(AuthzEnv env, Question question) { - this.env = env; - this.question = question; - } + private final AuthzEnv env; + private final Question question; + + public DirectAAFUserPass(AuthzEnv env, Question question) { + this.env = env; + this.question = question; + } - @Override - public boolean validate(String user, Type type, byte[] pass, Object state) { - try { - AuthzTrans trans; - if(state !=null) { - if(state instanceof AuthzTrans) { - trans = (AuthzTrans)state; - } else { - trans = env.newTransNoAvg(); - if(state instanceof HttpServletRequest) { - trans.set((HttpServletRequest)state); - } - } - } else { - trans = env.newTransNoAvg(); - } - Result result = question.doesUserCredMatch(trans, user, pass); - trans.logAuditTrail(env.info()); - switch(result.status) { - case OK: - return true; - default: - String ip = trans.ip()==null?"":(", ip="+trans.ip()); - env.warn().log(user, "failed password validation" + ip + ':',result.errorString()); - } - } catch (DAOException e) { - env.error().log(e,"Cannot validate user/pass from cassandra"); - } - return false; - } + @Override + public boolean validate(String user, Type type, byte[] pass, Object state) { + try { + AuthzTrans trans; + if(state !=null) { + if(state instanceof AuthzTrans) { + trans = (AuthzTrans)state; + } else { + trans = env.newTransNoAvg(); + if(state instanceof HttpServletRequest) { + trans.set((HttpServletRequest)state); + } + } + } else { + trans = env.newTransNoAvg(); + } + Result result = question.doesUserCredMatch(trans, user, pass); + trans.logAuditTrail(env.info()); + switch(result.status) { + case OK: + return true; + default: + String ip = trans.ip()==null?"":(", ip="+trans.ip()); + env.warn().log(user, "failed password validation" + ip + ':',result.errorString()); + } + } catch (DAOException e) { + env.error().log(e,"Cannot validate user/pass from cassandra"); + } + return false; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java index 2c0c054b..6dd5e006 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java @@ -48,31 +48,31 @@ import org.onap.aaf.cadi.taf.cert.X509Taf; * */ public class DirectCertIdentity implements CertIdentity { - private static CachedCertDAO certDAO; + private static CachedCertDAO certDAO; - @Override - public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] _certBytes) throws CertificateException { - byte[] certBytes = _certBytes; - if(cert==null && certBytes==null) { - return null; - } - if(certBytes==null) { - certBytes = cert.getEncoded(); - } - byte[] fingerprint = X509Taf.getFingerPrint(certBytes); + @Override + public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] _certBytes) throws CertificateException { + byte[] certBytes = _certBytes; + if(cert==null && certBytes==null) { + return null; + } + if(certBytes==null) { + certBytes = cert.getEncoded(); + } + byte[] fingerprint = X509Taf.getFingerPrint(certBytes); - AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); - - Result> cresp = certDAO.read(trans, ByteBuffer.wrap(fingerprint)); - if(cresp.isOKhasData()) { - Data cdata = cresp.value.get(0); - return new X509Principal(cdata.id,cert,certBytes,null); - } - return null; - } + AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); + + Result> cresp = certDAO.read(trans, ByteBuffer.wrap(fingerprint)); + if(cresp.isOKhasData()) { + Data cdata = cresp.value.get(0); + return new X509Principal(cdata.id,cert,certBytes,null); + } + return null; + } - public static void set(CachedCertDAO ccd) { - certDAO = ccd; - } + public static void set(CachedCertDAO ccd) { + certDAO = ccd; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java index 3dceb3bf..caededa2 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java @@ -27,33 +27,33 @@ import org.onap.aaf.cadi.LocatorException; import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator; public class DirectLocatorCreator implements AbsAAFLocator.LocatorCreator { - private final AuthzEnv env; - private final LocateDAO locateDAO; - private String myhostname; - private int myport; - - public DirectLocatorCreator(AuthzEnv env, LocateDAO locateDAO) { - this.env = env; - this.locateDAO = locateDAO; - } - - @Override - public AbsAAFLocator create(String key, String version) throws LocatorException { - DirectAAFLocator dal = new DirectAAFLocator(env,locateDAO,key,version); - if(myhostname!=null) { - dal.setSelf(myhostname, myport); - } - return dal; - } - - /** - * Make sure DirectAAFLocator created does not include self. - * @param hostname - * @param port - */ - public void setSelf(String hostname, int port) { - myhostname = hostname; - myport = port; - } + private final AuthzEnv env; + private final LocateDAO locateDAO; + private String myhostname; + private int myport; + + public DirectLocatorCreator(AuthzEnv env, LocateDAO locateDAO) { + this.env = env; + this.locateDAO = locateDAO; + } + + @Override + public AbsAAFLocator create(String key, String version) throws LocatorException { + DirectAAFLocator dal = new DirectAAFLocator(env,locateDAO,key,version); + if(myhostname!=null) { + dal.setSelf(myhostname, myport); + } + return dal; + } + + /** + * Make sure DirectAAFLocator created does not include self. + * @param hostname + * @param port + */ + public void setSelf(String hostname, int port) { + myhostname = hostname; + myport = port; + } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java index 1ddf022c..da7044cf 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java @@ -35,77 +35,77 @@ import org.onap.aaf.cadi.register.Registrant; import org.onap.aaf.cadi.util.Split; public class DirectRegistrar implements Registrant { - private Data locate; - private LocateDAO ldao; - public DirectRegistrar(Access access, LocateDAO ldao, String name, String version, int port) throws CadiException { - this.ldao = ldao; - locate = new LocateDAO.Data(); - locate.name = name; - locate.port = port; - - try { - String latitude = access.getProperty(Config.CADI_LATITUDE, null); - if(latitude==null) { - latitude = access.getProperty("AFT_LATITUDE", null); - } - String longitude = access.getProperty(Config.CADI_LONGITUDE, null); - if(longitude==null) { - longitude = access.getProperty("AFT_LONGITUDE", null); - } - if(latitude==null || longitude==null) { - throw new CadiException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " is required"); - } else { - locate.latitude = Float.parseFloat(latitude); - locate.longitude = Float.parseFloat(longitude); - } - String split[] = Split.splitTrim('.', version); - locate.pkg = split.length>3?Integer.parseInt(split[3]):0; - locate.patch = split.length>2?Integer.parseInt(split[2]):0; - locate.minor = split.length>1?Integer.parseInt(split[1]):0; - locate.major = split.length>0?Integer.parseInt(split[0]):0; - locate.hostname = access.getProperty(Config.AAF_REGISTER_AS, null); - if(locate.hostname==null) { - locate.hostname = access.getProperty(Config.HOSTNAME, null); - } - if(locate.hostname==null) { - locate.hostname = Inet4Address.getLocalHost().getHostName(); - } - String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); - if(subprotocols==null) { - locate.protocol="http"; - } else { - locate.protocol="https"; - for(String s : Split.split(',', subprotocols)) { - locate.subprotocol(true).add(s); - } - } - } catch (NumberFormatException | UnknownHostException e) { - throw new CadiException("Error extracting Data from Properties for Registrar",e); - } - } - - @Override - public Result update(AuthzEnv env) { - org.onap.aaf.auth.layer.Result dr = ldao.update(env.newTransNoAvg(), locate); - if(dr.isOK()) { - return Result.ok(200, null); - } else { - return Result.err(503, dr.errorString()); - } - } + private Data locate; + private LocateDAO ldao; + public DirectRegistrar(Access access, LocateDAO ldao, String name, String version, int port) throws CadiException { + this.ldao = ldao; + locate = new LocateDAO.Data(); + locate.name = name; + locate.port = port; + + try { + String latitude = access.getProperty(Config.CADI_LATITUDE, null); + if(latitude==null) { + latitude = access.getProperty("AFT_LATITUDE", null); + } + String longitude = access.getProperty(Config.CADI_LONGITUDE, null); + if(longitude==null) { + longitude = access.getProperty("AFT_LONGITUDE", null); + } + if(latitude==null || longitude==null) { + throw new CadiException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " is required"); + } else { + locate.latitude = Float.parseFloat(latitude); + locate.longitude = Float.parseFloat(longitude); + } + String split[] = Split.splitTrim('.', version); + locate.pkg = split.length>3?Integer.parseInt(split[3]):0; + locate.patch = split.length>2?Integer.parseInt(split[2]):0; + locate.minor = split.length>1?Integer.parseInt(split[1]):0; + locate.major = split.length>0?Integer.parseInt(split[0]):0; + locate.hostname = access.getProperty(Config.AAF_REGISTER_AS, null); + if(locate.hostname==null) { + locate.hostname = access.getProperty(Config.HOSTNAME, null); + } + if(locate.hostname==null) { + locate.hostname = Inet4Address.getLocalHost().getHostName(); + } + String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); + if(subprotocols==null) { + locate.protocol="http"; + } else { + locate.protocol="https"; + for(String s : Split.split(',', subprotocols)) { + locate.subprotocol(true).add(s); + } + } + } catch (NumberFormatException | UnknownHostException e) { + throw new CadiException("Error extracting Data from Properties for Registrar",e); + } + } + + @Override + public Result update(AuthzEnv env) { + org.onap.aaf.auth.layer.Result dr = ldao.update(env.newTransNoAvg(), locate); + if(dr.isOK()) { + return Result.ok(200, null); + } else { + return Result.err(503, dr.errorString()); + } + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.server.Registrant#cancel(org.onap.aaf.auth.env.test.AuthzEnv) - */ - @Override - public Result cancel(AuthzEnv env) { - org.onap.aaf.auth.layer.Result dr = ldao.delete(env.newTransNoAvg(), locate, false); - if(dr.isOK()) { - return Result.ok(200, null); - } else { - return Result.err(503, dr.errorString()); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.server.Registrant#cancel(org.onap.aaf.auth.env.test.AuthzEnv) + */ + @Override + public Result cancel(AuthzEnv env) { + org.onap.aaf.auth.layer.Result dr = ldao.delete(env.newTransNoAvg(), locate, false); + if(dr.isOK()) { + return Result.ok(200, null); + } else { + return Result.err(503, dr.errorString()); + } - } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java index 31a93723..47723e6b 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java @@ -50,91 +50,91 @@ import org.onap.aaf.misc.env.Trans; // @RunWith(PowerMockRunner.class) public class JU_Cached { - @Mock - CIDAO ciDaoMock; + @Mock + CIDAO ciDaoMock; - @Mock - AuthzEnv authzEnvMock; + @Mock + AuthzEnv authzEnvMock; - @Mock - CIDAO cidaoATMock; - - String name = "nameString"; + @Mock + CIDAO cidaoATMock; + + String name = "nameString"; - @Before - public void setUp(){ - MockitoAnnotations.initMocks(this); - } - - @Test - public void testCachedIdx(){ - Cached cached = new Cached(ciDaoMock, name, 1, 30000L); - assertThat(cached.cacheIdx("1234567890"), is(0)); - } - - @Test - public void testInvalidate(){ - Cached cached = new Cached(ciDaoMock, name, 5, 30000L); - cached.add("test", new ArrayList<>()); - cached.invalidate("test"); - cached.invalidate("test1"); - } - - @SuppressWarnings("static-access") - @Test - public void testStopTimer(){ - Cached cached = new Cached(ciDaoMock, name, 1, 30000L); - cached.stopTimer(); - assertTrue(true); - } + @Before + public void setUp(){ + MockitoAnnotations.initMocks(this); + } + + @Test + public void testCachedIdx(){ + Cached cached = new Cached(ciDaoMock, name, 1, 30000L); + assertThat(cached.cacheIdx("1234567890"), is(0)); + } + + @Test + public void testInvalidate(){ + Cached cached = new Cached(ciDaoMock, name, 5, 30000L); + cached.add("test", new ArrayList<>()); + cached.invalidate("test"); + cached.invalidate("test1"); + } + + @SuppressWarnings("static-access") + @Test + public void testStopTimer(){ + Cached cached = new Cached(ciDaoMock, name, 1, 30000L); + cached.stopTimer(); + assertTrue(true); + } - @SuppressWarnings("static-access") - @Test - public void testStartRefresh(){ - Cached cached = new Cached(ciDaoMock, name, 1, 30000L); - cached.startRefresh(authzEnvMock, cidaoATMock); - assertTrue(true); - } -// @Mock -// Trans transMock; -// @Mock -// Getter getterMock; -// -// @Test -// public void testGet(){ -// cached.get(transMock, name, getterMock); -// fail("not implemented"); -// } -// -// @SuppressWarnings("unchecked") -// public Result> get(TRANS trans, String key, Getter getter) { -// List ld = null; -// Result> rld = null; -// -// int cacheIdx = cacheIdx(key); -// Map map = ((Map)cache[cacheIdx]); -// -// // Check for saved element in cache -// Dated cached = map.get(key); -// // Note: These Segment Timestamps are kept up to date with DB -// Date dbStamp = info.get(trans, name,cacheIdx); -// -// // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax) -// if(cached!=null && dbStamp.before(cached.timestamp)) { -// ld = (List)cached.data; -// rld = Result.ok(ld); -// } else { -// rld = getter.get(); -// if(rld.isOK()) { // only store valid lists -// map.put(key, new Dated(rld.value)); // successful item found gets put in cache -//// } else if(rld.status == Result.ERR_Backend){ -//// map.remove(key); -// } -// } -// return rld; -// } + @SuppressWarnings("static-access") + @Test + public void testStartRefresh(){ + Cached cached = new Cached(ciDaoMock, name, 1, 30000L); + cached.startRefresh(authzEnvMock, cidaoATMock); + assertTrue(true); + } +// @Mock +// Trans transMock; +// @Mock +// Getter getterMock; +// +// @Test +// public void testGet(){ +// cached.get(transMock, name, getterMock); +// fail("not implemented"); +// } +// +// @SuppressWarnings("unchecked") +// public Result> get(TRANS trans, String key, Getter getter) { +// List ld = null; +// Result> rld = null; +// +// int cacheIdx = cacheIdx(key); +// Map map = ((Map)cache[cacheIdx]); +// +// // Check for saved element in cache +// Dated cached = map.get(key); +// // Note: These Segment Timestamps are kept up to date with DB +// Date dbStamp = info.get(trans, name,cacheIdx); +// +// // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax) +// if(cached!=null && dbStamp.before(cached.timestamp)) { +// ld = (List)cached.data; +// rld = Result.ok(ld); +// } else { +// rld = getter.get(); +// if(rld.isOK()) { // only store valid lists +// map.put(key, new Dated(rld.value)); // successful item found gets put in cache +//// } else if(rld.status == Result.ERR_Backend){ +//// map.remove(key); +// } +// } +// return rld; +// } - class DataStub extends CacheableData { - @Override public int[] invalidate(Cached cache) { return null; } - } + class DataStub extends CacheableData { + @Override public int[] invalidate(Cached cache) { return null; } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CachedDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CachedDAO.java index 14612a1f..8ffc5c2f 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CachedDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CachedDAO.java @@ -39,26 +39,26 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_CachedDAO { - CachedDAO cachedDAO; - @Mock - DAO daoMock; - @Mock - CIDAO ciDAOMock; - int segsize=1; - Object[ ] objs = new Object[2]; - - @Before - public void setUp(){ - objs[0] = "helo"; - objs[1] = "polo"; - cachedDAO = new CachedDAO(daoMock, ciDAOMock, segsize, segsize); - } - - @Test - public void testKeyFromObjs(){ - String result = cachedDAO.keyFromObjs(objs); - System.out.println("value of resut " +result); - assertTrue(true); - } - + CachedDAO cachedDAO; + @Mock + DAO daoMock; + @Mock + CIDAO ciDAOMock; + int segsize=1; + Object[ ] objs = new Object[2]; + + @Before + public void setUp(){ + objs[0] = "helo"; + objs[1] = "polo"; + cachedDAO = new CachedDAO(daoMock, ciDAOMock, segsize, segsize); + } + + @Test + public void testKeyFromObjs(){ + String result = cachedDAO.keyFromObjs(objs); + System.out.println("value of resut " +result); + assertTrue(true); + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassAccess.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassAccess.java index 525450a6..722011b0 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassAccess.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassAccess.java @@ -41,33 +41,33 @@ import com.datastax.driver.core.Cluster.Builder; @RunWith(PowerMockRunner.class) public class JU_CassAccess { - CassAccess cassAccess; - - public static final String KEYSPACE = "authz"; - public static final String CASSANDRA_CLUSTERS = "cassandra.clusters"; - public static final String CASSANDRA_CLUSTERS_PORT = "cassandra.clusters.port"; - public static final String CASSANDRA_CLUSTERS_USER_NAME = "cassandra.clusters.user"; - public static final String CASSANDRA_CLUSTERS_PASSWORD = "cassandra.clusters.password"; - public static final String CASSANDRA_RESET_EXCEPTIONS = "cassandra.reset.exceptions"; - public static final String LATITUDE = "LATITUDE"; - public static final String LONGITUDE = "LONGITUDE"; - //private static final List resetExceptions = new ArrayList<>(); - public static final String ERR_ACCESS_MSG = "Accessing Backend"; - private static Builder cb = null; - @Mock - Env envMock; - String prefix=null; - - @Before - public void setUp(){ - cassAccess = new CassAccess(); - } + CassAccess cassAccess; + + public static final String KEYSPACE = "authz"; + public static final String CASSANDRA_CLUSTERS = "cassandra.clusters"; + public static final String CASSANDRA_CLUSTERS_PORT = "cassandra.clusters.port"; + public static final String CASSANDRA_CLUSTERS_USER_NAME = "cassandra.clusters.user"; + public static final String CASSANDRA_CLUSTERS_PASSWORD = "cassandra.clusters.password"; + public static final String CASSANDRA_RESET_EXCEPTIONS = "cassandra.reset.exceptions"; + public static final String LATITUDE = "LATITUDE"; + public static final String LONGITUDE = "LONGITUDE"; + //private static final List resetExceptions = new ArrayList<>(); + public static final String ERR_ACCESS_MSG = "Accessing Backend"; + private static Builder cb = null; + @Mock + Env envMock; + String prefix=null; + + @Before + public void setUp(){ + cassAccess = new CassAccess(); + } - @Test(expected=APIException.class) - public void testCluster() throws APIException, IOException { - cassAccess.cluster(envMock, prefix); - - } + @Test(expected=APIException.class) + public void testCluster() throws APIException, IOException { + cassAccess.cluster(envMock, prefix); + + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassDAOImpl.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassDAOImpl.java index d06e38f7..b5749747 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassDAOImpl.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_CassDAOImpl.java @@ -64,33 +64,33 @@ AuthzTrans authzTransMock; - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Before - public void setUp() - { - String name = "name"; - String keySpace = "keySpace"; - String table = "table"; - cassDAOImpl = new CassDAOImpl(transStoreMock, name, clusterMock, keySpace, classDataMock, table, consistencyLevelMock, consistencyLevelMock); - } + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Before + public void setUp() + { + String name = "name"; + String keySpace = "keySpace"; + String table = "table"; + cassDAOImpl = new CassDAOImpl(transStoreMock, name, clusterMock, keySpace, classDataMock, table, consistencyLevelMock, consistencyLevelMock); + } - //TODO: Gabe [JUnit] Visibility issue - @Test - public void testReadConsistency() { - String table = "users"; - PowerMockito.when(authzTransMock.getProperty(CASS_READ_CONSISTENCY+'.'+table)).thenReturn("TWO"); - ConsistencyLevel consistencyLevel = cassDAOImpl.readConsistency(authzTransMock, table); - System.out.println("Consistency level" + consistencyLevel.name()); - assertEquals("TWO", consistencyLevel.name()); - } - - @Test - public void testWriteConsistency() { - String table = "users"; - PowerMockito.when(authzTransMock.getProperty(CASS_WRITE_CONSISTENCY+'.'+table)).thenReturn(null); - ConsistencyLevel consistencyLevel = cassDAOImpl.writeConsistency(authzTransMock, table); - System.out.println("Consistency level" + consistencyLevel.name()); - assertEquals("ONE", consistencyLevel.name()); - } - + //TODO: Gabe [JUnit] Visibility issue + @Test + public void testReadConsistency() { + String table = "users"; + PowerMockito.when(authzTransMock.getProperty(CASS_READ_CONSISTENCY+'.'+table)).thenReturn("TWO"); + ConsistencyLevel consistencyLevel = cassDAOImpl.readConsistency(authzTransMock, table); + System.out.println("Consistency level" + consistencyLevel.name()); + assertEquals("TWO", consistencyLevel.name()); + } + + @Test + public void testWriteConsistency() { + String table = "users"; + PowerMockito.when(authzTransMock.getProperty(CASS_WRITE_CONSISTENCY+'.'+table)).thenReturn(null); + ConsistencyLevel consistencyLevel = cassDAOImpl.writeConsistency(authzTransMock, table); + System.out.println("Consistency level" + consistencyLevel.name()); + assertEquals("ONE", consistencyLevel.name()); + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java index 8cfb8520..8cd412d2 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java @@ -34,16 +34,16 @@ import org.powermock.modules.junit4.PowerMockRunner; public class JU_DAOException { DAOException daoException; - //DAOException daoException = new DAOException(); - String message = "message"; - Throwable cause; - @Before - public void setUp(){ - daoException = new DAOException(); - } + //DAOException daoException = new DAOException(); + String message = "message"; + Throwable cause; + @Before + public void setUp(){ + daoException = new DAOException(); + } - @Test - public void test(){ - assertTrue(true); - } + @Test + public void test(){ + assertTrue(true); + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java index 3064de55..331e4c8b 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java @@ -53,148 +53,148 @@ import junit.framework.Assert; * */ public class AbsJUCass { - protected static final String AUTHZ = "authz"; - protected static Cluster cluster; - protected static AuthzEnv env; - protected static int iterations = 0; - protected static float totals=0.0f; - protected static float remote = 0.0f; - protected static float json = 0.0f; - protected static AuthzTrans trans; - protected static boolean details = true; - - @BeforeClass - public static void startup() throws APIException, IOException { - synchronized(AUTHZ) { - if(env==null) { - final String resource = "cadi.properties"; - File f = new File("etc" + resource); - InputStream is=null; - Properties props = new Properties(); - try { - if(f.exists()) { - is = new FileInputStream(f); - } else { - URL rsrc = ClassLoader.getSystemResource(resource); - is = rsrc.openStream(); - } - props.load(is); - } finally { - if(is==null) { - env= new AuthzEnv(); - Assert.fail(resource + " must exist in etc dir, or in Classpath"); - } - is.close(); - } - env = new AuthzEnv(props); - } - } - cluster = CassAccess.cluster(env,"LOCAL"); + protected static final String AUTHZ = "authz"; + protected static Cluster cluster; + protected static AuthzEnv env; + protected static int iterations = 0; + protected static float totals=0.0f; + protected static float remote = 0.0f; + protected static float json = 0.0f; + protected static AuthzTrans trans; + protected static boolean details = true; + + @BeforeClass + public static void startup() throws APIException, IOException { + synchronized(AUTHZ) { + if(env==null) { + final String resource = "cadi.properties"; + File f = new File("etc" + resource); + InputStream is=null; + Properties props = new Properties(); + try { + if(f.exists()) { + is = new FileInputStream(f); + } else { + URL rsrc = ClassLoader.getSystemResource(resource); + is = rsrc.openStream(); + } + props.load(is); + } finally { + if(is==null) { + env= new AuthzEnv(); + Assert.fail(resource + " must exist in etc dir, or in Classpath"); + } + is.close(); + } + env = new AuthzEnv(props); + } + } + cluster = CassAccess.cluster(env,"LOCAL"); - env.info().log("Connecting to Cluster"); - try { - cluster.connect(AUTHZ); - } catch(Exception e) { - cluster=null; - env.error().log(e); - Assert.fail("Not able to connect to DB: " + e.getLocalizedMessage()); - } - env.info().log("Connected"); - - // Load special data here - - // WebPhone - env.setProperty("java.naming.provider.url","ldap://ldap.webphone.att.com:389"); - env.setProperty("com.sun.jndi.ldap.connect.pool","true"); - - iterations = 0; - - } - - @AfterClass - public static void shutdown() { - if(cluster!=null) { - cluster.close(); - cluster = null; - } - } + env.info().log("Connecting to Cluster"); + try { + cluster.connect(AUTHZ); + } catch(Exception e) { + cluster=null; + env.error().log(e); + Assert.fail("Not able to connect to DB: " + e.getLocalizedMessage()); + } + env.info().log("Connected"); + + // Load special data here + + // WebPhone + env.setProperty("java.naming.provider.url","ldap://ldap.webphone.att.com:389"); + env.setProperty("com.sun.jndi.ldap.connect.pool","true"); + + iterations = 0; + + } + + @AfterClass + public static void shutdown() { + if(cluster!=null) { + cluster.close(); + cluster = null; + } + } - @Before - public void newTrans() { - trans = env.newTrans(); - - trans.setProperty(CassDAOImpl.USER_NAME, System.getProperty("user.name")); - } - - @After - public void auditTrail() { - if(totals==0) { // "updateTotals()" was not called... just do one Trans - StringBuilder sb = new StringBuilder(); - Metric metric = trans.auditTrail(4, sb, Env.JSON, Env.REMOTE); - if(details) { - env.info().log( - sb, - "Total time:", - totals += metric.total, - "JSON time: ", - metric.buckets[0], - "REMOTE time: ", - metric.buckets[1] - ); - } else { - totals += metric.total; - } - } - } - - protected void updateTotals() { - Metric metric = trans.auditTrail(0, null, Env.JSON, Env.REMOTE); - totals+=metric.total; - json +=metric.buckets[0]; - remote+=metric.buckets[1]; - } + @Before + public void newTrans() { + trans = env.newTrans(); + + trans.setProperty(CassDAOImpl.USER_NAME, System.getProperty("user.name")); + } + + @After + public void auditTrail() { + if(totals==0) { // "updateTotals()" was not called... just do one Trans + StringBuilder sb = new StringBuilder(); + Metric metric = trans.auditTrail(4, sb, Env.JSON, Env.REMOTE); + if(details) { + env.info().log( + sb, + "Total time:", + totals += metric.total, + "JSON time: ", + metric.buckets[0], + "REMOTE time: ", + metric.buckets[1] + ); + } else { + totals += metric.total; + } + } + } + + protected void updateTotals() { + Metric metric = trans.auditTrail(0, null, Env.JSON, Env.REMOTE); + totals+=metric.total; + json +=metric.buckets[0]; + remote+=metric.buckets[1]; + } - @AfterClass - public static void print() { - float transTime; - if(iterations==0) { - transTime=totals; - } else { - transTime=totals/iterations; - } - env.info().log( - "Total time:", - totals, - "JSON time:", - json, - "REMOTE time:", - remote, - "Iterations:", - iterations, - "Transaction time:", - transTime - ); - } - - /** - * Take a User/Pass and turn into an MD5 Hashed BasicAuth - * - * @param user - * @param pass - * @return - * @throws IOException - * @throws NoSuchAlgorithmException - */ - //TODO: Gabe [JUnit] Issue - public static byte[] userPassToBytes(String user, String pass) - throws IOException, NoSuchAlgorithmException { - // Take the form of BasicAuth, so as to allow any character in Password - // (this is an issue in 1.0) - // Also, it makes it quicker to evaluate Basic Auth direct questions - String ba = Symm.base64url.encode(user + ':' + pass); - // Take MD5 Hash, so that data in DB can't be reversed out. - return Hash.hashMD5(ba.getBytes()); - } + @AfterClass + public static void print() { + float transTime; + if(iterations==0) { + transTime=totals; + } else { + transTime=totals/iterations; + } + env.info().log( + "Total time:", + totals, + "JSON time:", + json, + "REMOTE time:", + remote, + "Iterations:", + iterations, + "Transaction time:", + transTime + ); + } + + /** + * Take a User/Pass and turn into an MD5 Hashed BasicAuth + * + * @param user + * @param pass + * @return + * @throws IOException + * @throws NoSuchAlgorithmException + */ + //TODO: Gabe [JUnit] Issue + public static byte[] userPassToBytes(String user, String pass) + throws IOException, NoSuchAlgorithmException { + // Take the form of BasicAuth, so as to allow any character in Password + // (this is an issue in 1.0) + // Also, it makes it quicker to evaluate Basic Auth direct questions + String ba = Symm.base64url.encode(user + ':' + pass); + // Take MD5 Hash, so that data in DB can't be reversed out. + return Hash.hashMD5(ba.getBytes()); + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java index e316ac7e..4ffa946f 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java @@ -38,228 +38,228 @@ import org.onap.aaf.auth.dao.cass.UserRoleDAO; public class JU_Bytification { - @Test - public void testNS() throws IOException { - - // Normal - NsDAO.Data ns = new NsDAO.Data(); - ns.name = "org.osaaf."; - ns.type = NsType.APP.type; + @Test + public void testNS() throws IOException { + + // Normal + NsDAO.Data ns = new NsDAO.Data(); + ns.name = "org.osaaf."; + ns.type = NsType.APP.type; - ByteBuffer bb = ns.bytify(); - - NsDAO.Data nsr = new NsDAO.Data(); - nsr.reconstitute(bb); - check(ns,nsr); - - // Empty admin -// ns.admin(true).clear(); - bb = ns.bytify(); - nsr = new NsDAO.Data(); - nsr.reconstitute(bb); - check(ns,nsr); - - // Empty responsible -// ns.responsible(true).clear(); - bb = ns.bytify(); - nsr = new NsDAO.Data(); - nsr.reconstitute(bb); - check(ns,nsr); + ByteBuffer bb = ns.bytify(); + + NsDAO.Data nsr = new NsDAO.Data(); + nsr.reconstitute(bb); + check(ns,nsr); + + // Empty admin +// ns.admin(true).clear(); + bb = ns.bytify(); + nsr = new NsDAO.Data(); + nsr.reconstitute(bb); + check(ns,nsr); + + // Empty responsible +// ns.responsible(true).clear(); + bb = ns.bytify(); + nsr = new NsDAO.Data(); + nsr.reconstitute(bb); + check(ns,nsr); - bb = ns.bytify(); - nsr = new NsDAO.Data(); - nsr.reconstitute(bb); - check(ns,nsr); - } - - private void check(NsDAO.Data a, NsDAO.Data b) { - assertEquals(a.name,b.name); - assertEquals(a.type,b.type); -// assertEquals(a.admin.size(),b.admin.size()); - -// for(String s: a.admin) { -// assertTrue(b.admin.contains(s)); -// } -// -// assertEquals(a.responsible.size(),b.responsible.size()); -// for(String s: a.responsible) { -// assertTrue(b.responsible.contains(s)); -// } - } + bb = ns.bytify(); + nsr = new NsDAO.Data(); + nsr.reconstitute(bb); + check(ns,nsr); + } + + private void check(NsDAO.Data a, NsDAO.Data b) { + assertEquals(a.name,b.name); + assertEquals(a.type,b.type); +// assertEquals(a.admin.size(),b.admin.size()); + +// for(String s: a.admin) { +// assertTrue(b.admin.contains(s)); +// } +// +// assertEquals(a.responsible.size(),b.responsible.size()); +// for(String s: a.responsible) { +// assertTrue(b.responsible.contains(s)); +// } + } - @Test - public void testRole() throws IOException { - RoleDAO.Data rd1 = new RoleDAO.Data(); - rd1.ns = "org.osaaf."; - rd1.name = "my.role"; - rd1.perms(true).add("org.osaaf..my.Perm|myInstance|myAction"); - rd1.perms(true).add("org.osaaf..my.Perm|myInstance|myAction2"); + @Test + public void testRole() throws IOException { + RoleDAO.Data rd1 = new RoleDAO.Data(); + rd1.ns = "org.osaaf."; + rd1.name = "my.role"; + rd1.perms(true).add("org.osaaf..my.Perm|myInstance|myAction"); + rd1.perms(true).add("org.osaaf..my.Perm|myInstance|myAction2"); - // Normal - ByteBuffer bb = rd1.bytify(); - RoleDAO.Data rd2 = new RoleDAO.Data(); - rd2.reconstitute(bb); - check(rd1,rd2); - - // Overshoot Buffer - StringBuilder sb = new StringBuilder(300); - sb.append("role|instance|veryLongAction..."); - for(int i=0;i<280;++i) { - sb.append('a'); - } - rd1.perms(true).add(sb.toString()); - bb = rd1.bytify(); - rd2 = new RoleDAO.Data(); - rd2.reconstitute(bb); - check(rd1,rd2); - - // No Perms - rd1.perms.clear(); - - bb = rd1.bytify(); - rd2 = new RoleDAO.Data(); - rd2.reconstitute(bb); - check(rd1,rd2); - - // 1000 Perms - for(int i=0;i<1000;++i) { - rd1.perms(true).add("com|inst|action"+ i); - } + // Normal + ByteBuffer bb = rd1.bytify(); + RoleDAO.Data rd2 = new RoleDAO.Data(); + rd2.reconstitute(bb); + check(rd1,rd2); + + // Overshoot Buffer + StringBuilder sb = new StringBuilder(300); + sb.append("role|instance|veryLongAction..."); + for(int i=0;i<280;++i) { + sb.append('a'); + } + rd1.perms(true).add(sb.toString()); + bb = rd1.bytify(); + rd2 = new RoleDAO.Data(); + rd2.reconstitute(bb); + check(rd1,rd2); + + // No Perms + rd1.perms.clear(); + + bb = rd1.bytify(); + rd2 = new RoleDAO.Data(); + rd2.reconstitute(bb); + check(rd1,rd2); + + // 1000 Perms + for(int i=0;i<1000;++i) { + rd1.perms(true).add("com|inst|action"+ i); + } - bb = rd1.bytify(); - rd2 = new RoleDAO.Data(); - rd2.reconstitute(bb); - check(rd1,rd2); + bb = rd1.bytify(); + rd2 = new RoleDAO.Data(); + rd2.reconstitute(bb); + check(rd1,rd2); - } - - private void check(RoleDAO.Data a, RoleDAO.Data b) { - assertEquals(a.ns,b.ns); - assertEquals(a.name,b.name); - - assertEquals(a.perms.size(),b.perms.size()); - for(String s: a.perms) { - assertTrue(b.perms.contains(s)); - } - } + } + + private void check(RoleDAO.Data a, RoleDAO.Data b) { + assertEquals(a.ns,b.ns); + assertEquals(a.name,b.name); + + assertEquals(a.perms.size(),b.perms.size()); + for(String s: a.perms) { + assertTrue(b.perms.contains(s)); + } + } - @Test - public void testPerm() throws IOException { - PermDAO.Data pd1 = new PermDAO.Data(); - pd1.ns = "org.osaaf."; - pd1.type = "my.perm"; - pd1.instance = "instance"; - pd1.action = "read"; - pd1.roles(true).add("org.osaaf..my.Role"); - pd1.roles(true).add("org.osaaf..my.Role2"); + @Test + public void testPerm() throws IOException { + PermDAO.Data pd1 = new PermDAO.Data(); + pd1.ns = "org.osaaf."; + pd1.type = "my.perm"; + pd1.instance = "instance"; + pd1.action = "read"; + pd1.roles(true).add("org.osaaf..my.Role"); + pd1.roles(true).add("org.osaaf..my.Role2"); - // Normal - ByteBuffer bb = pd1.bytify(); - PermDAO.Data rd2 = new PermDAO.Data(); - rd2.reconstitute(bb); - check(pd1,rd2); - - // No Perms - pd1.roles.clear(); - - bb = pd1.bytify(); - rd2 = new PermDAO.Data(); - rd2.reconstitute(bb); - check(pd1,rd2); - - // 1000 Perms - for(int i=0;i<1000;++i) { - pd1.roles(true).add("org.osaaf..my.Role"+ i); - } + // Normal + ByteBuffer bb = pd1.bytify(); + PermDAO.Data rd2 = new PermDAO.Data(); + rd2.reconstitute(bb); + check(pd1,rd2); + + // No Perms + pd1.roles.clear(); + + bb = pd1.bytify(); + rd2 = new PermDAO.Data(); + rd2.reconstitute(bb); + check(pd1,rd2); + + // 1000 Perms + for(int i=0;i<1000;++i) { + pd1.roles(true).add("org.osaaf..my.Role"+ i); + } - bb = pd1.bytify(); - rd2 = new PermDAO.Data(); - rd2.reconstitute(bb); - check(pd1,rd2); + bb = pd1.bytify(); + rd2 = new PermDAO.Data(); + rd2.reconstitute(bb); + check(pd1,rd2); - } - - private void check(PermDAO.Data a, PermDAO.Data b) { - assertEquals(a.ns,b.ns); - assertEquals(a.type,b.type); - assertEquals(a.instance,b.instance); - assertEquals(a.action,b.action); - - assertEquals(a.roles.size(),b.roles.size()); - for(String s: a.roles) { - assertTrue(b.roles.contains(s)); - } - } + } + + private void check(PermDAO.Data a, PermDAO.Data b) { + assertEquals(a.ns,b.ns); + assertEquals(a.type,b.type); + assertEquals(a.instance,b.instance); + assertEquals(a.action,b.action); + + assertEquals(a.roles.size(),b.roles.size()); + for(String s: a.roles) { + assertTrue(b.roles.contains(s)); + } + } - @Test - public void testUserRole() throws IOException { - UserRoleDAO.Data urd1 = new UserRoleDAO.Data(); - urd1.user = "myname@abc.att.com"; - urd1.role("org.osaaf.","my.role"); - urd1.expires = new Date(); + @Test + public void testUserRole() throws IOException { + UserRoleDAO.Data urd1 = new UserRoleDAO.Data(); + urd1.user = "myname@abc.att.com"; + urd1.role("org.osaaf.","my.role"); + urd1.expires = new Date(); - // Normal - ByteBuffer bb = urd1.bytify(); - UserRoleDAO.Data urd2 = new UserRoleDAO.Data(); - urd2.reconstitute(bb); - check(urd1,urd2); - - // A null - urd1.expires = null; - urd1.role = null; - - bb = urd1.bytify(); - urd2 = new UserRoleDAO.Data(); - urd2.reconstitute(bb); - check(urd1,urd2); - } + // Normal + ByteBuffer bb = urd1.bytify(); + UserRoleDAO.Data urd2 = new UserRoleDAO.Data(); + urd2.reconstitute(bb); + check(urd1,urd2); + + // A null + urd1.expires = null; + urd1.role = null; + + bb = urd1.bytify(); + urd2 = new UserRoleDAO.Data(); + urd2.reconstitute(bb); + check(urd1,urd2); + } - private void check(UserRoleDAO.Data a, UserRoleDAO.Data b) { - assertEquals(a.user,b.user); - assertEquals(a.role,b.role); - assertEquals(a.expires,b.expires); - } + private void check(UserRoleDAO.Data a, UserRoleDAO.Data b) { + assertEquals(a.user,b.user); + assertEquals(a.role,b.role); + assertEquals(a.expires,b.expires); + } - - @Test - public void testCred() throws IOException { - CredDAO.Data cd = new CredDAO.Data(); - cd.id = "m55555@abc.att.com"; - cd.ns = "org.osaaf.abc"; - cd.type = 2; - cd.cred = ByteBuffer.wrap(new byte[]{1,34,5,3,25,0,2,5,3,4}); - cd.expires = new Date(); + + @Test + public void testCred() throws IOException { + CredDAO.Data cd = new CredDAO.Data(); + cd.id = "m55555@abc.att.com"; + cd.ns = "org.osaaf.abc"; + cd.type = 2; + cd.cred = ByteBuffer.wrap(new byte[]{1,34,5,3,25,0,2,5,3,4}); + cd.expires = new Date(); - // Normal - ByteBuffer bb = cd.bytify(); - CredDAO.Data cd2 = new CredDAO.Data(); - cd2.reconstitute(bb); - check(cd,cd2); - - // nulls - cd.expires = null; - cd.cred = null; - - bb = cd.bytify(); - cd2 = new CredDAO.Data(); - cd2.reconstitute(bb); - check(cd,cd2); + // Normal + ByteBuffer bb = cd.bytify(); + CredDAO.Data cd2 = new CredDAO.Data(); + cd2.reconstitute(bb); + check(cd,cd2); + + // nulls + cd.expires = null; + cd.cred = null; + + bb = cd.bytify(); + cd2 = new CredDAO.Data(); + cd2.reconstitute(bb); + check(cd,cd2); - } + } - private void check(CredDAO.Data a, CredDAO.Data b) { - assertEquals(a.id,b.id); - assertEquals(a.ns,b.ns); - assertEquals(a.type,b.type); - if(a.cred==null) { - assertEquals(a.cred,b.cred); - } else { - int l = a.cred.limit(); - assertEquals(l,b.cred.limit()); - for (int i=0;i { - private static final String USER_PERMS = "userPerms"; - private static final Map certAuths = new TreeMap<>(); - public Facade1_0 facade1_0; // this is the default Facade - public Facade1_0 facade1_0_XML; // this is the XML Facade - public Map cacheUser; - public AAFAuthn aafAuthn; - public AAFLurPerm aafLurPerm; - final public Cluster cluster; - public final LocateDAO locateDAO; - - - /** - * Construct AuthzAPI with all the Context Supporting Routes that Authz needs - * - * @param env - * @param si - * @param dm - * @param decryptor - * @throws APIException - */ - public AAF_CM(AuthzEnv env) throws Exception { - super(env.access(),env); - aafLurPerm = aafCon().newLur(); - // Note: If you need both Authn and Authz construct the following: - aafAuthn = aafCon().newAuthn(aafLurPerm); - - String aaf_env = env.getProperty(Config.AAF_ENV); - if(aaf_env==null) { - throw new APIException("aaf_env needs to be set"); - } - - // Initialize Facade for all uses - AuthzTrans trans = env.newTrans(); - - cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); - locateDAO = new LocateDAO(trans,cluster,CassAccess.KEYSPACE); - - // Have AAFLocator object Create DirectLocators for Location needs - AbsAAFLocator.setCreator(new DirectLocatorCreator(env, locateDAO)); - - // Load Supported Certificate Authorities by property - // Note: Some will be dynamic Properties, so we need to look through all - for(Entry es : env.access().getProperties().entrySet()) { - String key = es.getKey().toString(); - if(key.startsWith(CA.CM_CA_PREFIX)) { - int idx = key.indexOf('.'); - if(idx==key.lastIndexOf('.')) { // else it's a regular property - - env.log(Level.INIT, "Loading Certificate Authority Module: " + key.substring(idx+1)); - String[] segs = Split.split(',', env.getProperty(key)); - if(segs.length>0) { - String[][] multiParams = new String[segs.length-1][]; - for(int i=0;i cac = (Class)Class.forName(segs[0]); - Constructor cons = cac.getConstructor(new Class[] { - Access.class,String.class,String.class,String[][].class - }); - Object pinst[] = new Object[4]; - pinst[0]=env; - pinst[1]= key.substring(idx+1); - pinst[2]= aaf_env; - pinst[3] = multiParams; - CA ca = cons.newInstance(pinst); - certAuths.put(ca.getName(),ca); - } - } - } - } - if(certAuths.size()==0) { - throw new APIException("No Certificate Authorities have been configured in CertMan"); - } - - CMService service = new CMService(trans, this); - // note: Service knows how to shutdown Cluster on Shutdown, etc. See Constructor - facade1_0 = FacadeFactory.v1_0(this,trans, service,Data.TYPE.JSON); // Default Facade - facade1_0_XML = FacadeFactory.v1_0(this,trans,service,Data.TYPE.XML); - - - synchronized(env) { - if(cacheUser == null) { - cacheUser = Cache.obtain(USER_PERMS); - Cache.startCleansing(env, USER_PERMS); - } - } - - //////////////////////////////////////////////////////////////////////////// - // APIs - //////////////////////////////////////////////////////////////////////// - API_Cert.init(this); - API_Artifact.init(this); - - StringBuilder sb = new StringBuilder(); - trans.auditTrail(2, sb); - trans.init().log(sb); - } - - public CA getCA(String key) { - return certAuths.get(key); - } - - /** - * Setup XML and JSON implementations for each supported Version type - * - * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties - * to do Versions and Content switches - * - */ - public void route(HttpMethods meth, String path, API api, Code code) throws Exception { - String version = "1.0"; - // Get Correct API Class from Mapper - Class respCls = facade1_0.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); - // setup Application API HTML ContentTypes for JSON and Route - String application = applicationJSON(respCls, version); - route(env,meth,path,code,application,"application/json;version="+version,"*/*"); - - // setup Application API HTML ContentTypes for XML and Route - application = applicationXML(respCls, version); - route(env,meth,path,code.clone(facade1_0_XML),application,"application/xml;version="+version); - - // Add other Supported APIs here as created - } - - public void routeAll(HttpMethods meth, String path, API api, Code code) throws Exception { - route(env,meth,path,code,""); // this will always match - } - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - try { - return new Filter[] { - new AuthzTransFilter(env,aafCon(), - new AAFTrustChecker((Env)env), - additionalTafLurs) - }; - } catch (NumberFormatException e) { - throw new CadiException("Invalid Property information", e); - } - } - - @SuppressWarnings("unchecked") - @Override - public Registrant[] registrants(final int port) throws CadiException, LocatorException { - return new Registrant[] { - new DirectRegistrar(access,locateDAO,app_name,app_version,port) - }; - } - - public void destroy() { - Cache.stopTimer(); - locateDAO.close(env.newTransNoAvg()); - cluster.close(); - } - - public static void main(final String[] args) { - try { - Log4JLogIt logIt = new Log4JLogIt(args, "cm"); - PropAccess propAccess = new PropAccess(logIt,args); - - AAF_CM service = new AAF_CM(new AuthzEnv(propAccess)); - JettyServiceStarter jss = new JettyServiceStarter(service); - jss.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + private static final String USER_PERMS = "userPerms"; + private static final Map certAuths = new TreeMap<>(); + public Facade1_0 facade1_0; // this is the default Facade + public Facade1_0 facade1_0_XML; // this is the XML Facade + public Map cacheUser; + public AAFAuthn aafAuthn; + public AAFLurPerm aafLurPerm; + final public Cluster cluster; + public final LocateDAO locateDAO; + + + /** + * Construct AuthzAPI with all the Context Supporting Routes that Authz needs + * + * @param env + * @param si + * @param dm + * @param decryptor + * @throws APIException + */ + public AAF_CM(AuthzEnv env) throws Exception { + super(env.access(),env); + aafLurPerm = aafCon().newLur(); + // Note: If you need both Authn and Authz construct the following: + aafAuthn = aafCon().newAuthn(aafLurPerm); + + String aaf_env = env.getProperty(Config.AAF_ENV); + if(aaf_env==null) { + throw new APIException("aaf_env needs to be set"); + } + + // Initialize Facade for all uses + AuthzTrans trans = env.newTrans(); + + cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); + locateDAO = new LocateDAO(trans,cluster,CassAccess.KEYSPACE); + + // Have AAFLocator object Create DirectLocators for Location needs + AbsAAFLocator.setCreator(new DirectLocatorCreator(env, locateDAO)); + + // Load Supported Certificate Authorities by property + // Note: Some will be dynamic Properties, so we need to look through all + for(Entry es : env.access().getProperties().entrySet()) { + String key = es.getKey().toString(); + if(key.startsWith(CA.CM_CA_PREFIX)) { + int idx = key.indexOf('.'); + if(idx==key.lastIndexOf('.')) { // else it's a regular property + + env.log(Level.INIT, "Loading Certificate Authority Module: " + key.substring(idx+1)); + String[] segs = Split.split(',', env.getProperty(key)); + if(segs.length>0) { + String[][] multiParams = new String[segs.length-1][]; + for(int i=0;i cac = (Class)Class.forName(segs[0]); + Constructor cons = cac.getConstructor(new Class[] { + Access.class,String.class,String.class,String[][].class + }); + Object pinst[] = new Object[4]; + pinst[0]=env; + pinst[1]= key.substring(idx+1); + pinst[2]= aaf_env; + pinst[3] = multiParams; + CA ca = cons.newInstance(pinst); + certAuths.put(ca.getName(),ca); + } + } + } + } + if(certAuths.size()==0) { + throw new APIException("No Certificate Authorities have been configured in CertMan"); + } + + CMService service = new CMService(trans, this); + // note: Service knows how to shutdown Cluster on Shutdown, etc. See Constructor + facade1_0 = FacadeFactory.v1_0(this,trans, service,Data.TYPE.JSON); // Default Facade + facade1_0_XML = FacadeFactory.v1_0(this,trans,service,Data.TYPE.XML); + + + synchronized(env) { + if(cacheUser == null) { + cacheUser = Cache.obtain(USER_PERMS); + Cache.startCleansing(env, USER_PERMS); + } + } + + //////////////////////////////////////////////////////////////////////////// + // APIs + //////////////////////////////////////////////////////////////////////// + API_Cert.init(this); + API_Artifact.init(this); + + StringBuilder sb = new StringBuilder(); + trans.auditTrail(2, sb); + trans.init().log(sb); + } + + public CA getCA(String key) { + return certAuths.get(key); + } + + /** + * Setup XML and JSON implementations for each supported Version type + * + * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties + * to do Versions and Content switches + * + */ + public void route(HttpMethods meth, String path, API api, Code code) throws Exception { + String version = "1.0"; + // Get Correct API Class from Mapper + Class respCls = facade1_0.mapper().getClass(api); + if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + // setup Application API HTML ContentTypes for JSON and Route + String application = applicationJSON(respCls, version); + route(env,meth,path,code,application,"application/json;version="+version,"*/*"); + + // setup Application API HTML ContentTypes for XML and Route + application = applicationXML(respCls, version); + route(env,meth,path,code.clone(facade1_0_XML),application,"application/xml;version="+version); + + // Add other Supported APIs here as created + } + + public void routeAll(HttpMethods meth, String path, API api, Code code) throws Exception { + route(env,meth,path,code,""); // this will always match + } + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + try { + return new Filter[] { + new AuthzTransFilter(env,aafCon(), + new AAFTrustChecker((Env)env), + additionalTafLurs) + }; + } catch (NumberFormatException e) { + throw new CadiException("Invalid Property information", e); + } + } + + @SuppressWarnings("unchecked") + @Override + public Registrant[] registrants(final int port) throws CadiException, LocatorException { + return new Registrant[] { + new DirectRegistrar(access,locateDAO,app_name,app_version,port) + }; + } + + public void destroy() { + Cache.stopTimer(); + locateDAO.close(env.newTransNoAvg()); + cluster.close(); + } + + public static void main(final String[] args) { + try { + Log4JLogIt logIt = new Log4JLogIt(args, "cm"); + PropAccess propAccess = new PropAccess(logIt,args); + + AAF_CM service = new AAF_CM(new AuthzEnv(propAccess)); + JettyServiceStarter jss = new JettyServiceStarter(service); + jss.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java index 134ad7c5..34f7927e 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java @@ -39,95 +39,95 @@ import org.onap.aaf.auth.rserv.HttpMethods; * */ public class API_Artifact { - private static final String GET_ARTIFACTS = "Get Artifacts"; + private static final String GET_ARTIFACTS = "Get Artifacts"; private static final String CERT_ARTIFACTS = "/cert/artifacts"; - /** - * Normal Init level APIs - * - * @param cmAPI - * @throws Exception - */ - public static void init(final AAF_CM cmAPI) throws Exception { - cmAPI.route(HttpMethods.POST, CERT_ARTIFACTS, API.ARTIFACTS, new Code(cmAPI,"Create Artifacts") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.createArtifacts(trans, req, resp); - if(r.isOK()) { - resp.setStatus(HttpStatus.CREATED_201); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Normal Init level APIs + * + * @param cmAPI + * @throws Exception + */ + public static void init(final AAF_CM cmAPI) throws Exception { + cmAPI.route(HttpMethods.POST, CERT_ARTIFACTS, API.ARTIFACTS, new Code(cmAPI,"Create Artifacts") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.createArtifacts(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,r); + } + } + }); - /** - * Use Query Params to get Artifacts by Machine or MechID - */ - cmAPI.route(HttpMethods.GET, CERT_ARTIFACTS, API.ARTIFACTS, new Code(cmAPI,GET_ARTIFACTS) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.readArtifacts(trans, req, resp); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Use Query Params to get Artifacts by Machine or MechID + */ + cmAPI.route(HttpMethods.GET, CERT_ARTIFACTS, API.ARTIFACTS, new Code(cmAPI,GET_ARTIFACTS) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.readArtifacts(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - cmAPI.route(HttpMethods.GET, "/cert/artifacts/:mechid/:machine", API.ARTIFACTS, new Code(cmAPI,GET_ARTIFACTS) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - Result r = context.readArtifacts(trans, resp, pathParam(req,":mechid"), pathParam(req,":machine")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); - - - cmAPI.route(HttpMethods.PUT, CERT_ARTIFACTS, API.ARTIFACTS, new Code(cmAPI,"Update Artifacts") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.updateArtifacts(trans, req, resp); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + cmAPI.route(HttpMethods.GET, "/cert/artifacts/:mechid/:machine", API.ARTIFACTS, new Code(cmAPI,GET_ARTIFACTS) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + + Result r = context.readArtifacts(trans, resp, pathParam(req,":mechid"), pathParam(req,":machine")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + + cmAPI.route(HttpMethods.PUT, CERT_ARTIFACTS, API.ARTIFACTS, new Code(cmAPI,"Update Artifacts") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.updateArtifacts(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - cmAPI.route(HttpMethods.DELETE, "/cert/artifacts/:mechid/:machine", API.VOID, new Code(cmAPI,"Delete Artifacts") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.deleteArtifacts(trans, resp, - pathParam(req, ":mechid"), pathParam(req,":machine")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); - + cmAPI.route(HttpMethods.DELETE, "/cert/artifacts/:mechid/:machine", API.VOID, new Code(cmAPI,"Delete Artifacts") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.deleteArtifacts(trans, resp, + pathParam(req, ":mechid"), pathParam(req,":machine")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + - cmAPI.route(HttpMethods.DELETE, CERT_ARTIFACTS, API.VOID, new Code(cmAPI,"Delete Artifacts") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.deleteArtifacts(trans, req, resp); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); - + cmAPI.route(HttpMethods.DELETE, CERT_ARTIFACTS, API.VOID, new Code(cmAPI,"Delete Artifacts") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.deleteArtifacts(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + - } + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java index 0cea9c73..625fed62 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java @@ -41,102 +41,102 @@ import org.onap.aaf.misc.env.Slot; * */ public class API_Cert { - public static final String CERT_AUTH = "CertAuthority"; - private static Slot sCertAuth; + public static final String CERT_AUTH = "CertAuthority"; + private static Slot sCertAuth; - /** - * Normal Init level APIs - * - * @param aafCM - * @param facade - * @throws Exception - */ - public static void init(final AAF_CM aafCM) throws Exception { - // Check for Created Certificate Authorities in TRANS - sCertAuth = aafCM.env.slot(CERT_AUTH); - - //////// - // Overall APIs - /////// - aafCM.route(HttpMethods.PUT,"/cert/:ca",API.CERT_REQ,new Code(aafCM,"Request Certificate") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String key = pathParam(req, ":ca"); - CA ca; - if((ca = aafCM.getCA(key))==null) { - context.error(trans,resp,Result.ERR_BadData,"CA %s is not supported",key); - } else { - trans.put(sCertAuth, ca); - Result r = context.requestCert(trans, req, resp, ca); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - } - }); - - aafCM.route(HttpMethods.GET,"/cert/:ca/personal",API.CERT,new Code(aafCM,"Request Personal Certificate") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String key = pathParam(req, ":ca"); - CA ca; - if((ca = aafCM.getCA(key))==null) { - context.error(trans,resp,Result.ERR_BadData,"CA %s is not supported",key); - } else { - trans.put(sCertAuth, ca); - Result r = context.requestPersonalCert(trans, req, resp, ca); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - } - }); + /** + * Normal Init level APIs + * + * @param aafCM + * @param facade + * @throws Exception + */ + public static void init(final AAF_CM aafCM) throws Exception { + // Check for Created Certificate Authorities in TRANS + sCertAuth = aafCM.env.slot(CERT_AUTH); + + //////// + // Overall APIs + /////// + aafCM.route(HttpMethods.PUT,"/cert/:ca",API.CERT_REQ,new Code(aafCM,"Request Certificate") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String key = pathParam(req, ":ca"); + CA ca; + if((ca = aafCM.getCA(key))==null) { + context.error(trans,resp,Result.ERR_BadData,"CA %s is not supported",key); + } else { + trans.put(sCertAuth, ca); + Result r = context.requestCert(trans, req, resp, ca); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + } + }); + + aafCM.route(HttpMethods.GET,"/cert/:ca/personal",API.CERT,new Code(aafCM,"Request Personal Certificate") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String key = pathParam(req, ":ca"); + CA ca; + if((ca = aafCM.getCA(key))==null) { + context.error(trans,resp,Result.ERR_BadData,"CA %s is not supported",key); + } else { + trans.put(sCertAuth, ca); + Result r = context.requestPersonalCert(trans, req, resp, ca); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + } + }); - - /** - * - */ - aafCM.route(HttpMethods.GET, "/cert/may/:perm", API.VOID, new Code(aafCM,"Check Permission") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.check(trans, resp, pathParam(req,"perm")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - trans.checkpoint(r.errorString()); - context.error(trans,resp,Result.err(Result.ERR_Denied,"%s does not have Permission.",trans.user())); - } - } - }); + + /** + * + */ + aafCM.route(HttpMethods.GET, "/cert/may/:perm", API.VOID, new Code(aafCM,"Check Permission") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.check(trans, resp, pathParam(req,"perm")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + trans.checkpoint(r.errorString()); + context.error(trans,resp,Result.err(Result.ERR_Denied,"%s does not have Permission.",trans.user())); + } + } + }); - /** - * Get Cert by ID and Machine - */ + /** + * Get Cert by ID and Machine + */ - - /** - * Get Certs by ID - */ - aafCM.route(HttpMethods.GET, "/cert/id/:id", API.CERT, new Code(aafCM,"GetByID") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.readCertsByMechID(trans, resp, pathParam(req,"id")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + + /** + * Get Certs by ID + */ + aafCM.route(HttpMethods.GET, "/cert/id/:id", API.CERT, new Code(aafCM,"GetByID") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.readCertsByMechID(trans, resp, pathParam(req,"id")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - - /** - * Get Certs by Machine - */ - - } + + /** + * Get Certs by Machine + */ + + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java index f1f70a7e..820f02d1 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java @@ -42,198 +42,198 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.env.util.Split; public abstract class CA { - private static final String MUST_EXIST_TO_CREATE_CSRS_FOR = " must exist to create CSRs for "; - //TODO figuring out what is an Issuing CA is a matter of convention. Consider SubClassing for Open Source - public static final String ISSUING_CA = "Issuing CA"; - public static final String CM_CA_PREFIX = "cm_ca."; - public static final String CM_CA_BASE_SUBJECT = ".baseSubject"; - protected static final String CM_PUBLIC_DIR = "cm_public_dir"; - private static final String CM_TRUST_CAS = "cm_trust_cas"; - protected static final String CM_BACKUP_CAS = "cm_backup_cas"; + private static final String MUST_EXIST_TO_CREATE_CSRS_FOR = " must exist to create CSRs for "; + //TODO figuring out what is an Issuing CA is a matter of convention. Consider SubClassing for Open Source + public static final String ISSUING_CA = "Issuing CA"; + public static final String CM_CA_PREFIX = "cm_ca."; + public static final String CM_CA_BASE_SUBJECT = ".baseSubject"; + protected static final String CM_PUBLIC_DIR = "cm_public_dir"; + private static final String CM_TRUST_CAS = "cm_trust_cas"; + protected static final String CM_BACKUP_CAS = "cm_backup_cas"; - public static final Set EMPTY = Collections.unmodifiableSet(new HashSet<>()); + public static final Set EMPTY = Collections.unmodifiableSet(new HashSet<>()); - - private final String name; - private final String env; - private MessageDigest messageDigest; - private final String permNS; - private final String permType; - private final ArrayList idDomains; - private String[] trustedCAs; - private String[] caIssuerDNs; - private List rdns; + + private final String name; + private final String env; + private MessageDigest messageDigest; + private final String permNS; + private final String permType; + private final ArrayList idDomains; + private String[] trustedCAs; + private String[] caIssuerDNs; + private List rdns; - protected CA(Access access, String caName, String env) throws IOException, CertException { - trustedCAs = new String[4]; // starting array - this.name = caName; - this.env = env; - permNS = CM_CA_PREFIX + name; - permType = access.getProperty(permNS + ".perm_type",null); - if(permType==null) { - throw new CertException(permNS + ".perm_type" + MUST_EXIST_TO_CREATE_CSRS_FOR + caName); - } - caIssuerDNs = Split.splitTrim(':', access.getProperty(Config.CADI_X509_ISSUERS, null)); - - String tag = CA.CM_CA_PREFIX+caName+CA.CM_CA_BASE_SUBJECT; - - String fields = access.getProperty(tag, null); - if(fields==null) { - throw new CertException(tag + MUST_EXIST_TO_CREATE_CSRS_FOR + caName); - } - access.log(Level.INFO, tag, "=",fields); - rdns = RDN.parse('/',fields); - for(RDN rdn : rdns) { - if(rdn.aoi==BCStyle.EmailAddress) { // Cert Specs say Emails belong in Subject - throw new CertException("email address is not allowed in " + CM_CA_BASE_SUBJECT); - } - } - - idDomains = new ArrayList<>(); - StringBuilder sb = null; - for(String s : Split.splitTrim(',', access.getProperty(CA.CM_CA_PREFIX+caName+".idDomains", ""))) { - if(s.length()>0) { - if(sb==null) { - sb = new StringBuilder(); - } else { - sb.append(", "); - } - idDomains.add(s); - sb.append(s); - } - } - if(sb!=null) { - access.printf(Level.INIT, "CA '%s' supports Personal Certificates for %s", caName, sb); - } - - String dataDir = access.getProperty(CM_PUBLIC_DIR,null); - if(dataDir!=null) { - File data = new File(dataDir); - byte[] bytes; - if(data.exists()) { - String trustCas = access.getProperty(CM_TRUST_CAS,null); - if(trustCas!=null) { - for(String fname : Split.splitTrim(',', trustCas)) { - File crt; - if(fname.contains("/")) { - crt = new File(fname); - } else { - crt = new File(data,fname); - } - if(crt.exists()) { - access.printf(Level.INIT, "Loading CA Cert from %s", crt.getAbsolutePath()); - bytes = new byte[(int)crt.length()]; - FileInputStream fis = new FileInputStream(crt); - try { - int read = fis.read(bytes); - if(read>0) { - addTrustedCA(new String(bytes)); - } - } finally { - fis.close(); - } - } else { - access.printf(Level.INIT, "FAILED to Load CA Cert from %s", crt.getAbsolutePath()); - } - } - } else { - access.printf(Level.INIT, "Cannot load external TRUST CAs: No property %s",CM_TRUST_CAS); - } - } else { - access.printf(Level.INIT, "Cannot load external TRUST CAs: %s doesn't exist, or is not accessible",data.getAbsolutePath()); - } - } - } + protected CA(Access access, String caName, String env) throws IOException, CertException { + trustedCAs = new String[4]; // starting array + this.name = caName; + this.env = env; + permNS = CM_CA_PREFIX + name; + permType = access.getProperty(permNS + ".perm_type",null); + if(permType==null) { + throw new CertException(permNS + ".perm_type" + MUST_EXIST_TO_CREATE_CSRS_FOR + caName); + } + caIssuerDNs = Split.splitTrim(':', access.getProperty(Config.CADI_X509_ISSUERS, null)); + + String tag = CA.CM_CA_PREFIX+caName+CA.CM_CA_BASE_SUBJECT; + + String fields = access.getProperty(tag, null); + if(fields==null) { + throw new CertException(tag + MUST_EXIST_TO_CREATE_CSRS_FOR + caName); + } + access.log(Level.INFO, tag, "=",fields); + rdns = RDN.parse('/',fields); + for(RDN rdn : rdns) { + if(rdn.aoi==BCStyle.EmailAddress) { // Cert Specs say Emails belong in Subject + throw new CertException("email address is not allowed in " + CM_CA_BASE_SUBJECT); + } + } + + idDomains = new ArrayList<>(); + StringBuilder sb = null; + for(String s : Split.splitTrim(',', access.getProperty(CA.CM_CA_PREFIX+caName+".idDomains", ""))) { + if(s.length()>0) { + if(sb==null) { + sb = new StringBuilder(); + } else { + sb.append(", "); + } + idDomains.add(s); + sb.append(s); + } + } + if(sb!=null) { + access.printf(Level.INIT, "CA '%s' supports Personal Certificates for %s", caName, sb); + } + + String dataDir = access.getProperty(CM_PUBLIC_DIR,null); + if(dataDir!=null) { + File data = new File(dataDir); + byte[] bytes; + if(data.exists()) { + String trustCas = access.getProperty(CM_TRUST_CAS,null); + if(trustCas!=null) { + for(String fname : Split.splitTrim(',', trustCas)) { + File crt; + if(fname.contains("/")) { + crt = new File(fname); + } else { + crt = new File(data,fname); + } + if(crt.exists()) { + access.printf(Level.INIT, "Loading CA Cert from %s", crt.getAbsolutePath()); + bytes = new byte[(int)crt.length()]; + FileInputStream fis = new FileInputStream(crt); + try { + int read = fis.read(bytes); + if(read>0) { + addTrustedCA(new String(bytes)); + } + } finally { + fis.close(); + } + } else { + access.printf(Level.INIT, "FAILED to Load CA Cert from %s", crt.getAbsolutePath()); + } + } + } else { + access.printf(Level.INIT, "Cannot load external TRUST CAs: No property %s",CM_TRUST_CAS); + } + } else { + access.printf(Level.INIT, "Cannot load external TRUST CAs: %s doesn't exist, or is not accessible",data.getAbsolutePath()); + } + } + } - protected void addCaIssuerDN(String issuerDN) { - boolean changed = true; - for(String id : caIssuerDNs) { - if(id.equals(issuerDN)) { - changed = false; - break; - } - } - if(changed) { - String[] newsa = new String[caIssuerDNs.length+1]; - newsa[0]=issuerDN; - System.arraycopy(caIssuerDNs, 0, newsa, 1, caIssuerDNs.length); - caIssuerDNs = newsa; - } - } - - protected synchronized void addTrustedCA(final String crtString) { - String crt; - if(crtString.endsWith("\n")) { - crt = crtString; - } else { - crt = crtString + '\n'; - } - for(int i=0;i=0) { - return idDomains.contains(p.getName().substring(at+1)); - } else { - return false; - } - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.ca.CA#inPersonalDomains(java.security.Principal) + */ + public boolean inPersonalDomains(Principal p) { + int at = p.getName().indexOf('@'); + if(at>=0) { + return idDomains.contains(p.getName().substring(at+1)); + } else { + return false; + } + } - public MessageDigest messageDigest() { - return messageDigest; - } + public MessageDigest messageDigest() { + return messageDigest; + } - public CSRMeta newCSRMeta() { - return new CSRMeta(rdns); - } + public CSRMeta newCSRMeta() { + return new CSRMeta(rdns); + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java index 3f398381..000b6dd5 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java @@ -56,203 +56,203 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.env.util.Split; public class JscepCA extends CA { - static final String CA_PREFIX = "http://"; - static final String CA_POSTFIX="/certsrv/mscep_admin/mscep.dll"; + static final String CA_PREFIX = "http://"; + static final String CA_POSTFIX="/certsrv/mscep_admin/mscep.dll"; - private static final String MS_PROFILE="1"; - private static final int MAX_RETRY=3; - public static final long INVALIDATE_TIME = 1000*60*10L; // 10 mins + private static final String MS_PROFILE="1"; + private static final int MAX_RETRY=3; + public static final long INVALIDATE_TIME = 1000*60*10L; // 10 mins - // package on purpose - private Map mxcwiS; - private Map mxcwiC; + // package on purpose + private Map mxcwiS; + private Map mxcwiC; - private JscepClientLocator clients; + private JscepClientLocator clients; - public JscepCA(final Access access, final String name, final String env, String [][] params) throws IOException, CertException, LocatorException { - super(access, name, env); - mxcwiS = new ConcurrentHashMap<>(); - mxcwiC = new ConcurrentHashMap<>(); - - if(params.length<2) { - throw new CertException("No Trust Chain parameters are included"); - } - if(params[0].length<2) { - throw new CertException("User/Password required for JSCEP"); - } - final String id = params[0][0]; - final String pw = params[0][1]; - - // Set this for NTLM password Microsoft - Authenticator.setDefault(new Authenticator() { - public PasswordAuthentication getPasswordAuthentication () { - try { - return new PasswordAuthentication (id,access.decrypt(pw,true).toCharArray()); - } catch (IOException e) { - access.log(e); - } - return null; - } - }); - - StringBuilder urlstr = new StringBuilder(); + public JscepCA(final Access access, final String name, final String env, String [][] params) throws IOException, CertException, LocatorException { + super(access, name, env); + mxcwiS = new ConcurrentHashMap<>(); + mxcwiC = new ConcurrentHashMap<>(); + + if(params.length<2) { + throw new CertException("No Trust Chain parameters are included"); + } + if(params[0].length<2) { + throw new CertException("User/Password required for JSCEP"); + } + final String id = params[0][0]; + final String pw = params[0][1]; + + // Set this for NTLM password Microsoft + Authenticator.setDefault(new Authenticator() { + public PasswordAuthentication getPasswordAuthentication () { + try { + return new PasswordAuthentication (id,access.decrypt(pw,true).toCharArray()); + } catch (IOException e) { + access.log(e); + } + return null; + } + }); + + StringBuilder urlstr = new StringBuilder(); - for(int i=1;i1) { - urlstr.append(','); // delimiter - } - urlstr.append(params[i][0]); - - String dir = access.getProperty(CM_PUBLIC_DIR, ""); - if(!"".equals(dir) && !dir.endsWith("/")) { - dir = dir + '/'; - } - String path; - List frs = new ArrayList<>(params.length-1); - try { - for(int j=1; j1) { + urlstr.append(','); // delimiter + } + urlstr.append(params[i][0]); + + String dir = access.getProperty(CM_PUBLIC_DIR, ""); + if(!"".equals(dir) && !dir.endsWith("/")) { + dir = dir + '/'; + } + String path; + List frs = new ArrayList<>(params.length-1); + try { + for(int j=1; j { + } else if (er.isPending()) { + trans.checkpoint("Polling, waiting on CA to complete"); + Thread.sleep(3000); + } else if (er.isFailure()) { + throw new CertException(clients.info(item)+':'+er.getFailInfo().toString()); + } + } + } catch(LocatorException e) { + trans.error().log(e); + i=MAX_RETRY; + } catch (ClientException e) { + trans.error().log(e,"SCEP Client Error, Temporarily Invalidating Client: " + clients.info(item)); + try { + clients.invalidate(client); + if(!clients.hasItems()) { + clients.refresh(); + } + } catch (LocatorException e1) { + trans.error().log(e,clients.info(item)); + i=MAX_RETRY; // can't go any further + } + } catch (InterruptedException|TransactionException|CertificateException|OperatorCreationException | CertStoreException e) { + trans.error().log(e); + i=MAX_RETRY; + } finally { + tt.done(); + } + } + + return null; + } + + /** + * Locator specifically for Jscep Clients. + * + * Class based client for access to common Map + */ + private class JscepClientLocator extends HotPeerLocator { - protected JscepClientLocator(Access access, String urlstr)throws LocatorException { - super(access, urlstr, JscepCA.INVALIDATE_TIME, - access.getProperty("cadi_latitude","39.833333"), //Note: Defaulting to GEO center of US - access.getProperty("cadi_longitude","-98.583333") - ); - } + protected JscepClientLocator(Access access, String urlstr)throws LocatorException { + super(access, urlstr, JscepCA.INVALIDATE_TIME, + access.getProperty("cadi_latitude","39.833333"), //Note: Defaulting to GEO center of US + access.getProperty("cadi_longitude","-98.583333") + ); + } - @Override - protected Client _newClient(String urlinfo) throws LocatorException { - try { - String[] info = Split.split('/', urlinfo); - Client c = new Client(new URL(JscepCA.CA_PREFIX + info[0] + JscepCA.CA_POSTFIX), - new CertificateVerifier() { - @Override - public boolean verify(X509Certificate cert) { - //TODO checkIssuer - return true; - } - } - ); - // Map URL to Client, because Client doesn't expose Connection - mxcwiC.put(c, mxcwiS.get(urlinfo)); - return c; - } catch (MalformedURLException e) { - throw new LocatorException(e); - } - } + @Override + protected Client _newClient(String urlinfo) throws LocatorException { + try { + String[] info = Split.split('/', urlinfo); + Client c = new Client(new URL(JscepCA.CA_PREFIX + info[0] + JscepCA.CA_POSTFIX), + new CertificateVerifier() { + @Override + public boolean verify(X509Certificate cert) { + //TODO checkIssuer + return true; + } + } + ); + // Map URL to Client, because Client doesn't expose Connection + mxcwiC.put(c, mxcwiS.get(urlinfo)); + return c; + } catch (MalformedURLException e) { + throw new LocatorException(e); + } + } - @Override - protected Client _invalidate(Client client) { - return null; - } + @Override + protected Client _invalidate(Client client) { + return null; + } - @Override - protected void _destroy(Client client) { - mxcwiC.remove(client); - } - - - } + @Override + protected void _destroy(Client client) { + mxcwiC.remove(client); + } + + + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java index 893e9f32..b7d78f05 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java @@ -73,194 +73,194 @@ import org.onap.aaf.misc.env.Trans; public class LocalCA extends CA { - private final static BigInteger ONE = new BigInteger("1"); - // Extensions - private static final KeyPurposeId[] ASN_WebUsage = new KeyPurposeId[] { - KeyPurposeId.id_kp_serverAuth, // WebServer - KeyPurposeId.id_kp_clientAuth // WebClient - }; - - private final PrivateKey caKey; - private final X500Name issuer; - private final SecureRandom random = new SecureRandom(); - private BigInteger serial; - private final X509ChainWithIssuer x509cwi; // "Cert" is CACert - - - public LocalCA(Access access, final String name, final String env, final String[][] params) throws IOException, CertException { - super(access, name, env); - - serial = new BigInteger(64,random); + private final static BigInteger ONE = new BigInteger("1"); + // Extensions + private static final KeyPurposeId[] ASN_WebUsage = new KeyPurposeId[] { + KeyPurposeId.id_kp_serverAuth, // WebServer + KeyPurposeId.id_kp_clientAuth // WebClient + }; + + private final PrivateKey caKey; + private final X500Name issuer; + private final SecureRandom random = new SecureRandom(); + private BigInteger serial; + private final X509ChainWithIssuer x509cwi; // "Cert" is CACert + + + public LocalCA(Access access, final String name, final String env, final String[][] params) throws IOException, CertException { + super(access, name, env); + + serial = new BigInteger(64,random); - if(params.length<1 || params[0].length<2) { - throw new IOException("LocalCA expects cm_ca.=org.onap.aaf.auth.cm.ca.LocalCA,[;]+"); - } - - // Read in the Private Key - String configured; - File f = new File(params[0][0]); - if(f.exists() && f.isFile()) { - String fileName = f.getName(); - if(fileName.endsWith(".key")) { - caKey = Factory.toPrivateKey(NullTrans.singleton(),f); - List frs = new ArrayList<>(params.length-1); - try { - String dir = access.getProperty(CM_PUBLIC_DIR, ""); - if(!"".equals(dir) && !dir.endsWith("/")) { - dir = dir + '/'; - } + if(params.length<1 || params[0].length<2) { + throw new IOException("LocalCA expects cm_ca.=org.onap.aaf.auth.cm.ca.LocalCA,[;]+"); + } + + // Read in the Private Key + String configured; + File f = new File(params[0][0]); + if(f.exists() && f.isFile()) { + String fileName = f.getName(); + if(fileName.endsWith(".key")) { + caKey = Factory.toPrivateKey(NullTrans.singleton(),f); + List frs = new ArrayList<>(params.length-1); + try { + String dir = access.getProperty(CM_PUBLIC_DIR, ""); + if(!"".equals(dir) && !dir.endsWith("/")) { + dir = dir + '/'; + } - String path; - for(int i=1; i; enc:>"); - } - try { - Provider p; - KeyStore keyStore; - FileInputStream fis = null; - if(fileName.endsWith(".pkcs11")) { - String ksType="PKCS11"; - p = Factory.getSecurityProvider(ksType,params); - keyStore = KeyStore.getInstance(ksType,p); - } else if(fileName.endsWith(".jks")) { - keyStore = KeyStore.getInstance("JKS"); - fis = new FileInputStream(f); - } else if(fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) { - keyStore = KeyStore.getInstance("PKCS12"); - fis = new FileInputStream(f); - } else { - throw new CertException("Unknown Keystore type from filename " + fileName); - } - - KeyStore.ProtectionParameter keyPass; + String path; + for(int i=1; i; enc:>"); + } + try { + Provider p; + KeyStore keyStore; + FileInputStream fis = null; + if(fileName.endsWith(".pkcs11")) { + String ksType="PKCS11"; + p = Factory.getSecurityProvider(ksType,params); + keyStore = KeyStore.getInstance(ksType,p); + } else if(fileName.endsWith(".jks")) { + keyStore = KeyStore.getInstance("JKS"); + fis = new FileInputStream(f); + } else if(fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) { + keyStore = KeyStore.getInstance("PKCS12"); + fis = new FileInputStream(f); + } else { + throw new CertException("Unknown Keystore type from filename " + fileName); + } + + KeyStore.ProtectionParameter keyPass; - try { - String pass = access.decrypt(params[0][2]/*encrypted passcode*/, true); - if(pass==null) { - throw new CertException("Passcode for " + fileName + " cannot be decrypted."); - } - char[] ksPass = pass.toCharArray(); - //Assuming Key Pass is same as Keystore Pass - keyPass = new KeyStore.PasswordProtection(ksPass); + try { + String pass = access.decrypt(params[0][2]/*encrypted passcode*/, true); + if(pass==null) { + throw new CertException("Passcode for " + fileName + " cannot be decrypted."); + } + char[] ksPass = pass.toCharArray(); + //Assuming Key Pass is same as Keystore Pass + keyPass = new KeyStore.PasswordProtection(ksPass); - keyStore.load(fis,ksPass); - } finally { - if (fis != null) - fis.close(); - } - Entry entry; - if(fileName.endsWith(".pkcs11")) { - entry = keyStore.getEntry(params[0][1]/*alias*/, null); - } else { - entry = keyStore.getEntry(params[0][1]/*alias*/, keyPass); - } - if(entry==null) { - throw new CertException("There is no Keystore entry with name '" + params[0][1] +'\''); - } - PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry)entry; - caKey = privateKeyEntry.getPrivateKey(); - - x509cwi = new X509ChainWithIssuer(privateKeyEntry.getCertificateChain()); - configured = "keystore \"" + fileName + "\", alias " + params[0][1]; - } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableEntryException e) { - throw new CertException("Exception opening Keystore " + fileName, e); - } - } - } else { - throw new CertException("Private Key, " + f.getPath() + ", does not exist"); - } - - X500NameBuilder xnb = new X500NameBuilder(); - List rp = RDN.parse(',', x509cwi.getIssuerDN()); - Collections.reverse(rp); - for(RDN rnd : rp) { - xnb.addRDN(rnd.aoi,rnd.value); - } - issuer = xnb.build(); - access.printf(Level.INIT, "LocalCA is configured with %s. The Issuer DN is %s.", - configured, issuer.toString()); - } + keyStore.load(fis,ksPass); + } finally { + if (fis != null) + fis.close(); + } + Entry entry; + if(fileName.endsWith(".pkcs11")) { + entry = keyStore.getEntry(params[0][1]/*alias*/, null); + } else { + entry = keyStore.getEntry(params[0][1]/*alias*/, keyPass); + } + if(entry==null) { + throw new CertException("There is no Keystore entry with name '" + params[0][1] +'\''); + } + PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry)entry; + caKey = privateKeyEntry.getPrivateKey(); + + x509cwi = new X509ChainWithIssuer(privateKeyEntry.getCertificateChain()); + configured = "keystore \"" + fileName + "\", alias " + params[0][1]; + } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableEntryException e) { + throw new CertException("Exception opening Keystore " + fileName, e); + } + } + } else { + throw new CertException("Private Key, " + f.getPath() + ", does not exist"); + } + + X500NameBuilder xnb = new X500NameBuilder(); + List rp = RDN.parse(',', x509cwi.getIssuerDN()); + Collections.reverse(rp); + for(RDN rnd : rp) { + xnb.addRDN(rnd.aoi,rnd.value); + } + issuer = xnb.build(); + access.printf(Level.INIT, "LocalCA is configured with %s. The Issuer DN is %s.", + configured, issuer.toString()); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.cm.service.CA#sign(org.bouncycastle.pkcs.PKCS10CertificationRequest) - */ - @Override - public X509andChain sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException { - GregorianCalendar gc = new GregorianCalendar(); - Date start = gc.getTime(); - gc.add(GregorianCalendar.MONTH, 6); - Date end = gc.getTime(); - X509Certificate x509; - TimeTaken tt = trans.start("Create/Sign Cert",Env.SUB); - try { - BigInteger bi; - - synchronized(ONE) { - bi = serial; - serial = serial.add(ONE); - } - - RSAPublicKey rpk = (RSAPublicKey)csrmeta.keypair(trans).getPublic(); - X509v3CertificateBuilder xcb = new X509v3CertificateBuilder( - issuer, - bi, // replace with Serialnumber scheme - start, - end, - csrmeta.x500Name(), - SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new RSAKeyParameters(false,rpk.getModulus(),rpk.getPublicExponent())) -// new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded())) - ); - List lsan = new ArrayList<>(); - for(String s : csrmeta.sans()) { - lsan.add(new GeneralName(GeneralName.dNSName,s)); - } - GeneralName[] sans = new GeneralName[lsan.size()]; - lsan.toArray(sans); + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.service.CA#sign(org.bouncycastle.pkcs.PKCS10CertificationRequest) + */ + @Override + public X509andChain sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException { + GregorianCalendar gc = new GregorianCalendar(); + Date start = gc.getTime(); + gc.add(GregorianCalendar.MONTH, 6); + Date end = gc.getTime(); + X509Certificate x509; + TimeTaken tt = trans.start("Create/Sign Cert",Env.SUB); + try { + BigInteger bi; + + synchronized(ONE) { + bi = serial; + serial = serial.add(ONE); + } + + RSAPublicKey rpk = (RSAPublicKey)csrmeta.keypair(trans).getPublic(); + X509v3CertificateBuilder xcb = new X509v3CertificateBuilder( + issuer, + bi, // replace with Serialnumber scheme + start, + end, + csrmeta.x500Name(), + SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new RSAKeyParameters(false,rpk.getModulus(),rpk.getPublicExponent())) +// new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded())) + ); + List lsan = new ArrayList<>(); + for(String s : csrmeta.sans()) { + lsan.add(new GeneralName(GeneralName.dNSName,s)); + } + GeneralName[] sans = new GeneralName[lsan.size()]; + lsan.toArray(sans); - JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); - xcb.addExtension(Extension.basicConstraints, - false, new BasicConstraints(false - )) - .addExtension(Extension.keyUsage, - true, new KeyUsage(KeyUsage.digitalSignature - | KeyUsage.keyEncipherment - | KeyUsage.nonRepudiation)) - .addExtension(Extension.extendedKeyUsage, - true, new ExtendedKeyUsage(ASN_WebUsage)) + JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); + xcb.addExtension(Extension.basicConstraints, + false, new BasicConstraints(false + )) + .addExtension(Extension.keyUsage, + true, new KeyUsage(KeyUsage.digitalSignature + | KeyUsage.keyEncipherment + | KeyUsage.nonRepudiation)) + .addExtension(Extension.extendedKeyUsage, + true, new ExtendedKeyUsage(ASN_WebUsage)) .addExtension(Extension.authorityKeyIdentifier, - false, extUtils.createAuthorityKeyIdentifier(x509cwi.cert)) + false, extUtils.createAuthorityKeyIdentifier(x509cwi.cert)) .addExtension(Extension.subjectKeyIdentifier, - false, extUtils.createSubjectKeyIdentifier(rpk)) - .addExtension(Extension.subjectAlternativeName, - false, new GeneralNames(sans)) -// .addExtension(MiscObjectIdentifiers.netscape, true, new NetscapeCertType( -// NetscapeCertType.sslClient|NetscapeCertType.sslClient)) - ; - - x509 = new JcaX509CertificateConverter().getCertificate( - xcb.build(BCFactory.contentSigner(caKey))); - } catch (GeneralSecurityException|OperatorCreationException e) { - throw new CertException(e); - } finally { - tt.done(); - } - - return new X509andChain(x509,x509cwi.trustChain); - } + false, extUtils.createSubjectKeyIdentifier(rpk)) + .addExtension(Extension.subjectAlternativeName, + false, new GeneralNames(sans)) +// .addExtension(MiscObjectIdentifiers.netscape, true, new NetscapeCertType( +// NetscapeCertType.sslClient|NetscapeCertType.sslClient)) + ; + + x509 = new JcaX509CertificateConverter().getCertificate( + xcb.build(BCFactory.contentSigner(caKey))); + } catch (GeneralSecurityException|OperatorCreationException e) { + throw new CertException(e); + } finally { + tt.done(); + } + + return new X509andChain(x509,x509cwi.trustChain); + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java index e31b9988..e51f2faa 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java @@ -33,61 +33,61 @@ import org.onap.aaf.cadi.configure.CertException; import org.onap.aaf.cadi.configure.Factory; public class X509ChainWithIssuer extends X509andChain { - private String issuerDN; - public X509Certificate caX509; + private String issuerDN; + public X509Certificate caX509; - public X509ChainWithIssuer(X509ChainWithIssuer orig, X509Certificate x509) throws IOException, CertException { - super(x509,orig.trustChain); - issuerDN=orig.issuerDN; - } - - public X509ChainWithIssuer(final List rdrs) throws IOException, CertException { - // Trust Chain. Last one should be the CA - Collection certs; - X509Certificate x509; - for(Reader rdr : rdrs) { - if(rdr==null) { // cover for badly formed array - continue; - } - - byte[] bytes = Factory.decode(rdr,null); - try { - certs = Factory.toX509Certificate(bytes); - } catch (CertificateException e) { - throw new CertException(e); - } - for(Certificate c : certs) { - x509=(X509Certificate)c; - Principal subject = x509.getSubjectDN(); - if(subject==null) { - continue; - } - if(cert==null) { // first in Trust Chain - issuerDN = subject.toString(); - cert=x509; // adding each time makes sure last one is signer. - } - addTrustChainEntry(x509); - } - } - } - - public X509ChainWithIssuer(Certificate[] certs) throws IOException, CertException { - X509Certificate x509; - for(int i=certs.length-1; i>=0; --i) { - x509=(X509Certificate)certs[i]; - Principal subject = x509.getSubjectDN(); - if(subject!=null) { - addTrustChainEntry(x509); - if(i==0) { // last one is signer - cert=x509; - issuerDN= subject.toString(); - } - } - } - } + public X509ChainWithIssuer(X509ChainWithIssuer orig, X509Certificate x509) throws IOException, CertException { + super(x509,orig.trustChain); + issuerDN=orig.issuerDN; + } + + public X509ChainWithIssuer(final List rdrs) throws IOException, CertException { + // Trust Chain. Last one should be the CA + Collection certs; + X509Certificate x509; + for(Reader rdr : rdrs) { + if(rdr==null) { // cover for badly formed array + continue; + } + + byte[] bytes = Factory.decode(rdr,null); + try { + certs = Factory.toX509Certificate(bytes); + } catch (CertificateException e) { + throw new CertException(e); + } + for(Certificate c : certs) { + x509=(X509Certificate)c; + Principal subject = x509.getSubjectDN(); + if(subject==null) { + continue; + } + if(cert==null) { // first in Trust Chain + issuerDN = subject.toString(); + cert=x509; // adding each time makes sure last one is signer. + } + addTrustChainEntry(x509); + } + } + } + + public X509ChainWithIssuer(Certificate[] certs) throws IOException, CertException { + X509Certificate x509; + for(int i=certs.length-1; i>=0; --i) { + x509=(X509Certificate)certs[i]; + Principal subject = x509.getSubjectDN(); + if(subject!=null) { + addTrustChainEntry(x509); + if(i==0) { // last one is signer + cert=x509; + issuerDN= subject.toString(); + } + } + } + } - public String getIssuerDN() { - return issuerDN; - } + public String getIssuerDN() { + return issuerDN; + } } \ No newline at end of file diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java index 5141cc62..3c684db2 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java @@ -37,44 +37,44 @@ import org.onap.aaf.cadi.configure.Factory; * */ public class X509andChain { - protected X509Certificate cert; - protected String[] trustChain; - - public X509andChain() { - cert = null; - trustChain = null; - } - - public X509andChain(X509Certificate cert, String[] tc) throws IOException, CertException { - this.cert = cert; - trustChain=tc; - } + protected X509Certificate cert; + protected String[] trustChain; + + public X509andChain() { + cert = null; + trustChain = null; + } + + public X509andChain(X509Certificate cert, String[] tc) throws IOException, CertException { + this.cert = cert; + trustChain=tc; + } - public X509andChain(X509Certificate cert, List chain) throws IOException, CertException { - this.cert = cert; - trustChain = new String[chain.size()+1]; - chain.toArray(trustChain); - } - - - public void addTrustChainEntry(X509Certificate x509) throws IOException, CertException { - if(trustChain==null) { - trustChain = new String[] {Factory.toString(NullTrans.singleton(),x509)}; - } else { - String[] temp = new String[trustChain.length+1]; - System.arraycopy(trustChain, 0, temp, 0, trustChain.length); - temp[trustChain.length]=Factory.toString(NullTrans.singleton(),x509); - trustChain=temp; - } - } - + public X509andChain(X509Certificate cert, List chain) throws IOException, CertException { + this.cert = cert; + trustChain = new String[chain.size()+1]; + chain.toArray(trustChain); + } + + + public void addTrustChainEntry(X509Certificate x509) throws IOException, CertException { + if(trustChain==null) { + trustChain = new String[] {Factory.toString(NullTrans.singleton(),x509)}; + } else { + String[] temp = new String[trustChain.length+1]; + System.arraycopy(trustChain, 0, temp, 0, trustChain.length); + temp[trustChain.length]=Factory.toString(NullTrans.singleton(),x509); + trustChain=temp; + } + } + - public X509Certificate getX509() { - return cert; - } - - public String[] getTrustChain() { - return trustChain; - } - + public X509Certificate getX509() { + return cert; + } + + public String[] getTrustChain() { + return trustChain; + } + } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java index e40a7a21..8edfa634 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java @@ -52,100 +52,100 @@ import org.onap.aaf.misc.env.Trans; * */ public class BCFactory extends Factory { - private static final JcaContentSignerBuilder jcsb; + private static final JcaContentSignerBuilder jcsb; - static { - // Bouncy - jcsb = new JcaContentSignerBuilder(Factory.SIG_ALGO); - } - - public static ContentSigner contentSigner(PrivateKey pk) throws OperatorCreationException { - return jcsb.build(pk); - } - - public static String toString(PKCS10CertificationRequest csr) throws IOException, CertException { - if(csr==null) { - throw new CertException("x509 Certificate Request not built"); - } - return textBuilder("CERTIFICATE REQUEST",csr.getEncoded()); - } + static { + // Bouncy + jcsb = new JcaContentSignerBuilder(Factory.SIG_ALGO); + } + + public static ContentSigner contentSigner(PrivateKey pk) throws OperatorCreationException { + return jcsb.build(pk); + } + + public static String toString(PKCS10CertificationRequest csr) throws IOException, CertException { + if(csr==null) { + throw new CertException("x509 Certificate Request not built"); + } + return textBuilder("CERTIFICATE REQUEST",csr.getEncoded()); + } - public static PKCS10CertificationRequest toCSR(Trans trans, File file) throws IOException { - TimeTaken tt = trans.start("Reconstitute CSR", Env.SUB); - try { - FileReader fr = new FileReader(file); - return new PKCS10CertificationRequest(decode(strip(fr))); - } finally { - tt.done(); - } - } + public static PKCS10CertificationRequest toCSR(Trans trans, File file) throws IOException { + TimeTaken tt = trans.start("Reconstitute CSR", Env.SUB); + try { + FileReader fr = new FileReader(file); + return new PKCS10CertificationRequest(decode(strip(fr))); + } finally { + tt.done(); + } + } - public static byte[] sign(Trans trans, ASN1Object toSign, PrivateKey pk) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException { - TimeTaken tt = trans.start("Encode Security Object", Env.SUB); - try { - return sign(trans,toSign.getEncoded(),pk); - } finally { - tt.done(); - } - } - - public static CSRMeta createCSRMeta(CA ca, String mechid, String sponsorEmail, List fqdns) throws CertException { - CSRMeta csr = ca.newCSRMeta(); - boolean first = true; - // Set CN (and SAN) - for(String fqdn : fqdns) { - if(first) { - first = false; - csr.cn(fqdn); - } - csr.san(fqdn); // duplicate CN in SAN, per RFC 5280 section 4.2.1.6 - } - - csr.challenge(new String(Symm.randomGen(24))); - csr.mechID(mechid); - csr.email(sponsorEmail); - String errs; - if((errs=validateApp(csr))!=null) { - throw new CertException(errs); - } - return csr; - } - - private static String validateApp(CSRMeta csr) { - CertmanValidator v = new CertmanValidator(); - if(v.nullOrBlank("cn", csr.cn()) - .nullOrBlank("mechID", csr.mechID()) -// .nullOrBlank("email", csr.email()) - .err()) { - return v.errs(); - } else { - return null; - } - } + public static byte[] sign(Trans trans, ASN1Object toSign, PrivateKey pk) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException { + TimeTaken tt = trans.start("Encode Security Object", Env.SUB); + try { + return sign(trans,toSign.getEncoded(),pk); + } finally { + tt.done(); + } + } + + public static CSRMeta createCSRMeta(CA ca, String mechid, String sponsorEmail, List fqdns) throws CertException { + CSRMeta csr = ca.newCSRMeta(); + boolean first = true; + // Set CN (and SAN) + for(String fqdn : fqdns) { + if(first) { + first = false; + csr.cn(fqdn); + } + csr.san(fqdn); // duplicate CN in SAN, per RFC 5280 section 4.2.1.6 + } + + csr.challenge(new String(Symm.randomGen(24))); + csr.mechID(mechid); + csr.email(sponsorEmail); + String errs; + if((errs=validateApp(csr))!=null) { + throw new CertException(errs); + } + return csr; + } + + private static String validateApp(CSRMeta csr) { + CertmanValidator v = new CertmanValidator(); + if(v.nullOrBlank("cn", csr.cn()) + .nullOrBlank("mechID", csr.mechID()) +// .nullOrBlank("email", csr.email()) + .err()) { + return v.errs(); + } else { + return null; + } + } - public static CSRMeta createPersonalCSRMeta(CA ca, String personal, String email) throws CertException { - CSRMeta csr = ca.newCSRMeta(); - csr.cn(personal); - csr.challenge(new String(Symm.randomGen(24))); - csr.email(email); - String errs; - if((errs=validatePersonal(csr))!=null) { - throw new CertException(errs); - } - return csr; - } + public static CSRMeta createPersonalCSRMeta(CA ca, String personal, String email) throws CertException { + CSRMeta csr = ca.newCSRMeta(); + csr.cn(personal); + csr.challenge(new String(Symm.randomGen(24))); + csr.email(email); + String errs; + if((errs=validatePersonal(csr))!=null) { + throw new CertException(errs); + } + return csr; + } - private static String validatePersonal(CSRMeta csr) { - CertmanValidator v = new CertmanValidator(); - if(v.nullOrBlank("cn", csr.cn()) - .nullOrBlank("email", csr.email()) - .err()) { - return v.errs(); - } else { - return null; - } - } - + private static String validatePersonal(CSRMeta csr) { + CertmanValidator v = new CertmanValidator(); + if(v.nullOrBlank("cn", csr.cn()) + .nullOrBlank("email", csr.email()) + .err()) { + return v.errs(); + } else { + return null; + } + } + } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java index f9fcad17..5df439ab 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java @@ -54,212 +54,212 @@ import org.onap.aaf.cadi.configure.Factory; import org.onap.aaf.misc.env.Trans; public class CSRMeta { - private String cn; - private String mechID; - private String environment; - private String email; - private String challenge; - private List rdns; - private ArrayList sanList = new ArrayList<>(); - private KeyPair keyPair; - private X500Name name = null; - private SecureRandom random = new SecureRandom(); + private String cn; + private String mechID; + private String environment; + private String email; + private String challenge; + private List rdns; + private ArrayList sanList = new ArrayList<>(); + private KeyPair keyPair; + private X500Name name = null; + private SecureRandom random = new SecureRandom(); - public CSRMeta(List rdns) { - this.rdns = rdns; - } + public CSRMeta(List rdns) { + this.rdns = rdns; + } - public X500Name x500Name() { - if(name==null) { - X500NameBuilder xnb = new X500NameBuilder(); - xnb.addRDN(BCStyle.CN,cn); - xnb.addRDN(BCStyle.E,email); - if(mechID!=null) { - if(environment==null) { - xnb.addRDN(BCStyle.OU,mechID); - } else { - xnb.addRDN(BCStyle.OU,mechID+':'+environment); - } - } - for(RDN rdn : rdns) { - xnb.addRDN(rdn.aoi,rdn.value); - } - name = xnb.build(); - } - return name; - } - - - public PKCS10CertificationRequest generateCSR(Trans trans) throws IOException, CertException { - PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name(),keypair(trans).getPublic()); - if(challenge!=null) { - DERPrintableString password = new DERPrintableString(challenge); - builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, password); - } - - int plus = email==null?0:1; - if(!sanList.isEmpty()) { - GeneralName[] gna = new GeneralName[sanList.size()+plus]; - int i=-1; - for(String s : sanList) { - gna[++i]=new GeneralName(GeneralName.dNSName,s); - } - gna[++i]=new GeneralName(GeneralName.rfc822Name,email); - - builder.addAttribute( - PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, - new Extensions(new Extension[] { - new Extension(Extension.subjectAlternativeName,false,new GeneralNames(gna).getEncoded()) - }) - ); - } + public X500Name x500Name() { + if(name==null) { + X500NameBuilder xnb = new X500NameBuilder(); + xnb.addRDN(BCStyle.CN,cn); + xnb.addRDN(BCStyle.E,email); + if(mechID!=null) { + if(environment==null) { + xnb.addRDN(BCStyle.OU,mechID); + } else { + xnb.addRDN(BCStyle.OU,mechID+':'+environment); + } + } + for(RDN rdn : rdns) { + xnb.addRDN(rdn.aoi,rdn.value); + } + name = xnb.build(); + } + return name; + } + + + public PKCS10CertificationRequest generateCSR(Trans trans) throws IOException, CertException { + PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name(),keypair(trans).getPublic()); + if(challenge!=null) { + DERPrintableString password = new DERPrintableString(challenge); + builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, password); + } + + int plus = email==null?0:1; + if(!sanList.isEmpty()) { + GeneralName[] gna = new GeneralName[sanList.size()+plus]; + int i=-1; + for(String s : sanList) { + gna[++i]=new GeneralName(GeneralName.dNSName,s); + } + gna[++i]=new GeneralName(GeneralName.rfc822Name,email); + + builder.addAttribute( + PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, + new Extensions(new Extension[] { + new Extension(Extension.subjectAlternativeName,false,new GeneralNames(gna).getEncoded()) + }) + ); + } - try { - return builder.build(BCFactory.contentSigner(keypair(trans).getPrivate())); - } catch (OperatorCreationException e) { - throw new CertException(e); - } - } - - @SuppressWarnings("deprecation") - public static void dump(PKCS10CertificationRequest csr) { - Attribute[] certAttributes = csr.getAttributes(); - for (Attribute attribute : certAttributes) { - if (!attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { - continue; - } + try { + return builder.build(BCFactory.contentSigner(keypair(trans).getPrivate())); + } catch (OperatorCreationException e) { + throw new CertException(e); + } + } + + @SuppressWarnings("deprecation") + public static void dump(PKCS10CertificationRequest csr) { + Attribute[] certAttributes = csr.getAttributes(); + for (Attribute attribute : certAttributes) { + if (!attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { + continue; + } - Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); - GeneralNames gns = GeneralNames.fromExtensions(extensions,Extension.subjectAlternativeName); - GeneralName[] names = gns.getNames(); - for(int k=0; k < names.length; k++) { - String title = ""; - if(names[k].getTagNo() == GeneralName.dNSName) { - title = "dNSName"; - } else if(names[k].getTagNo() == GeneralName.iPAddress) { - title = "iPAddress"; - // Deprecated, but I don't see anything better to use. - names[k].toASN1Object(); - } else if(names[k].getTagNo() == GeneralName.otherName) { - title = "otherName"; - } else if(names[k].getTagNo() == GeneralName.rfc822Name) { - title = "email"; - } + Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); + GeneralNames gns = GeneralNames.fromExtensions(extensions,Extension.subjectAlternativeName); + GeneralName[] names = gns.getNames(); + for(int k=0; k < names.length; k++) { + String title = ""; + if(names[k].getTagNo() == GeneralName.dNSName) { + title = "dNSName"; + } else if(names[k].getTagNo() == GeneralName.iPAddress) { + title = "iPAddress"; + // Deprecated, but I don't see anything better to use. + names[k].toASN1Object(); + } else if(names[k].getTagNo() == GeneralName.otherName) { + title = "otherName"; + } else if(names[k].getTagNo() == GeneralName.rfc822Name) { + title = "email"; + } - System.out.println(title + ": "+ names[k].getName()); - } - } - } - - public X509Certificate initialConversationCert(Trans trans) throws IOException, CertificateException, OperatorCreationException { - GregorianCalendar gc = new GregorianCalendar(); - Date start = gc.getTime(); - gc.add(GregorianCalendar.DAY_OF_MONTH,2); - Date end = gc.getTime(); - @SuppressWarnings("deprecation") - X509v3CertificateBuilder xcb = new X509v3CertificateBuilder( - x500Name(), - new BigInteger(12,random), // replace with Serialnumber scheme - start, - end, - x500Name(), - new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keypair(trans).getPublic().getEncoded())) - ); - return new JcaX509CertificateConverter().getCertificate( - xcb.build(BCFactory.contentSigner(keypair(trans).getPrivate()))); - } + System.out.println(title + ": "+ names[k].getName()); + } + } + } + + public X509Certificate initialConversationCert(Trans trans) throws IOException, CertificateException, OperatorCreationException { + GregorianCalendar gc = new GregorianCalendar(); + Date start = gc.getTime(); + gc.add(GregorianCalendar.DAY_OF_MONTH,2); + Date end = gc.getTime(); + @SuppressWarnings("deprecation") + X509v3CertificateBuilder xcb = new X509v3CertificateBuilder( + x500Name(), + new BigInteger(12,random), // replace with Serialnumber scheme + start, + end, + x500Name(), + new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keypair(trans).getPublic().getEncoded())) + ); + return new JcaX509CertificateConverter().getCertificate( + xcb.build(BCFactory.contentSigner(keypair(trans).getPrivate()))); + } - public CSRMeta san(String v) { - sanList.add(v); - return this; - } + public CSRMeta san(String v) { + sanList.add(v); + return this; + } - public List sans() { - return sanList; - } + public List sans() { + return sanList; + } - public KeyPair keypair(Trans trans) { - if(keyPair == null) { - keyPair = Factory.generateKeyPair(trans); - } - return keyPair; - } + public KeyPair keypair(Trans trans) { + if(keyPair == null) { + keyPair = Factory.generateKeyPair(trans); + } + return keyPair; + } - /** - * @return the cn - */ - public String cn() { - return cn; - } + /** + * @return the cn + */ + public String cn() { + return cn; + } - /** - * @param cn the cn to set - */ - public void cn(String cn) { - this.cn = cn; - } + /** + * @param cn the cn to set + */ + public void cn(String cn) { + this.cn = cn; + } - /** - * Environment of Service MechID is good for - */ - public void environment(String env) { - environment = env; - } - - /** - * - * @return - */ - public String environment() { - return environment; - } - - /** - * @return the mechID - */ - public String mechID() { - return mechID; - } + /** + * Environment of Service MechID is good for + */ + public void environment(String env) { + environment = env; + } + + /** + * + * @return + */ + public String environment() { + return environment; + } + + /** + * @return the mechID + */ + public String mechID() { + return mechID; + } - /** - * @param mechID the mechID to set - */ - public void mechID(String mechID) { - this.mechID = mechID; - } + /** + * @param mechID the mechID to set + */ + public void mechID(String mechID) { + this.mechID = mechID; + } - /** - * @return the email - */ - public String email() { - return email; - } + /** + * @return the email + */ + public String email() { + return email; + } - /** - * @param email the email to set - */ - public void email(String email) { - this.email = email; - } + /** + * @param email the email to set + */ + public void email(String email) { + this.email = email; + } - /** - * @return the challenge - */ - public String challenge() { - return challenge; - } + /** + * @return the challenge + */ + public String challenge() { + return challenge; + } - /** - * @param challenge the challenge to set - */ - public void challenge(String challenge) { - this.challenge = challenge; - } - + /** + * @param challenge the challenge to set + */ + public void challenge(String challenge) { + this.challenge = challenge; + } + } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java index b109ffcb..c39ba6d3 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java @@ -29,75 +29,75 @@ import org.onap.aaf.cadi.configure.CertException; import org.onap.aaf.cadi.util.Split; public class RDN { - public String tag; - public String value; - public ASN1ObjectIdentifier aoi; - public RDN(final String tagValue) throws CertException { - String[] tv = Split.splitTrim('=',tagValue); - switch(tv[0]) { - case "cn":case "CN": aoi = BCStyle.CN; break; - case "c":case "C": aoi = BCStyle.C;break; - case "st":case "ST": aoi = BCStyle.ST;break; - case "l":case "L": aoi = BCStyle.L;break; - case "o":case "O": aoi = BCStyle.O;break; - case "ou":case "OU": aoi = BCStyle.OU;break; - case "dc":case "DC": aoi = BCStyle.DC;break; - case "gn":case "GN": aoi = BCStyle.GIVENNAME; break; - case "sn":case "SN": aoi = BCStyle.SN; break; // surname - case "email":case "EMAIL": - case "emailaddress": - case "EMAILADDRESS": aoi = BCStyle.EmailAddress;break; // should be SAN extension - case "initials": aoi = BCStyle.INITIALS; break; - case "pseudonym": aoi = BCStyle.PSEUDONYM; break; - case "generationQualifier": aoi = BCStyle.GENERATION; break; - case "serialNumber": aoi = BCStyle.SERIALNUMBER; break; - default: - throw new CertException("Unknown ASN1ObjectIdentifier for " + tv[0] + " in " + tagValue); - } - tag = tv[0]; - value = tv[1]; - } - - /** - * Parse various forms of DNs into appropriate RDNs, which have the ASN1ObjectIdentifier - * @param delim - * @param dnString - * @return - * @throws CertException - */ - public static List parse(final char delim, final String dnString ) throws CertException { - List lrnd = new ArrayList<>(); - StringBuilder sb = new StringBuilder(); - boolean inQuotes = false; - for(int i=0;i0) { - lrnd.add(new RDN(sb.toString())); - sb.setLength(0); - } - } else { - sb.append(dnString.charAt(i)); - } - } - } - if(sb.indexOf("=")>0) { - lrnd.add(new RDN(sb.toString())); - } - return lrnd; - } - - @Override - public String toString() { - return tag + '=' + value; - } + public String tag; + public String value; + public ASN1ObjectIdentifier aoi; + public RDN(final String tagValue) throws CertException { + String[] tv = Split.splitTrim('=',tagValue); + switch(tv[0]) { + case "cn":case "CN": aoi = BCStyle.CN; break; + case "c":case "C": aoi = BCStyle.C;break; + case "st":case "ST": aoi = BCStyle.ST;break; + case "l":case "L": aoi = BCStyle.L;break; + case "o":case "O": aoi = BCStyle.O;break; + case "ou":case "OU": aoi = BCStyle.OU;break; + case "dc":case "DC": aoi = BCStyle.DC;break; + case "gn":case "GN": aoi = BCStyle.GIVENNAME; break; + case "sn":case "SN": aoi = BCStyle.SN; break; // surname + case "email":case "EMAIL": + case "emailaddress": + case "EMAILADDRESS": aoi = BCStyle.EmailAddress;break; // should be SAN extension + case "initials": aoi = BCStyle.INITIALS; break; + case "pseudonym": aoi = BCStyle.PSEUDONYM; break; + case "generationQualifier": aoi = BCStyle.GENERATION; break; + case "serialNumber": aoi = BCStyle.SERIALNUMBER; break; + default: + throw new CertException("Unknown ASN1ObjectIdentifier for " + tv[0] + " in " + tagValue); + } + tag = tv[0]; + value = tv[1]; + } + + /** + * Parse various forms of DNs into appropriate RDNs, which have the ASN1ObjectIdentifier + * @param delim + * @param dnString + * @return + * @throws CertException + */ + public static List parse(final char delim, final String dnString ) throws CertException { + List lrnd = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + boolean inQuotes = false; + for(int i=0;i0) { + lrnd.add(new RDN(sb.toString())); + sb.setLength(0); + } + } else { + sb.append(dnString.charAt(i)); + } + } + } + if(sb.indexOf("=")>0) { + lrnd.add(new RDN(sb.toString())); + } + return lrnd; + } + + @Override + public String toString() { + return tag + '=' + value; + } } \ No newline at end of file diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertReq.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertReq.java index d960945c..ad7f10eb 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertReq.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertReq.java @@ -31,19 +31,19 @@ import org.onap.aaf.auth.cm.cert.CSRMeta; import org.onap.aaf.cadi.configure.CertException; public class CertReq { - // These cannot be null - public CA certAuthority; - public String mechid; - public List fqdns; - // Notify - public List emails; - - - // These may be null - public String sponsor; - public XMLGregorianCalendar start, end; - - public CSRMeta getCSRMeta() throws CertException { - return BCFactory.createCSRMeta(certAuthority, mechid, sponsor,fqdns); - } + // These cannot be null + public CA certAuthority; + public String mechid; + public List fqdns; + // Notify + public List emails; + + + // These may be null + public String sponsor; + public XMLGregorianCalendar start, end; + + public CSRMeta getCSRMeta() throws CertException { + return BCFactory.createCSRMeta(certAuthority, mechid, sponsor,fqdns); + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertResp.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertResp.java index 970bfb85..e156fe91 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertResp.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/data/CertResp.java @@ -33,59 +33,59 @@ import org.onap.aaf.cadi.configure.Factory; import org.onap.aaf.misc.env.Trans; public class CertResp { - private CA ca; - private KeyPair keyPair; - private String challenge; - - private String privateKey, certString; - private String[] trustChain; - private String[] notes; - - public CertResp(Trans trans, CA ca, X509Certificate x509, CSRMeta csrMeta, String[] trustChain, String[] notes) throws IOException, GeneralSecurityException, CertException { - keyPair = csrMeta.keypair(trans); - privateKey = Factory.toString(trans, keyPair.getPrivate()); - certString = Factory.toString(trans,x509); - challenge=csrMeta.challenge(); - this.ca = ca; - this.trustChain = trustChain; - this.notes = notes; - } + private CA ca; + private KeyPair keyPair; + private String challenge; + + private String privateKey, certString; + private String[] trustChain; + private String[] notes; + + public CertResp(Trans trans, CA ca, X509Certificate x509, CSRMeta csrMeta, String[] trustChain, String[] notes) throws IOException, GeneralSecurityException, CertException { + keyPair = csrMeta.keypair(trans); + privateKey = Factory.toString(trans, keyPair.getPrivate()); + certString = Factory.toString(trans,x509); + challenge=csrMeta.challenge(); + this.ca = ca; + this.trustChain = trustChain; + this.notes = notes; + } - // Use for Read Responses, etc - public CertResp(String cert) { - certString = cert; - } + // Use for Read Responses, etc + public CertResp(String cert) { + certString = cert; + } - - public String asCertString() { - return certString; - } - - public String privateString() throws IOException { - return privateKey; - } - - public String challenge() { - return challenge==null?"":challenge; - } - - public String[] notes() { - return notes; - } - - public String[] caIssuerDNs() { - return ca.getCaIssuerDNs(); - } - - public String env() { - return ca.getEnv(); - } - - public String[] trustChain() { - return trustChain; - } - - public String[] trustCAs() { - return ca.getTrustedCAs(); - } + + public String asCertString() { + return certString; + } + + public String privateString() throws IOException { + return privateKey; + } + + public String challenge() { + return challenge==null?"":challenge; + } + + public String[] notes() { + return notes; + } + + public String[] caIssuerDNs() { + return ca.getCaIssuerDNs(); + } + + public String env() { + return ca.getEnv(); + } + + public String[] trustChain() { + return trustChain; + } + + public String[] trustCAs() { + return ca.getTrustedCAs(); + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade.java index 9eb9c2fa..4952dbec 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade.java @@ -40,143 +40,143 @@ import org.onap.aaf.auth.layer.Result; public interface Facade { ///////////////////// STANDARD ELEMENTS ////////////////// - /** - * @param trans - * @param response - * @param result - */ - void error(AuthzTrans trans, HttpServletResponse response, Result result); - - /** - * - * @param trans - * @param response - * @param status - */ - void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... detail); - - /** - * Permission checker - * - * @param trans - * @param resp - * @param perm - * @return - * @throws IOException - */ - Result check(AuthzTrans trans, HttpServletResponse resp, String perm) throws IOException; - - /** - * - * @return - */ - public Mapper mapper(); + /** + * @param trans + * @param response + * @param result + */ + void error(AuthzTrans trans, HttpServletResponse response, Result result); + + /** + * + * @param trans + * @param response + * @param status + */ + void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... detail); + + /** + * Permission checker + * + * @param trans + * @param resp + * @param perm + * @return + * @throws IOException + */ + Result check(AuthzTrans trans, HttpServletResponse resp, String perm) throws IOException; + + /** + * + * @return + */ + public Mapper mapper(); ///////////////////// STANDARD ELEMENTS ////////////////// - - /** - * - * @param trans - * @param resp - * @param rservlet - * @return - */ - public abstract Result requestCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca); - - /** - * - * @param trans - * @param resp - * @param rservlet - * @return - */ - public abstract Result requestPersonalCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca); - - - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - public abstract Result renewCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, boolean withTrust); - - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - public abstract Result dropCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - - /** - * - * @param trans - * @param resp - * @param pathParam - * @return - */ - public Result readCertsByMechID(AuthzTrans trans, HttpServletResponse resp, String mechID); - - - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - Result createArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - Result readArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - /** - * - * @param trans - * @param resp - * @param mechid - * @param machine - * @return - */ - Result readArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine); - - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - Result updateArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - Result deleteArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - /** - * - * @param trans - * @param resp - * @param mechid - * @param machine - * @return - */ - Result deleteArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine); + + /** + * + * @param trans + * @param resp + * @param rservlet + * @return + */ + public abstract Result requestCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca); + + /** + * + * @param trans + * @param resp + * @param rservlet + * @return + */ + public abstract Result requestPersonalCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca); + + + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + public abstract Result renewCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, boolean withTrust); + + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + public abstract Result dropCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + + /** + * + * @param trans + * @param resp + * @param pathParam + * @return + */ + public Result readCertsByMechID(AuthzTrans trans, HttpServletResponse resp, String mechID); + + + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + Result createArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + Result readArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + /** + * + * @param trans + * @param resp + * @param mechid + * @param machine + * @return + */ + Result readArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine); + + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + Result updateArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + Result deleteArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + /** + * + * @param trans + * @param resp + * @param mechid + * @param machine + * @return + */ + Result deleteArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine); } \ No newline at end of file diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade1_0.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade1_0.java index 49d976b2..4a3b5cbe 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade1_0.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/Facade1_0.java @@ -37,10 +37,10 @@ import certman.v1_0.CertInfo; * */ public class Facade1_0 extends FacadeImpl { - public Facade1_0(AAF_CM certman, - CMService service, - Mapper mapper, - Data.TYPE type) throws APIException { - super(certman, service, mapper, type); - } + public Facade1_0(AAF_CM certman, + CMService service, + Mapper mapper, + Data.TYPE type) throws APIException { + super(certman, service, mapper, type); + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeFactory.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeFactory.java index 6eb13f93..e9ffb908 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeFactory.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeFactory.java @@ -30,12 +30,12 @@ import org.onap.aaf.misc.env.Data; public class FacadeFactory { - public static Facade1_0 v1_0(AAF_CM certman, AuthzTrans trans, CMService service, Data.TYPE type) throws APIException { - return new Facade1_0( - certman, - service, - new Mapper1_0(), - type); - } + public static Facade1_0 v1_0(AAF_CM certman, AuthzTrans trans, CMService service, Data.TYPE type) throws APIException { + return new Facade1_0( + certman, + service, + new Mapper1_0(), + type); + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java index 98fdf11b..310ea8b2 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java @@ -66,7 +66,7 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; * 1) Interact with the Service Implementation (which might be supported by various kinds of Backend Storage) * 2) Validate incoming data (if applicable) * 3) Convert the Service response into the right Format, and mark the Content Type - * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. + * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. * 4) Log Service info, warnings and exceptions as necessary * 5) When asked by the API layer, this will create and write Error content to the OutputStream * @@ -77,562 +77,562 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; * */ public abstract class FacadeImpl extends org.onap.aaf.auth.layer.FacadeImpl implements Facade - { - private static final String TRUE = "TRUE"; - private static final String REQUEST_CERT = "Request New Certificate"; - private static final String RENEW_CERT = "Renew Certificate"; - private static final String DROP_CERT = "Drop Certificate"; - private static final String READ_CERTS_MECHID = "Read Certificates by MechID"; - private static final String CREATE_ARTIFACTS = "Create Deployment Artifact"; - private static final String READ_ARTIFACTS = "Read Deployment Artifact"; - private static final String UPDATE_ARTIFACTS = "Update Deployment Artifact"; - private static final String DELETE_ARTIFACTS = "Delete Deployment Artifact"; - - private CMService service; - - private final RosettaDF errDF; - private final RosettaDF certRequestDF, certRenewDF, certDropDF; - private final RosettaDF certDF; - private final RosettaDF artiDF; - private Mapper mapper; -// private Slot sCertAuth; - private AAF_CM certman; - private final String voidResp; - - public FacadeImpl(AAF_CM certman, - CMService service, - Mapper mapper, - Data.TYPE dataType) throws APIException { - this.service = service; - this.mapper = mapper; - this.certman = certman; - AuthzEnv env = certman.env; - //TODO: Gabe [JUnit] Static issue, talk to Jonathan - (errDF = env.newDataFactory(mapper.getClass(API.ERROR))).in(dataType).out(dataType); - (certRequestDF = env.newDataFactory(mapper.getClass(API.CERT_REQ))).in(dataType).out(dataType); - (certRenewDF = env.newDataFactory(mapper.getClass(API.CERT_RENEW))).in(dataType).out(dataType); - (certDropDF = env.newDataFactory(mapper.getClass(API.CERT_DROP))).in(dataType).out(dataType); - (certDF = env.newDataFactory(mapper.getClass(API.CERT))).in(dataType).out(dataType); - (artiDF = env.newDataFactory(mapper.getClass(API.ARTIFACTS))).in(dataType).out(dataType); -// sCertAuth = env.slot(API_Cert.CERT_AUTH); - if(artiDF.getOutType().name().contains("xml")) { - voidResp = "application/Void+xml;charset=utf-8;version=1.0,application/xml;version=1.0,*/*"; - } else { - voidResp = "application/Void+json;charset=utf-8;version=1.0,application/json;version=1.0,*/*"; - } - } - - public Mapper mapper() { - return mapper; - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) - * - * Note: Conforms to AT&T TSS RESTful Error Structure - */ - @Override - public void error(AuthzTrans trans, HttpServletResponse response, Result result) { - error(trans, response, result.status, - result.details==null?"":result.details.trim(), - result.variables==null?new String[0]:result.variables); - } - - @Override - public void error(AuthzTrans trans, HttpServletResponse response, int status, final String _msg, final String ... _detail) { - String msgId; - String prefix; - boolean hidemsg=false; - switch(status) { - case 202: - case ERR_ActionNotCompleted: - msgId = "SVC1202"; - prefix = "Accepted, Action not complete"; - response.setStatus(/*httpstatus=*/202); - break; - - case 403: - case ERR_Policy: - case ERR_Security: - case ERR_Denied: - msgId = "SVC1403"; - prefix = "Forbidden"; - response.setStatus(/*httpstatus=*/403); - break; - - case 404: - case ERR_NotFound: - msgId = "SVC1404"; - prefix = "Not Found"; - response.setStatus(/*httpstatus=*/404); - break; - - case 406: - case ERR_BadData: - msgId="SVC1406"; - prefix = "Not Acceptable"; - response.setStatus(/*httpstatus=*/406); - break; - - case 409: - case ERR_ConflictAlreadyExists: - msgId = "SVC1409"; - prefix = "Conflict Already Exists"; - response.setStatus(/*httpstatus=*/409); - break; - - case 501: - case ERR_NotImplemented: - msgId = "SVC1501"; - prefix = "Not Implemented"; - response.setStatus(/*httpstatus=*/501); - break; - - - default: - msgId = "SVC1500"; - prefix = "General Service Error"; - response.setStatus(/*httpstatus=*/500); - hidemsg=true; - break; - } - - try { - StringBuilder holder = new StringBuilder(); - ERROR em = mapper().errorFromMessage(holder, msgId,prefix + ": " + _msg,_detail); - trans.checkpoint( - "ErrResp [" + - msgId + - "] " + - holder.toString(), - Env.ALWAYS); - if(hidemsg) { - holder.setLength(0); - em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); - } - errDF.newData(trans).load(em).to(response.getOutputStream()); - - } catch (Exception e) { - trans.error().log(e,"unable to send response for",_msg); - } - } - - @Override - public Result check(AuthzTrans trans, HttpServletResponse resp, String perm) throws IOException { - String[] p = Split.split('|',perm); - AAFPermission ap; - switch(p.length) { - case 3: - ap = new AAFPermission(null, p[0],p[1],p[2]); - break; - case 4: - ap = new AAFPermission(p[0],p[1],p[2],p[3]); - break; - default: - return Result.err(Result.ERR_BadData,"Invalid Perm String"); - } - if(certman.aafLurPerm.fish(trans.getUserPrincipal(), ap)) { - resp.setContentType(voidResp); - resp.getOutputStream().write(0); - return Result.ok(); - } else { - return Result.err(Result.ERR_Denied,"%s does not have %s",trans.user(),ap.getKey()); - } - } - - /* (non-Javadoc) - * @see com.att.auth.certman.facade.Facade#requestCert(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result requestCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca) { - TimeTaken tt = trans.start(REQUEST_CERT, Env.SUB|Env.ALWAYS); - String wt; - boolean withTrust=(wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt); - try { - REQ request; - try { - Data rd = certRequestDF.newData().load(req.getInputStream()); - request = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,REQUEST_CERT); - return Result.err(Result.ERR_BadData,"Invalid Input"); - } - - Result rcr = service.requestCert(trans,mapper.toReq(trans,request), ca); - if(rcr.notOK()) { - return Result.err(rcr); - } - -// CA certAuth = trans.get(sCertAuth,null); - Result rc = mapper.toCert(trans, rcr, withTrust); - switch(rc.status) { - case OK: - RosettaData data = certDF.newData(trans).load(rc.value); - data.to(resp.getOutputStream()); - - setContentType(resp,certDF.getOutType()); - return Result.ok(); - default: - return Result.err(rc); - } - - } catch (Exception e) { - trans.error().log(e,IN,REQUEST_CERT); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.cm.facade.Facade#requestPersonalCert(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean) - */ - @Override - public Result requestPersonalCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca) { - return Result.err(Result.ERR_NotImplemented,"not implemented yet"); -// Result rcr = service.requestPersonalCert(trans,ca); -// if(rcr.notOK()) { -// return Result.err(rcr); -// } else { -// try { -// resp.setContentType("application/zip, application/octet-stream"); -// ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream()); -// PrintStream ps = new PrintStream(zos); -// ZipEntry ze = new ZipEntry(trans.user()+".key"); -// zos.putNextEntry(ze); -// ps.print(rcr.value.privateString()); -// zos.closeEntry(); + { + private static final String TRUE = "TRUE"; + private static final String REQUEST_CERT = "Request New Certificate"; + private static final String RENEW_CERT = "Renew Certificate"; + private static final String DROP_CERT = "Drop Certificate"; + private static final String READ_CERTS_MECHID = "Read Certificates by MechID"; + private static final String CREATE_ARTIFACTS = "Create Deployment Artifact"; + private static final String READ_ARTIFACTS = "Read Deployment Artifact"; + private static final String UPDATE_ARTIFACTS = "Update Deployment Artifact"; + private static final String DELETE_ARTIFACTS = "Delete Deployment Artifact"; + + private CMService service; + + private final RosettaDF errDF; + private final RosettaDF certRequestDF, certRenewDF, certDropDF; + private final RosettaDF certDF; + private final RosettaDF artiDF; + private Mapper mapper; +// private Slot sCertAuth; + private AAF_CM certman; + private final String voidResp; + + public FacadeImpl(AAF_CM certman, + CMService service, + Mapper mapper, + Data.TYPE dataType) throws APIException { + this.service = service; + this.mapper = mapper; + this.certman = certman; + AuthzEnv env = certman.env; + //TODO: Gabe [JUnit] Static issue, talk to Jonathan + (errDF = env.newDataFactory(mapper.getClass(API.ERROR))).in(dataType).out(dataType); + (certRequestDF = env.newDataFactory(mapper.getClass(API.CERT_REQ))).in(dataType).out(dataType); + (certRenewDF = env.newDataFactory(mapper.getClass(API.CERT_RENEW))).in(dataType).out(dataType); + (certDropDF = env.newDataFactory(mapper.getClass(API.CERT_DROP))).in(dataType).out(dataType); + (certDF = env.newDataFactory(mapper.getClass(API.CERT))).in(dataType).out(dataType); + (artiDF = env.newDataFactory(mapper.getClass(API.ARTIFACTS))).in(dataType).out(dataType); +// sCertAuth = env.slot(API_Cert.CERT_AUTH); + if(artiDF.getOutType().name().contains("xml")) { + voidResp = "application/Void+xml;charset=utf-8;version=1.0,application/xml;version=1.0,*/*"; + } else { + voidResp = "application/Void+json;charset=utf-8;version=1.0,application/json;version=1.0,*/*"; + } + } + + public Mapper mapper() { + return mapper; + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) + * + * Note: Conforms to AT&T TSS RESTful Error Structure + */ + @Override + public void error(AuthzTrans trans, HttpServletResponse response, Result result) { + error(trans, response, result.status, + result.details==null?"":result.details.trim(), + result.variables==null?new String[0]:result.variables); + } + + @Override + public void error(AuthzTrans trans, HttpServletResponse response, int status, final String _msg, final String ... _detail) { + String msgId; + String prefix; + boolean hidemsg=false; + switch(status) { + case 202: + case ERR_ActionNotCompleted: + msgId = "SVC1202"; + prefix = "Accepted, Action not complete"; + response.setStatus(/*httpstatus=*/202); + break; + + case 403: + case ERR_Policy: + case ERR_Security: + case ERR_Denied: + msgId = "SVC1403"; + prefix = "Forbidden"; + response.setStatus(/*httpstatus=*/403); + break; + + case 404: + case ERR_NotFound: + msgId = "SVC1404"; + prefix = "Not Found"; + response.setStatus(/*httpstatus=*/404); + break; + + case 406: + case ERR_BadData: + msgId="SVC1406"; + prefix = "Not Acceptable"; + response.setStatus(/*httpstatus=*/406); + break; + + case 409: + case ERR_ConflictAlreadyExists: + msgId = "SVC1409"; + prefix = "Conflict Already Exists"; + response.setStatus(/*httpstatus=*/409); + break; + + case 501: + case ERR_NotImplemented: + msgId = "SVC1501"; + prefix = "Not Implemented"; + response.setStatus(/*httpstatus=*/501); + break; + + + default: + msgId = "SVC1500"; + prefix = "General Service Error"; + response.setStatus(/*httpstatus=*/500); + hidemsg=true; + break; + } + + try { + StringBuilder holder = new StringBuilder(); + ERROR em = mapper().errorFromMessage(holder, msgId,prefix + ": " + _msg,_detail); + trans.checkpoint( + "ErrResp [" + + msgId + + "] " + + holder.toString(), + Env.ALWAYS); + if(hidemsg) { + holder.setLength(0); + em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); + } + errDF.newData(trans).load(em).to(response.getOutputStream()); + + } catch (Exception e) { + trans.error().log(e,"unable to send response for",_msg); + } + } + + @Override + public Result check(AuthzTrans trans, HttpServletResponse resp, String perm) throws IOException { + String[] p = Split.split('|',perm); + AAFPermission ap; + switch(p.length) { + case 3: + ap = new AAFPermission(null, p[0],p[1],p[2]); + break; + case 4: + ap = new AAFPermission(p[0],p[1],p[2],p[3]); + break; + default: + return Result.err(Result.ERR_BadData,"Invalid Perm String"); + } + if(certman.aafLurPerm.fish(trans.getUserPrincipal(), ap)) { + resp.setContentType(voidResp); + resp.getOutputStream().write(0); + return Result.ok(); + } else { + return Result.err(Result.ERR_Denied,"%s does not have %s",trans.user(),ap.getKey()); + } + } + + /* (non-Javadoc) + * @see com.att.auth.certman.facade.Facade#requestCert(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result requestCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca) { + TimeTaken tt = trans.start(REQUEST_CERT, Env.SUB|Env.ALWAYS); + String wt; + boolean withTrust=(wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt); + try { + REQ request; + try { + Data rd = certRequestDF.newData().load(req.getInputStream()); + request = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,REQUEST_CERT); + return Result.err(Result.ERR_BadData,"Invalid Input"); + } + + Result rcr = service.requestCert(trans,mapper.toReq(trans,request), ca); + if(rcr.notOK()) { + return Result.err(rcr); + } + +// CA certAuth = trans.get(sCertAuth,null); + Result rc = mapper.toCert(trans, rcr, withTrust); + switch(rc.status) { + case OK: + RosettaData data = certDF.newData(trans).load(rc.value); + data.to(resp.getOutputStream()); + + setContentType(resp,certDF.getOutType()); + return Result.ok(); + default: + return Result.err(rc); + } + + } catch (Exception e) { + trans.error().log(e,IN,REQUEST_CERT); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.facade.Facade#requestPersonalCert(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean) + */ + @Override + public Result requestPersonalCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca) { + return Result.err(Result.ERR_NotImplemented,"not implemented yet"); +// Result rcr = service.requestPersonalCert(trans,ca); +// if(rcr.notOK()) { +// return Result.err(rcr); +// } else { +// try { +// resp.setContentType("application/zip, application/octet-stream"); +// ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream()); +// PrintStream ps = new PrintStream(zos); +// ZipEntry ze = new ZipEntry(trans.user()+".key"); +// zos.putNextEntry(ze); +// ps.print(rcr.value.privateString()); +// zos.closeEntry(); // -// zos.putNextEntry(new ZipEntry(trans.user()+".crt")); -// ps.print(rcr.value.asCertString()); -// zos.closeEntry(); -// -// String wt; -// if((wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt)) { -// zos.putNextEntry(new ZipEntry(trans.user()+".trustCrts")); -// for(String s : ca.getTrustChain()) { -// ps.println(s); -// } -// zos.closeEntry(); -// } -// -// boolean withJKS = (wt=req.getParameter("withJKS"))!=null || TRUE.equalsIgnoreCase(wt); -// if(withJKS) { -// if(trans.getUserPrincipal() instanceof BasicPrincipal) { -// char[] cap = new String(((BasicPrincipal)trans.getUserPrincipal()).getCred()).toCharArray(); -// KeyStore ks = keystore(trans, rcr.value, ca.getTrustChain(), trans.user(), cap); -// zos.putNextEntry(new ZipEntry(trans.user()+".jks")); -// ks.store(zos, cap); -// zos.closeEntry(); -// } -// } -// -// zos.putNextEntry(new ZipEntry("cert_deploy.sh")); -// ps.println("# Deploy Certificate to ~/.aaf"); -// ps.println("if [ \"$1\" = \"\" ]; then echo \"sh deploy.sh \";exit; else chmod 700 $HOME/.aaf; fi"); -// ps.println("chmod 600 $1"); -// ps.println("if [ ! -e $HOME/.aaf ]; then mkdir -m 700 $HOME/.aaf; fi"); -// ps.println("THE_PWD=`pwd`"); -// ps.println("cd $HOME/.aaf"); -// ps.println("echo \"Deploying to `pwd`\""); -// ps.println("jar -xvf $THE_PWD/$1 " + trans.user()); -// ps.println("chmod 600 " + trans.user() + ".key"); -// if(withJKS) { -// ps.println("chmod 600 " + trans.user() + ".jks"); -// } -// ps.println("cd $THE_PWD"); -// ps.println("rm cert_deploy.sh"); -// zos.closeEntry(); -// +// zos.putNextEntry(new ZipEntry(trans.user()+".crt")); +// ps.print(rcr.value.asCertString()); +// zos.closeEntry(); +// +// String wt; +// if((wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt)) { +// zos.putNextEntry(new ZipEntry(trans.user()+".trustCrts")); +// for(String s : ca.getTrustChain()) { +// ps.println(s); +// } +// zos.closeEntry(); +// } +// +// boolean withJKS = (wt=req.getParameter("withJKS"))!=null || TRUE.equalsIgnoreCase(wt); +// if(withJKS) { +// if(trans.getUserPrincipal() instanceof BasicPrincipal) { +// char[] cap = new String(((BasicPrincipal)trans.getUserPrincipal()).getCred()).toCharArray(); +// KeyStore ks = keystore(trans, rcr.value, ca.getTrustChain(), trans.user(), cap); +// zos.putNextEntry(new ZipEntry(trans.user()+".jks")); +// ks.store(zos, cap); +// zos.closeEntry(); +// } +// } +// +// zos.putNextEntry(new ZipEntry("cert_deploy.sh")); +// ps.println("# Deploy Certificate to ~/.aaf"); +// ps.println("if [ \"$1\" = \"\" ]; then echo \"sh deploy.sh \";exit; else chmod 700 $HOME/.aaf; fi"); +// ps.println("chmod 600 $1"); +// ps.println("if [ ! -e $HOME/.aaf ]; then mkdir -m 700 $HOME/.aaf; fi"); +// ps.println("THE_PWD=`pwd`"); +// ps.println("cd $HOME/.aaf"); +// ps.println("echo \"Deploying to `pwd`\""); +// ps.println("jar -xvf $THE_PWD/$1 " + trans.user()); +// ps.println("chmod 600 " + trans.user() + ".key"); +// if(withJKS) { +// ps.println("chmod 600 " + trans.user() + ".jks"); +// } +// ps.println("cd $THE_PWD"); +// ps.println("rm cert_deploy.sh"); +// zos.closeEntry(); +// // -// zos.close(); -// -// } catch (IOException | KeyStoreException | CertificateException | APIException | CertException | NoSuchAlgorithmException e) { -// return Result.err(e); -// } -// } +// zos.close(); +// +// } catch (IOException | KeyStoreException | CertificateException | APIException | CertException | NoSuchAlgorithmException e) { +// return Result.err(e); +// } +// } // -// return Result.ok(); - } - -// private KeyStore keystore(AuthzTrans trans, CertResp cr, String[] trustChain, String name, char[] cap) throws KeyStoreException, CertificateException, APIException, IOException, CertException, NoSuchAlgorithmException { -// KeyStore jks = KeyStore.getInstance("jks"); -// jks.load(null, cap); -// -// // Get the Cert(s)... Might include Trust store -// List lcerts = new ArrayList<>(); -// lcerts.add(cr.asCertString()); -// for(String s : trustChain) { -// lcerts.add(s); -// } -// -// Collection certColl = Factory.toX509Certificate(lcerts); -// X509Certificate[] certs = new X509Certificate[certColl.size()]; -// certColl.toArray(certs); -// KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(cap); -// -// PrivateKey pk = Factory.toPrivateKey(trans, cr.privateString()); -// KeyStore.PrivateKeyEntry pkEntry = -// new KeyStore.PrivateKeyEntry(pk, new Certificate[] {certs[0]}); -// jks.setEntry(name, pkEntry, protParam); -// -// int i=0; -// for(X509Certificate x509 : certs) { -// jks.setCertificateEntry("cert_"+ ++i, x509); -// } -// return jks; -// } - - @Override - public Result renewCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, boolean withTrust) { - TimeTaken tt = trans.start(RENEW_CERT, Env.SUB|Env.ALWAYS); - try { - REQ request; - try { - Data rd = certRenewDF.newData().load(req.getInputStream()); - request = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,RENEW_CERT); - return Result.err(Result.ERR_BadData,"Invalid Input"); - } - -// String certAuth = trans.get(sCertAuth,null); - Result rcr = service.renewCert(trans,mapper.toRenew(trans,request)); - Result rc = mapper.toCert(trans, rcr, withTrust); - - switch(rc.status) { - case OK: - RosettaData data = certDF.newData(trans).load(rc.value); - data.to(resp.getOutputStream()); - - setContentType(resp,certDF.getOutType()); - return Result.ok(); - default: - return Result.err(rc); - } - } catch (Exception e) { - trans.error().log(e,IN,RENEW_CERT); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result dropCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DROP_CERT, Env.SUB|Env.ALWAYS); - try { - REQ request; - try { - Data rd = certDropDF.newData().load(req.getInputStream()); - request = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,DROP_CERT); - return Result.err(Result.ERR_BadData,"Invalid Input"); - } - - Result rv = service.dropCert(trans,mapper.toDrop(trans, request)); - switch(rv.status) { - case OK: - setContentType(resp,certRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rv); - } - } catch (Exception e) { - trans.error().log(e,IN,DROP_CERT); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.cm.facade.Facade#readCertsByMechID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result readCertsByMechID(AuthzTrans trans, HttpServletResponse resp, String mechID) { - TimeTaken tt = trans.start(READ_CERTS_MECHID, Env.SUB|Env.ALWAYS); - try { - Result rc = mapper.toCert(trans, service.readCertsByMechID(trans,mechID)); - switch(rc.status) { - case OK: - RosettaData data = certDF.newData(trans).load(rc.value); - data.to(resp.getOutputStream()); - - setContentType(resp,certDF.getOutType()); - return Result.ok(); - default: - return Result.err(rc); - } - } catch (Exception e) { - trans.error().log(e,IN,READ_CERTS_MECHID); - return Result.err(e); - } finally { - tt.done(); - } - } - - //////////////////////////// - // Artifacts - //////////////////////////// - @Override - public Result createArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(CREATE_ARTIFACTS, Env.SUB); - try { - ARTIFACTS arti; - try { - Data rd = artiDF.newData().load(req.getInputStream()); - arti = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_ARTIFACTS); - return Result.err(Result.ERR_BadData,"Invalid Input"); - } - - return service.createArtifact(trans,mapper.toArtifact(trans,arti)); - } catch (Exception e) { - - trans.error().log(e,IN,CREATE_ARTIFACTS); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result readArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(READ_ARTIFACTS, Env.SUB); - try { - String mechid = req.getParameter("mechid"); - String machine = req.getParameter("machine"); - String ns = req.getParameter("ns"); - - Result ra; - if( machine !=null && mechid == null) { - ra = mapper.fromArtifacts(service.readArtifactsByMachine(trans, machine)); - } else if(mechid!=null && machine==null) { - ra = mapper.fromArtifacts(service.readArtifactsByMechID(trans, mechid)); - } else if(mechid!=null && machine!=null) { - ArtiDAO.Data add = new ArtiDAO.Data(); - add.mechid = mechid; - add.machine = machine; - add.ns = ns; - ra = mapper.fromArtifacts(service.readArtifacts(trans,add)); - } else if(ns!=null) { - ra = mapper.fromArtifacts(service.readArtifactsByNs(trans, ns)); - } else { - ra = Result.err(Status.ERR_BadData,"Invalid request inputs"); - } - - if(ra.isOK()) { - RosettaData data = artiDF.newData(trans).load(ra.value); - data.to(resp.getOutputStream()); - setContentType(resp,artiDF.getOutType()); - return Result.ok(); - } else { - return Result.err(ra); - } - - } catch (Exception e) { - trans.error().log(e,IN,READ_ARTIFACTS); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result readArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine) { - TimeTaken tt = trans.start(READ_ARTIFACTS, Env.SUB); - try { - ArtiDAO.Data add = new ArtiDAO.Data(); - add.mechid = mechid; - add.machine = machine; - Result ra = mapper.fromArtifacts(service.readArtifacts(trans,add)); - if(ra.isOK()) { - RosettaData data = artiDF.newData(trans).load(ra.value); - data.to(resp.getOutputStream()); - setContentType(resp,artiDF.getOutType()); - return Result.ok(); - } else { - return Result.err(ra); - } - } catch (Exception e) { - trans.error().log(e,IN,READ_ARTIFACTS); - return Result.err(e); - } finally { - tt.done(); - } - } - - - @Override - public Result updateArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_ARTIFACTS, Env.SUB); - try { - ARTIFACTS arti; - try { - Data rd = artiDF.newData().load(req.getInputStream()); - arti = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,UPDATE_ARTIFACTS); - return Result.err(Result.ERR_BadData,"Invalid Input"); - } - - return service.updateArtifact(trans,mapper.toArtifact(trans,arti)); - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_ARTIFACTS); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_ARTIFACTS, Env.SUB); - try { - ARTIFACTS arti; - try { - Data rd = artiDF.newData().load(req.getInputStream()); - arti = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,DELETE_ARTIFACTS); - return Result.err(Result.ERR_BadData,"Invalid Input"); - } - - Result rv = service.deleteArtifact(trans,mapper.toArtifact(trans,arti)); - switch(rv.status) { - case OK: - setContentType(resp,artiDF.getOutType()); - } - return rv; - } catch (Exception e) { - trans.error().log(e,IN,DELETE_ARTIFACTS); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine) { - TimeTaken tt = trans.start(DELETE_ARTIFACTS, Env.SUB); - try { - Result rv = service.deleteArtifact(trans, mechid, machine); - switch(rv.status) { - case OK: - setContentType(resp,artiDF.getOutType()); - } - return rv; - } catch (Exception e) { - trans.error().log(e,IN,DELETE_ARTIFACTS); - return Result.err(e); - } finally { - tt.done(); - } - } +// return Result.ok(); + } + +// private KeyStore keystore(AuthzTrans trans, CertResp cr, String[] trustChain, String name, char[] cap) throws KeyStoreException, CertificateException, APIException, IOException, CertException, NoSuchAlgorithmException { +// KeyStore jks = KeyStore.getInstance("jks"); +// jks.load(null, cap); +// +// // Get the Cert(s)... Might include Trust store +// List lcerts = new ArrayList<>(); +// lcerts.add(cr.asCertString()); +// for(String s : trustChain) { +// lcerts.add(s); +// } +// +// Collection certColl = Factory.toX509Certificate(lcerts); +// X509Certificate[] certs = new X509Certificate[certColl.size()]; +// certColl.toArray(certs); +// KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(cap); +// +// PrivateKey pk = Factory.toPrivateKey(trans, cr.privateString()); +// KeyStore.PrivateKeyEntry pkEntry = +// new KeyStore.PrivateKeyEntry(pk, new Certificate[] {certs[0]}); +// jks.setEntry(name, pkEntry, protParam); +// +// int i=0; +// for(X509Certificate x509 : certs) { +// jks.setCertificateEntry("cert_"+ ++i, x509); +// } +// return jks; +// } + + @Override + public Result renewCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, boolean withTrust) { + TimeTaken tt = trans.start(RENEW_CERT, Env.SUB|Env.ALWAYS); + try { + REQ request; + try { + Data rd = certRenewDF.newData().load(req.getInputStream()); + request = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,RENEW_CERT); + return Result.err(Result.ERR_BadData,"Invalid Input"); + } + +// String certAuth = trans.get(sCertAuth,null); + Result rcr = service.renewCert(trans,mapper.toRenew(trans,request)); + Result rc = mapper.toCert(trans, rcr, withTrust); + + switch(rc.status) { + case OK: + RosettaData data = certDF.newData(trans).load(rc.value); + data.to(resp.getOutputStream()); + + setContentType(resp,certDF.getOutType()); + return Result.ok(); + default: + return Result.err(rc); + } + } catch (Exception e) { + trans.error().log(e,IN,RENEW_CERT); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result dropCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DROP_CERT, Env.SUB|Env.ALWAYS); + try { + REQ request; + try { + Data rd = certDropDF.newData().load(req.getInputStream()); + request = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DROP_CERT); + return Result.err(Result.ERR_BadData,"Invalid Input"); + } + + Result rv = service.dropCert(trans,mapper.toDrop(trans, request)); + switch(rv.status) { + case OK: + setContentType(resp,certRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rv); + } + } catch (Exception e) { + trans.error().log(e,IN,DROP_CERT); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.facade.Facade#readCertsByMechID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result readCertsByMechID(AuthzTrans trans, HttpServletResponse resp, String mechID) { + TimeTaken tt = trans.start(READ_CERTS_MECHID, Env.SUB|Env.ALWAYS); + try { + Result rc = mapper.toCert(trans, service.readCertsByMechID(trans,mechID)); + switch(rc.status) { + case OK: + RosettaData data = certDF.newData(trans).load(rc.value); + data.to(resp.getOutputStream()); + + setContentType(resp,certDF.getOutType()); + return Result.ok(); + default: + return Result.err(rc); + } + } catch (Exception e) { + trans.error().log(e,IN,READ_CERTS_MECHID); + return Result.err(e); + } finally { + tt.done(); + } + } + + //////////////////////////// + // Artifacts + //////////////////////////// + @Override + public Result createArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_ARTIFACTS, Env.SUB); + try { + ARTIFACTS arti; + try { + Data rd = artiDF.newData().load(req.getInputStream()); + arti = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_ARTIFACTS); + return Result.err(Result.ERR_BadData,"Invalid Input"); + } + + return service.createArtifact(trans,mapper.toArtifact(trans,arti)); + } catch (Exception e) { + + trans.error().log(e,IN,CREATE_ARTIFACTS); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result readArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(READ_ARTIFACTS, Env.SUB); + try { + String mechid = req.getParameter("mechid"); + String machine = req.getParameter("machine"); + String ns = req.getParameter("ns"); + + Result ra; + if( machine !=null && mechid == null) { + ra = mapper.fromArtifacts(service.readArtifactsByMachine(trans, machine)); + } else if(mechid!=null && machine==null) { + ra = mapper.fromArtifacts(service.readArtifactsByMechID(trans, mechid)); + } else if(mechid!=null && machine!=null) { + ArtiDAO.Data add = new ArtiDAO.Data(); + add.mechid = mechid; + add.machine = machine; + add.ns = ns; + ra = mapper.fromArtifacts(service.readArtifacts(trans,add)); + } else if(ns!=null) { + ra = mapper.fromArtifacts(service.readArtifactsByNs(trans, ns)); + } else { + ra = Result.err(Status.ERR_BadData,"Invalid request inputs"); + } + + if(ra.isOK()) { + RosettaData data = artiDF.newData(trans).load(ra.value); + data.to(resp.getOutputStream()); + setContentType(resp,artiDF.getOutType()); + return Result.ok(); + } else { + return Result.err(ra); + } + + } catch (Exception e) { + trans.error().log(e,IN,READ_ARTIFACTS); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result readArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine) { + TimeTaken tt = trans.start(READ_ARTIFACTS, Env.SUB); + try { + ArtiDAO.Data add = new ArtiDAO.Data(); + add.mechid = mechid; + add.machine = machine; + Result ra = mapper.fromArtifacts(service.readArtifacts(trans,add)); + if(ra.isOK()) { + RosettaData data = artiDF.newData(trans).load(ra.value); + data.to(resp.getOutputStream()); + setContentType(resp,artiDF.getOutType()); + return Result.ok(); + } else { + return Result.err(ra); + } + } catch (Exception e) { + trans.error().log(e,IN,READ_ARTIFACTS); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result updateArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_ARTIFACTS, Env.SUB); + try { + ARTIFACTS arti; + try { + Data rd = artiDF.newData().load(req.getInputStream()); + arti = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_ARTIFACTS); + return Result.err(Result.ERR_BadData,"Invalid Input"); + } + + return service.updateArtifact(trans,mapper.toArtifact(trans,arti)); + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_ARTIFACTS); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteArtifacts(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_ARTIFACTS, Env.SUB); + try { + ARTIFACTS arti; + try { + Data rd = artiDF.newData().load(req.getInputStream()); + arti = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_ARTIFACTS); + return Result.err(Result.ERR_BadData,"Invalid Input"); + } + + Result rv = service.deleteArtifact(trans,mapper.toArtifact(trans,arti)); + switch(rv.status) { + case OK: + setContentType(resp,artiDF.getOutType()); + } + return rv; + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ARTIFACTS); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteArtifacts(AuthzTrans trans, HttpServletResponse resp, String mechid, String machine) { + TimeTaken tt = trans.start(DELETE_ARTIFACTS, Env.SUB); + try { + Result rv = service.deleteArtifact(trans, mechid, machine); + switch(rv.status) { + case OK: + setContentType(resp,artiDF.getOutType()); + } + return rv; + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ARTIFACTS); + return Result.err(e); + } finally { + tt.done(); + } + } } \ No newline at end of file diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper.java index aadb6650..7328f099 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper.java @@ -35,20 +35,20 @@ import org.onap.aaf.auth.layer.Result; public interface Mapper { - public enum API{ERROR,VOID,CERT,CERT_REQ,CERT_RENEW,CERT_DROP,ARTIFACTS}; - - public Class getClass(API api); - public A newInstance(API api); + public enum API{ERROR,VOID,CERT,CERT_REQ,CERT_RENEW,CERT_DROP,ARTIFACTS}; + + public Class getClass(API api); + public A newInstance(API api); - public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); - - public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException; - public Result toCert(AuthzTrans trans, Result> in); + public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); + + public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException; + public Result toCert(AuthzTrans trans, Result> in); - public Result toReq(AuthzTrans trans, REQ req); - public Result toRenew(AuthzTrans trans, REQ req); - public Result toDrop(AuthzTrans trans, REQ req); - - public List toArtifact(AuthzTrans trans, ARTIFACTS arti); - public Result fromArtifacts(Result> readArtifactsByMachine); + public Result toReq(AuthzTrans trans, REQ req); + public Result toRenew(AuthzTrans trans, REQ req); + public Result toDrop(AuthzTrans trans, REQ req); + + public List toArtifact(AuthzTrans trans, ARTIFACTS arti); + public Result fromArtifacts(Result> readArtifactsByMachine); } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java index c06734f4..53b97626 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java @@ -49,234 +49,234 @@ import certman.v1_0.CertificateRequest; public class Mapper1_0 implements Mapper { - - @Override - public Class getClass(API api) { - switch(api) { - case CERT_REQ: return CertificateRequest.class; - case CERT_RENEW: return CertificateRenew.class; - case CERT_DROP: return CertificateDrop.class; - case CERT: return CertInfo.class; - case ARTIFACTS: return Artifacts.class; - case ERROR: return Error.class; - case VOID: return Void.class; - } - return null; - } + + @Override + public Class getClass(API api) { + switch(api) { + case CERT_REQ: return CertificateRequest.class; + case CERT_RENEW: return CertificateRenew.class; + case CERT_DROP: return CertificateDrop.class; + case CERT: return CertInfo.class; + case ARTIFACTS: return Artifacts.class; + case ERROR: return Error.class; + case VOID: return Void.class; + } + return null; + } - @SuppressWarnings("unchecked") - @Override - public A newInstance(API api) { - switch(api) { - case CERT_REQ: return (A) new CertificateRequest(); - case CERT_RENEW: return (A) new CertificateRenew(); - case CERT_DROP: return (A) new CertificateDrop(); - case CERT: return (A) new CertInfo(); - case ARTIFACTS: return (A) new Artifacts(); - case ERROR: return (A)new Error(); - case VOID: return null; - } - return null; - } + @SuppressWarnings("unchecked") + @Override + public A newInstance(API api) { + switch(api) { + case CERT_REQ: return (A) new CertificateRequest(); + case CERT_RENEW: return (A) new CertificateRenew(); + case CERT_DROP: return (A) new CertificateDrop(); + case CERT: return (A) new CertInfo(); + case ARTIFACTS: return (A) new Artifacts(); + case ERROR: return (A)new Error(); + case VOID: return null; + } + return null; + } - ////////////// Mapping Functions ///////////// - @Override - public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { - Error err = new Error(); - err.setMessageId(msgID); - // AT&T Restful Error Format requires numbers "%" placements - err.setText(Vars.convert(holder, text, var)); - for(String s : var) { - err.getVariables().add(s); - } - return err; - } + ////////////// Mapping Functions ///////////// + @Override + public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { + Error err = new Error(); + err.setMessageId(msgID); + // AT&T Restful Error Format requires numbers "%" placements + err.setText(Vars.convert(holder, text, var)); + for(String s : var) { + err.getVariables().add(s); + } + return err; + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toCert(org.onap.aaf.auth.env.test.AuthzTrans, org.onap.aaf.auth.layer.test.Result) - */ - @Override - public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException { - if(!in.isOK()) { - return Result.err(in); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toCert(org.onap.aaf.auth.env.test.AuthzTrans, org.onap.aaf.auth.layer.test.Result) + */ + @Override + public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException { + if(!in.isOK()) { + return Result.err(in); + } - CertResp cin = in.value; - CertInfo cout = newInstance(API.CERT); - cout.setPrivatekey(cin.privateString()); - String value; - if((value=cin.challenge())!=null) { - cout.setChallenge(value); - } - // In Version 1, Cert is always first - cout.getCerts().add(cin.asCertString()); - // Follow with Trust Chain - if(cin.trustChain()!=null) { - for(String c : cin.trustChain()) { - if(c!=null) { - cout.getCerts().add(c); - } - } - } + CertResp cin = in.value; + CertInfo cout = newInstance(API.CERT); + cout.setPrivatekey(cin.privateString()); + String value; + if((value=cin.challenge())!=null) { + cout.setChallenge(value); + } + // In Version 1, Cert is always first + cout.getCerts().add(cin.asCertString()); + // Follow with Trust Chain + if(cin.trustChain()!=null) { + for(String c : cin.trustChain()) { + if(c!=null) { + cout.getCerts().add(c); + } + } + } - // Adding all the Certs in one response is a mistake. Makes it very hard for Agent to setup - // Certs in keystore versus Truststore. Separate in Version 2_0 - if(cin.trustCAs()!=null) { - for(String c : cin.trustCAs()) { - if(c!=null) { - if(!cout.getCerts().contains(c)) { - cout.getCerts().add(c); - } - } - } - } - if(cin.notes()!=null) { - boolean first = true; - StringBuilder sb = new StringBuilder(); - for(String n : cin.notes()) { - if(first) { - first = false; - } else { - sb.append('\n'); - } - sb.append(n); - } - cout.setNotes(sb.toString()); - } - List caIssuerDNs = cout.getCaIssuerDNs(); - for(String s : cin.caIssuerDNs()) { - caIssuerDNs.add(s); - } - cout.setEnv(cin.env()); - return Result.ok(cout); + // Adding all the Certs in one response is a mistake. Makes it very hard for Agent to setup + // Certs in keystore versus Truststore. Separate in Version 2_0 + if(cin.trustCAs()!=null) { + for(String c : cin.trustCAs()) { + if(c!=null) { + if(!cout.getCerts().contains(c)) { + cout.getCerts().add(c); + } + } + } + } + if(cin.notes()!=null) { + boolean first = true; + StringBuilder sb = new StringBuilder(); + for(String n : cin.notes()) { + if(first) { + first = false; + } else { + sb.append('\n'); + } + sb.append(n); + } + cout.setNotes(sb.toString()); + } + List caIssuerDNs = cout.getCaIssuerDNs(); + for(String s : cin.caIssuerDNs()) { + caIssuerDNs.add(s); + } + cout.setEnv(cin.env()); + return Result.ok(cout); - } + } - @Override - public Result toCert(AuthzTrans trans, Result> in) { - if(in.isOK()) { - CertInfo cout = newInstance(API.CERT); - List certs = cout.getCerts(); - for(CertDAO.Data cdd : in.value) { - certs.add(cdd.x509); - } - return Result.ok(cout); - } else { - return Result.err(in); - } - } + @Override + public Result toCert(AuthzTrans trans, Result> in) { + if(in.isOK()) { + CertInfo cout = newInstance(API.CERT); + List certs = cout.getCerts(); + for(CertDAO.Data cdd : in.value) { + certs.add(cdd.x509); + } + return Result.ok(cout); + } else { + return Result.err(in); + } + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toReq(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result toReq(AuthzTrans trans, BaseRequest req) { - CertificateRequest in; - try { - in = (CertificateRequest)req; - } catch(ClassCastException e) { - return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toReq(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result toReq(AuthzTrans trans, BaseRequest req) { + CertificateRequest in; + try { + in = (CertificateRequest)req; + } catch(ClassCastException e) { + return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); + } - CertReq out = new CertReq(); - CertmanValidator v = new CertmanValidator(); - out.mechid=in.getMechid(); - out.fqdns=in.getFqdns(); - v.isNull("CertRequest", req).nullOrBlank("MechID", out.mechid); - v.nullBlankMin("FQDNs", out.fqdns,1); - if(v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - out.emails = in.getEmail(); - out.sponsor=in.getSponsor(); - out.start = in.getStart(); - out.end = in.getEnd(); - out.fqdns = in.getFqdns(); - return Result.ok(out); - } + CertReq out = new CertReq(); + CertmanValidator v = new CertmanValidator(); + out.mechid=in.getMechid(); + out.fqdns=in.getFqdns(); + v.isNull("CertRequest", req).nullOrBlank("MechID", out.mechid); + v.nullBlankMin("FQDNs", out.fqdns,1); + if(v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + out.emails = in.getEmail(); + out.sponsor=in.getSponsor(); + out.start = in.getStart(); + out.end = in.getEnd(); + out.fqdns = in.getFqdns(); + return Result.ok(out); + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toRenew(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result toRenew(AuthzTrans trans, BaseRequest req) { - return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toRenew(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result toRenew(AuthzTrans trans, BaseRequest req) { + return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toDrop(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result toDrop(AuthzTrans trans, BaseRequest req) { - return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toDrop(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result toDrop(AuthzTrans trans, BaseRequest req) { + return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.cm.mapper.Mapper#toArtifact(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public List toArtifact(AuthzTrans trans, Artifacts artifacts) { - List ladd = new ArrayList<>(); - for(Artifact arti : artifacts.getArtifact()) { - ArtiDAO.Data data = new ArtiDAO.Data(); - data.mechid = arti.getMechid(); - data.machine = arti.getMachine(); - data.type(true).addAll(arti.getType()); - data.ca = arti.getCa(); - data.dir = arti.getDir(); - data.os_user = arti.getOsUser(); - // Optional (on way in) - data.ns = arti.getNs(); - data.renewDays = arti.getRenewDays(); - data.notify = arti.getNotification(); - - // Ignored on way in for create/update - data.sponsor = arti.getSponsor(); - data.expires = null; - - // Derive Optional Data from Machine (Domain) if exists - if(data.machine!=null) { - if(data.ca==null && data.machine.endsWith(".att.com")) { - data.ca = "aaf"; // default - } - if(data.ns==null ) { - data.ns=FQI.reverseDomain(data.machine); - } - } - data.sans(true).addAll(arti.getSans()); - ladd.add(data); - } - return ladd; - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.mapper.Mapper#toArtifact(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public List toArtifact(AuthzTrans trans, Artifacts artifacts) { + List ladd = new ArrayList<>(); + for(Artifact arti : artifacts.getArtifact()) { + ArtiDAO.Data data = new ArtiDAO.Data(); + data.mechid = arti.getMechid(); + data.machine = arti.getMachine(); + data.type(true).addAll(arti.getType()); + data.ca = arti.getCa(); + data.dir = arti.getDir(); + data.os_user = arti.getOsUser(); + // Optional (on way in) + data.ns = arti.getNs(); + data.renewDays = arti.getRenewDays(); + data.notify = arti.getNotification(); + + // Ignored on way in for create/update + data.sponsor = arti.getSponsor(); + data.expires = null; + + // Derive Optional Data from Machine (Domain) if exists + if(data.machine!=null) { + if(data.ca==null && data.machine.endsWith(".att.com")) { + data.ca = "aaf"; // default + } + if(data.ns==null ) { + data.ns=FQI.reverseDomain(data.machine); + } + } + data.sans(true).addAll(arti.getSans()); + ladd.add(data); + } + return ladd; + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.cm.mapper.Mapper#fromArtifacts(org.onap.aaf.auth.layer.test.Result) - */ - @Override - public Result fromArtifacts(Result> lArtiDAO) { - if(lArtiDAO.isOK()) { - Artifacts artis = new Artifacts(); - for(ArtiDAO.Data arti : lArtiDAO.value) { - Artifact a = new Artifact(); - a.setMechid(arti.mechid); - a.setMachine(arti.machine); - a.setSponsor(arti.sponsor); - a.setNs(arti.ns); - a.setCa(arti.ca); - a.setDir(arti.dir); - a.getType().addAll(arti.type(false)); - a.setOsUser(arti.os_user); - a.setRenewDays(arti.renewDays); - a.setNotification(arti.notify); - a.getSans().addAll(arti.sans(false)); - artis.getArtifact().add(a); - } - return Result.ok(artis); - } else { - return Result.err(lArtiDAO); - } - } - - + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.mapper.Mapper#fromArtifacts(org.onap.aaf.auth.layer.test.Result) + */ + @Override + public Result fromArtifacts(Result> lArtiDAO) { + if(lArtiDAO.isOK()) { + Artifacts artis = new Artifacts(); + for(ArtiDAO.Data arti : lArtiDAO.value) { + Artifact a = new Artifact(); + a.setMechid(arti.mechid); + a.setMachine(arti.machine); + a.setSponsor(arti.sponsor); + a.setNs(arti.ns); + a.setCa(arti.ca); + a.setDir(arti.dir); + a.getType().addAll(arti.type(false)); + a.setOsUser(arti.os_user); + a.setRenewDays(arti.renewDays); + a.setNotification(arti.notify); + a.getSans().addAll(arti.sans(false)); + artis.getArtifact().add(a); + } + return Result.ok(artis); + } else { + return Result.err(lArtiDAO); + } + } + + } \ No newline at end of file diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java index 23a0c543..d85ea2ca 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java @@ -49,225 +49,225 @@ import certman.v1_0.CertificateRequest; public class Mapper2_0 implements Mapper { - - @Override - public Class getClass(API api) { - switch(api) { - case CERT_REQ: return CertificateRequest.class; - case CERT_RENEW: return CertificateRenew.class; - case CERT_DROP: return CertificateDrop.class; - case CERT: return CertInfo.class; - case ARTIFACTS: return Artifacts.class; - case ERROR: return Error.class; - case VOID: return Void.class; - } - return null; - } + + @Override + public Class getClass(API api) { + switch(api) { + case CERT_REQ: return CertificateRequest.class; + case CERT_RENEW: return CertificateRenew.class; + case CERT_DROP: return CertificateDrop.class; + case CERT: return CertInfo.class; + case ARTIFACTS: return Artifacts.class; + case ERROR: return Error.class; + case VOID: return Void.class; + } + return null; + } - @SuppressWarnings("unchecked") - @Override - public A newInstance(API api) { - switch(api) { - case CERT_REQ: return (A) new CertificateRequest(); - case CERT_RENEW: return (A) new CertificateRenew(); - case CERT_DROP: return (A) new CertificateDrop(); - case CERT: return (A) new CertInfo(); - case ARTIFACTS: return (A) new Artifacts(); - case ERROR: return (A)new Error(); - case VOID: return null; - } - return null; - } + @SuppressWarnings("unchecked") + @Override + public A newInstance(API api) { + switch(api) { + case CERT_REQ: return (A) new CertificateRequest(); + case CERT_RENEW: return (A) new CertificateRenew(); + case CERT_DROP: return (A) new CertificateDrop(); + case CERT: return (A) new CertInfo(); + case ARTIFACTS: return (A) new Artifacts(); + case ERROR: return (A)new Error(); + case VOID: return null; + } + return null; + } - ////////////// Mapping Functions ///////////// - @Override - public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { - Error err = new Error(); - err.setMessageId(msgID); - // AT&T Restful Error Format requires numbers "%" placements - err.setText(Vars.convert(holder, text, var)); - for(String s : var) { - err.getVariables().add(s); - } - return err; - } + ////////////// Mapping Functions ///////////// + @Override + public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { + Error err = new Error(); + err.setMessageId(msgID); + // AT&T Restful Error Format requires numbers "%" placements + err.setText(Vars.convert(holder, text, var)); + for(String s : var) { + err.getVariables().add(s); + } + return err; + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toCert(org.onap.aaf.auth.env.test.AuthzTrans, org.onap.aaf.auth.layer.test.Result) - */ - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toCert(org.onap.aaf.auth.env.test.AuthzTrans, org.onap.aaf.auth.layer.test.Result) - */ - @Override - public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException { - if(!in.isOK()) { - CertResp cin = in.value; - CertInfo cout = newInstance(API.CERT); - cout.setPrivatekey(cin.privateString()); - String value; - if((value=cin.challenge())!=null) { - cout.setChallenge(value); - } - cout.getCerts().add(cin.asCertString()); - if(cin.trustChain()!=null) { - for(String c : cin.trustChain()) { - cout.getCerts().add(c); - } - } - if(cin.notes()!=null) { - boolean first = true; - StringBuilder sb = new StringBuilder(); - for(String n : cin.notes()) { - if(first) { - first = false; - } else { - sb.append('\n'); - } - sb.append(n); - } - cout.setNotes(sb.toString()); - } - - List caIssuerDNs = cout.getCaIssuerDNs(); - for(String s : cin.caIssuerDNs()) { - caIssuerDNs.add(s); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toCert(org.onap.aaf.auth.env.test.AuthzTrans, org.onap.aaf.auth.layer.test.Result) + */ + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toCert(org.onap.aaf.auth.env.test.AuthzTrans, org.onap.aaf.auth.layer.test.Result) + */ + @Override + public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException { + if(!in.isOK()) { + CertResp cin = in.value; + CertInfo cout = newInstance(API.CERT); + cout.setPrivatekey(cin.privateString()); + String value; + if((value=cin.challenge())!=null) { + cout.setChallenge(value); + } + cout.getCerts().add(cin.asCertString()); + if(cin.trustChain()!=null) { + for(String c : cin.trustChain()) { + cout.getCerts().add(c); + } + } + if(cin.notes()!=null) { + boolean first = true; + StringBuilder sb = new StringBuilder(); + for(String n : cin.notes()) { + if(first) { + first = false; + } else { + sb.append('\n'); + } + sb.append(n); + } + cout.setNotes(sb.toString()); + } + + List caIssuerDNs = cout.getCaIssuerDNs(); + for(String s : cin.caIssuerDNs()) { + caIssuerDNs.add(s); + } - cout.setEnv(cin.env()); - return Result.ok(cout); - } else { - return Result.err(in); - } - } + cout.setEnv(cin.env()); + return Result.ok(cout); + } else { + return Result.err(in); + } + } - @Override - public Result toCert(AuthzTrans trans, Result> in) { - if(in.isOK()) { - CertInfo cout = newInstance(API.CERT); - List certs = cout.getCerts(); - for(CertDAO.Data cdd : in.value) { - certs.add(cdd.x509); - } - return Result.ok(cout); - } else { - return Result.err(in); - } - } + @Override + public Result toCert(AuthzTrans trans, Result> in) { + if(in.isOK()) { + CertInfo cout = newInstance(API.CERT); + List certs = cout.getCerts(); + for(CertDAO.Data cdd : in.value) { + certs.add(cdd.x509); + } + return Result.ok(cout); + } else { + return Result.err(in); + } + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toReq(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result toReq(AuthzTrans trans, BaseRequest req) { - CertificateRequest in; - try { - in = (CertificateRequest)req; - } catch(ClassCastException e) { - return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toReq(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result toReq(AuthzTrans trans, BaseRequest req) { + CertificateRequest in; + try { + in = (CertificateRequest)req; + } catch(ClassCastException e) { + return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); + } - CertReq out = new CertReq(); - CertmanValidator v = new CertmanValidator(); - v.isNull("CertRequest", req) - .nullOrBlank("MechID", out.mechid=in.getMechid()); - v.nullBlankMin("FQDNs", out.fqdns=in.getFqdns(),1); - if(v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } + CertReq out = new CertReq(); + CertmanValidator v = new CertmanValidator(); + v.isNull("CertRequest", req) + .nullOrBlank("MechID", out.mechid=in.getMechid()); + v.nullBlankMin("FQDNs", out.fqdns=in.getFqdns(),1); + if(v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } - out.emails = in.getEmail(); - out.sponsor=in.getSponsor(); - out.start = in.getStart(); - out.end = in.getEnd(); - out.fqdns = in.getFqdns(); - return Result.ok(out); - } + out.emails = in.getEmail(); + out.sponsor=in.getSponsor(); + out.start = in.getStart(); + out.end = in.getEnd(); + out.fqdns = in.getFqdns(); + return Result.ok(out); + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toRenew(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result toRenew(AuthzTrans trans, BaseRequest req) { - return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toRenew(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result toRenew(AuthzTrans trans, BaseRequest req) { + return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); + } - /* (non-Javadoc) - * @see com.att.authz.certman.mapper.Mapper#toDrop(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result toDrop(AuthzTrans trans, BaseRequest req) { - return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); - } + /* (non-Javadoc) + * @see com.att.authz.certman.mapper.Mapper#toDrop(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result toDrop(AuthzTrans trans, BaseRequest req) { + return Result.err(Result.ERR_NotImplemented,"Not Implemented... yet"); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.cm.mapper.Mapper#toArtifact(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public List toArtifact(AuthzTrans trans, Artifacts artifacts) { - List ladd = new ArrayList<>(); - for(Artifact arti : artifacts.getArtifact()) { - ArtiDAO.Data data = new ArtiDAO.Data(); - data.mechid = arti.getMechid(); - data.machine = arti.getMachine(); - data.type(true).addAll(arti.getType()); - data.ca = arti.getCa(); - data.dir = arti.getDir(); - data.os_user = arti.getOsUser(); - // Optional (on way in) - data.ns = arti.getNs(); - data.renewDays = arti.getRenewDays(); - data.notify = arti.getNotification(); - - // Ignored on way in for create/update - data.sponsor = arti.getSponsor(); - data.expires = null; - - // Derive Optional Data from Machine (Domain) if exists - if(data.machine!=null) { - if(data.ca==null) { - if(data.machine.endsWith(".att.com")) { - data.ca = "aaf"; // default - } - } - if(data.ns==null ) { - data.ns=FQI.reverseDomain(data.machine); - } - } - data.sans(true).addAll(arti.getSans()); - ladd.add(data); - } - return ladd; - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.mapper.Mapper#toArtifact(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public List toArtifact(AuthzTrans trans, Artifacts artifacts) { + List ladd = new ArrayList<>(); + for(Artifact arti : artifacts.getArtifact()) { + ArtiDAO.Data data = new ArtiDAO.Data(); + data.mechid = arti.getMechid(); + data.machine = arti.getMachine(); + data.type(true).addAll(arti.getType()); + data.ca = arti.getCa(); + data.dir = arti.getDir(); + data.os_user = arti.getOsUser(); + // Optional (on way in) + data.ns = arti.getNs(); + data.renewDays = arti.getRenewDays(); + data.notify = arti.getNotification(); + + // Ignored on way in for create/update + data.sponsor = arti.getSponsor(); + data.expires = null; + + // Derive Optional Data from Machine (Domain) if exists + if(data.machine!=null) { + if(data.ca==null) { + if(data.machine.endsWith(".att.com")) { + data.ca = "aaf"; // default + } + } + if(data.ns==null ) { + data.ns=FQI.reverseDomain(data.machine); + } + } + data.sans(true).addAll(arti.getSans()); + ladd.add(data); + } + return ladd; + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.cm.mapper.Mapper#fromArtifacts(org.onap.aaf.auth.layer.test.Result) - */ - @Override - public Result fromArtifacts(Result> lArtiDAO) { - if(lArtiDAO.isOK()) { - Artifacts artis = new Artifacts(); - for(ArtiDAO.Data arti : lArtiDAO.value) { - Artifact a = new Artifact(); - a.setMechid(arti.mechid); - a.setMachine(arti.machine); - a.setSponsor(arti.sponsor); - a.setNs(arti.ns); - a.setCa(arti.ca); - a.setDir(arti.dir); - a.getType().addAll(arti.type(false)); - a.setOsUser(arti.os_user); - a.setRenewDays(arti.renewDays); - a.setNotification(arti.notify); - a.getSans().addAll(arti.sans(false)); - artis.getArtifact().add(a); - } - return Result.ok(artis); - } else { - return Result.err(lArtiDAO); - } - } - - + /* (non-Javadoc) + * @see org.onap.aaf.auth.cm.mapper.Mapper#fromArtifacts(org.onap.aaf.auth.layer.test.Result) + */ + @Override + public Result fromArtifacts(Result> lArtiDAO) { + if(lArtiDAO.isOK()) { + Artifacts artis = new Artifacts(); + for(ArtiDAO.Data arti : lArtiDAO.value) { + Artifact a = new Artifact(); + a.setMechid(arti.mechid); + a.setMachine(arti.machine); + a.setSponsor(arti.sponsor); + a.setNs(arti.ns); + a.setCa(arti.ca); + a.setDir(arti.dir); + a.getType().addAll(arti.type(false)); + a.setOsUser(arti.os_user); + a.setRenewDays(arti.renewDays); + a.setNotification(arti.notify); + a.getSans().addAll(arti.sans(false)); + artis.getArtifact().add(a); + } + return Result.ok(artis); + } else { + return Result.err(lArtiDAO); + } + } + + } \ No newline at end of file diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java index 259dfac9..62f0d680 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java @@ -67,632 +67,632 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.util.Chrono; public class CMService { - // If we add more CAs, may want to parameterize - private static final int STD_RENEWAL = 30; - private static final int MAX_RENEWAL = 60; - private static final int MIN_RENEWAL = 10; - - public static final String REQUEST = "request"; - public static final String IGNORE_IPS = "ignoreIPs"; - public static final String RENEW = "renew"; - public static final String DROP = "drop"; - public static final String DOMAIN = "domain"; - - private static final String CERTMAN = "certman"; - private static final String ACCESS = "access"; - - private static final String[] NO_NOTES = new String[0]; - private final Permission root_read_permission; - private final CertDAO certDAO; - private final CredDAO credDAO; - private final ArtiDAO artiDAO; - private AAF_CM certman; - - // @SuppressWarnings("unchecked") - public CMService(final AuthzTrans trans, AAF_CM certman) throws APIException, IOException { - // Jonathan 4/2015 SessionFilter unneeded... DataStax already deals with - // Multithreading well - - HistoryDAO hd = new HistoryDAO(trans, certman.cluster, CassAccess.KEYSPACE); - CacheInfoDAO cid = new CacheInfoDAO(trans, hd); - certDAO = new CertDAO(trans, hd, cid); - credDAO = new CredDAO(trans, hd, cid); - artiDAO = new ArtiDAO(trans, hd, cid); - - this.certman = certman; - - root_read_permission=new AAFPermission( - trans.getProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF), - "access", - "*", - "read" - ); - } - - public Result requestCert(final AuthzTrans trans, final Result req, final CA ca) { - if (req.isOK()) { - - if (req.value.fqdns.isEmpty()) { - return Result.err(Result.ERR_BadData, "No Machines passed in Request"); - } - - String key = req.value.fqdns.get(0); - - // Policy 6: Requester must be granted Change permission in Namespace requested - String mechNS = FQI.reverseDomain(req.value.mechid); - if (mechNS == null) { - return Result.err(Status.ERR_Denied, "%s does not reflect a valid AAF Namespace", req.value.mechid); - } - - List notes = null; - List fqdns = new ArrayList<>(req.value.fqdns); - - String email = null; - - try { - Organization org = trans.org(); - - boolean ignoreIPs = trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), IGNORE_IPS)); - - InetAddress primary = null; - // Organize incoming information to get to appropriate Artifact - if (!fqdns.isEmpty()) { - // Accept domain wild cards, but turn into real machines - // Need *domain.com:real.machine.domain.com:san.machine.domain.com:... - if (fqdns.get(0).startsWith("*")) { // Domain set - if (!trans.fish(new AAFPermission(null,ca.getPermType(), ca.getName(), DOMAIN))) { - return Result.err(Result.ERR_Denied, - "Domain based Authorizations (" + fqdns.get(0) + ") requires Exception"); - } - - // TODO check for Permission in Add Artifact? - String domain = fqdns.get(0).substring(1); - fqdns.remove(0); - if (fqdns.isEmpty()) { - return Result.err(Result.ERR_Denied, "Requests using domain require machine declaration"); - } - - if (!ignoreIPs) { - InetAddress ia = InetAddress.getByName(fqdns.get(0)); - if (ia == null) { - return Result.err(Result.ERR_Denied, - "Request not made from matching IP matching domain"); - } else if (ia.getHostName().endsWith(domain)) { - primary = ia; - } - } - - } else { - for (String cn : req.value.fqdns) { - if(!ignoreIPs) { - try { - InetAddress[] ias = InetAddress.getAllByName(cn); - Set potentialSanNames = new HashSet<>(); - for (InetAddress ia1 : ias) { - InetAddress ia2 = InetAddress.getByAddress(ia1.getAddress()); - if (primary == null && ias.length == 1 && trans.ip().equals(ia1.getHostAddress())) { - primary = ia1; - } else if (!cn.equals(ia1.getHostName()) - && !ia2.getHostName().equals(ia2.getHostAddress())) { - potentialSanNames.add(ia1.getHostName()); - } - } - } catch (UnknownHostException e1) { - return Result.err(Result.ERR_BadData, "There is no DNS lookup for %s", cn); - } - } - } - } - } - - final String host; - if(ignoreIPs) { - host = req.value.fqdns.get(0); - } else if (primary == null) { - return Result.err(Result.ERR_Denied, "Request not made from matching IP (%s)", trans.ip()); - } else { - host = primary.getHostAddress(); - } - - ArtiDAO.Data add = null; - Result> ra = artiDAO.read(trans, req.value.mechid, host); - if (ra.isOKhasData()) { - if (add == null) { - add = ra.value.get(0); // single key - } - } else { - ra = artiDAO.read(trans, req.value.mechid, key); - if (ra.isOKhasData()) { // is the Template available? - add = ra.value.get(0); - add.machine = host; - for (String s : fqdns) { - if (!s.equals(add.machine)) { - add.sans(true).add(s); - } - } - Result rc = artiDAO.create(trans, add); // Create new Artifact from Template - if (rc.notOK()) { - return Result.err(rc); - } - } else { - add = ra.value.get(0); - } - } - - // Add Artifact listed FQDNs - if (add.sans != null) { - for (String s : add.sans) { - if (!fqdns.contains(s)) { - fqdns.add(s); - } - } - } - - // Policy 2: If Config marked as Expired, do not create or renew - Date now = new Date(); - if (add.expires != null && now.after(add.expires)) { - return Result.err(Result.ERR_Policy, "Configuration for %s %s is expired %s", add.mechid, - add.machine, Chrono.dateFmt.format(add.expires)); - } - - // Policy 3: MechID must be current - Identity muser = org.getIdentity(trans, add.mechid); - if (muser == null) { - return Result.err(Result.ERR_Policy, "MechID must exist in %s", org.getName()); - } - - // Policy 4: Sponsor must be current - Identity ouser = muser.responsibleTo(); - if (ouser == null) { - return Result.err(Result.ERR_Policy, "%s does not have a current sponsor at %s", add.mechid, - org.getName()); - } else if (!ouser.isFound() || ouser.mayOwn() != null) { - return Result.err(Result.ERR_Policy, "%s reports that %s cannot be responsible for %s", - org.getName(), trans.user()); - } - - // Set Email from most current Sponsor - email = ouser.email(); - - // Policy 5: keep Artifact data current - if (!ouser.fullID().equals(add.sponsor)) { - add.sponsor = ouser.fullID(); - artiDAO.update(trans, add); - } - - // Policy 7: Caller must be the MechID or have specifically delegated - // permissions - if (!(trans.user().equals(req.value.mechid) - || trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), REQUEST)))) { - return Result.err(Status.ERR_Denied, "%s must have access to modify x509 certs in NS %s", - trans.user(), mechNS); - } - - // Make sure Primary is the first in fqdns - if (fqdns.size() > 1) { - for (int i = 0; i < fqdns.size(); ++i) { - if(primary==null) { - trans.error().log("CMService var primary is null"); - } else { - String fg = fqdns.get(i); - if (fg!=null && fg.equals(primary.getHostName())) { - if (i != 0) { - String tmp = fqdns.get(0); - fqdns.set(0, primary.getHostName()); - fqdns.set(i, tmp); - } - } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - trans.error().log(e); - return Result.err(Status.ERR_Denied, - "AppID Sponsorship cannot be determined at this time. Try later."); - } - - CSRMeta csrMeta; - try { - csrMeta = BCFactory.createCSRMeta(ca, req.value.mechid, email, fqdns); - X509andChain x509ac = ca.sign(trans, csrMeta); - if (x509ac == null) { - return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA"); - } - trans.info().printf("X509 Subject: %s", x509ac.getX509().getSubjectDN()); - - X509Certificate x509 = x509ac.getX509(); - CertDAO.Data cdd = new CertDAO.Data(); - cdd.ca = ca.getName(); - cdd.serial = x509.getSerialNumber(); - cdd.id = req.value.mechid; - cdd.x500 = x509.getSubjectDN().getName(); - cdd.x509 = Factory.toString(trans, x509); - certDAO.create(trans, cdd); - - CredDAO.Data crdd = new CredDAO.Data(); - crdd.other = Question.random.nextInt(); - crdd.cred = getChallenge256SaltedHash(csrMeta.challenge(), crdd.other); - crdd.expires = x509.getNotAfter(); - crdd.id = req.value.mechid; - crdd.ns = Question.domain2ns(crdd.id); - crdd.type = CredDAO.CERT_SHA256_RSA; - credDAO.create(trans, crdd); - - CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(notes)); - return Result.ok(cr); - } catch (Exception e) { - trans.error().log(e); - return Result.err(Result.ERR_ActionNotCompleted, e.getMessage()); - } - } else { - return Result.err(req); - } - } - - public Result renewCert(AuthzTrans trans, Result renew) { - if (renew.isOK()) { - return Result.err(Result.ERR_NotImplemented, "Not implemented yet"); - } else { - return Result.err(renew); - } - } - - public Result dropCert(AuthzTrans trans, Result drop) { - if (drop.isOK()) { - return Result.err(Result.ERR_NotImplemented, "Not implemented yet"); - } else { - return Result.err(drop); - } - } - - public Result> readCertsByMechID(AuthzTrans trans, String mechID) { - // Policy 1: To Read, must have NS Read or is Sponsor - String ns = Question.domain2ns(mechID); - try { - if (trans.user().equals(mechID) || trans.fish(new AAFPermission(ns,ACCESS, "*", "read")) - || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechID)) == null) { - return certDAO.readID(trans, mechID); - } else { - return Result.err(Result.ERR_Denied, "%s is not the ID, Sponsor or NS Owner/Admin for %s at %s", - trans.user(), mechID, trans.org().getName()); - } - } catch (OrganizationException e) { - return Result.err(e); - } - } - - public Result requestPersonalCert(AuthzTrans trans, CA ca) { - if (ca.inPersonalDomains(trans.getUserPrincipal())) { - Organization org = trans.org(); - - // Policy 1: MechID must be current - Identity ouser; - try { - ouser = org.getIdentity(trans, trans.user()); - } catch (OrganizationException e1) { - trans.error().log(e1); - ouser = null; - } - if (ouser == null) { - return Result.err(Result.ERR_Policy, "Requesting User must exist in %s", org.getName()); - } - - // Set Email from most current Sponsor - - CSRMeta csrMeta; - try { - csrMeta = BCFactory.createPersonalCSRMeta(ca, trans.user(), ouser.email()); - X509andChain x509ac = ca.sign(trans, csrMeta); - if (x509ac == null) { - return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA"); - } - X509Certificate x509 = x509ac.getX509(); - CertDAO.Data cdd = new CertDAO.Data(); - cdd.ca = ca.getName(); - cdd.serial = x509.getSerialNumber(); - cdd.id = trans.user(); - cdd.x500 = x509.getSubjectDN().getName(); - cdd.x509 = Factory.toString(trans, x509); - certDAO.create(trans, cdd); - - CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(null)); - return Result.ok(cr); - } catch (Exception e) { - trans.error().log(e); - return Result.err(Result.ERR_ActionNotCompleted, e.getMessage()); - } - } else { - return Result.err(Result.ERR_Denied, trans.user(), " not supported for CA", ca.getName()); - } - } - - /////////////// - // Artifact - ////////////// - public Result createArtifact(AuthzTrans trans, List list) { - CertmanValidator v = new CertmanValidator().artisRequired(list, 1); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - for (ArtiDAO.Data add : list) { - try { - // Policy 1: MechID must exist in Org - Identity muser = trans.org().getIdentity(trans, add.mechid); - if (muser == null) { - return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName()); - } - - // Policy 2: MechID must have valid Organization Owner - Identity emailUser; - if (muser.isPerson()) { - emailUser = muser; - } else { - Identity ouser = muser.responsibleTo(); - if (ouser == null) { - return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(), - add.mechid, trans.org().getName()); - } - - // Policy 3: Calling ID must be MechID Owner - if (!trans.user().startsWith(ouser.id())) { - return Result.err(Result.ERR_Denied, "%s is not the Sponsor for %s at %s", trans.user(), - add.mechid, trans.org().getName()); - } - emailUser = ouser; - } - - // Policy 4: Renewal Days are between 10 and 60 (constants, may be - // parameterized) - if (add.renewDays < MIN_RENEWAL) { - add.renewDays = STD_RENEWAL; - } else if (add.renewDays > MAX_RENEWAL) { - add.renewDays = MAX_RENEWAL; - } - - // Policy 5: If Notify is blank, set to Owner's Email - if (add.notify == null || add.notify.length() == 0) { - add.notify = "mailto:" + emailUser.email(); - } - - // Policy 6: Only do Domain by Exception - if (add.machine.startsWith("*")) { // Domain set - CA ca = certman.getCA(add.ca); - - if (!trans.fish(new AAFPermission(ca.getPermNS(),ca.getPermType(), add.ca, DOMAIN))) { - return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission", - add.machine); - } - } - - // Set Sponsor from Golden Source - add.sponsor = emailUser.fullID(); - - } catch (OrganizationException e) { - return Result.err(e); - } - // Add to DB - Result rv = artiDAO.create(trans, add); - // TODO come up with Partial Reporting Scheme, or allow only one at a time. - if (rv.notOK()) { - return Result.err(rv); - } - } - return Result.ok(); - } - - public Result> readArtifacts(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException { - CertmanValidator v = new CertmanValidator().keys(add); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - Result> data = artiDAO.read(trans, add); - if (data.notOKorIsEmpty()) { - return data; - } - add = data.value.get(0); - if (trans.user().equals(add.mechid) - || trans.fish(root_read_permission, - new AAFPermission(add.ns,ACCESS, "*", "read"), - new AAFPermission(add.ns,CERTMAN, add.ca, "read"), - new AAFPermission(add.ns,CERTMAN, add.ca, "request")) - || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, add.mechid)) == null) { - return data; - } else { - return Result.err(Result.ERR_Denied, - "%s is not %s, is not the sponsor, and doesn't have delegated permission.", trans.user(), - add.mechid, add.ns + ".certman|" + add.ca + "|read or ...|request"); // note: reason is set by 2nd - // case, if 1st case misses - } - - } - - public Result> readArtifactsByMechID(AuthzTrans trans, String mechid) - throws OrganizationException { - CertmanValidator v = new CertmanValidator(); - v.nullOrBlank("mechid", mechid); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - String ns = FQI.reverseDomain(mechid); - - String reason; - if (trans.fish(new AAFPermission(ns, ACCESS, "*", "read")) - || (reason = trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechid)) == null) { - return artiDAO.readByMechID(trans, mechid); - } else { - return Result.err(Result.ERR_Denied, reason); // note: reason is set by 2nd case, if 1st case misses - } - - } - - public Result> readArtifactsByMachine(AuthzTrans trans, String machine) { - CertmanValidator v = new CertmanValidator(); - v.nullOrBlank("machine", machine); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - - // TODO do some checks? - - Result> rv = artiDAO.readByMachine(trans, machine); - return rv; - } - - public Result> readArtifactsByNs(AuthzTrans trans, String ns) { - CertmanValidator v = new CertmanValidator(); - v.nullOrBlank("ns", ns); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - - // TODO do some checks? - - return artiDAO.readByNs(trans, ns); - } - - public Result updateArtifact(AuthzTrans trans, List list) throws OrganizationException { - CertmanValidator v = new CertmanValidator(); - v.artisRequired(list, 1); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - - // Check if requesting User is Sponsor - // TODO - Shall we do one, or multiples? - for (ArtiDAO.Data add : list) { - // Policy 1: MechID must exist in Org - Identity muser = trans.org().getIdentity(trans, add.mechid); - if (muser == null) { - return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName()); - } - - // Policy 2: MechID must have valid Organization Owner - Identity ouser = muser.responsibleTo(); - if (ouser == null) { - return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(), add.mechid, - trans.org().getName()); - } - - // Policy 3: Renewal Days are between 10 and 60 (constants, may be - // parameterized) - if (add.renewDays < MIN_RENEWAL) { - add.renewDays = STD_RENEWAL; - } else if (add.renewDays > MAX_RENEWAL) { - add.renewDays = MAX_RENEWAL; - } - - // Policy 4: Data is always updated with the latest Sponsor - // Add to Sponsor, to make sure we are always up to date. - add.sponsor = ouser.fullID(); - - // Policy 5: If Notify is blank, set to Owner's Email - if (add.notify == null || add.notify.length() == 0) { - add.notify = "mailto:" + ouser.email(); - } - // Policy 6: Only do Domain by Exception - if (add.machine.startsWith("*")) { // Domain set - CA ca = certman.getCA(add.ca); - if (ca == null) { - return Result.err(Result.ERR_BadData, "CA is required in Artifact"); - } - if (!trans.fish(new AAFPermission(null,ca.getPermType(), add.ca, DOMAIN))) { - return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission", - add.machine); - } - } - - // Policy 7: only Owner may update info - if (trans.user().startsWith(ouser.id())) { - return artiDAO.update(trans, add); - } else { - return Result.err(Result.ERR_Denied, "%s may not update info for %s", trans.user(), muser.fullID()); - } - } - return Result.err(Result.ERR_BadData, "No Artifacts to update"); - } - - public Result deleteArtifact(AuthzTrans trans, String mechid, String machine) throws OrganizationException { - CertmanValidator v = new CertmanValidator(); - v.nullOrBlank("mechid", mechid).nullOrBlank("machine", machine); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - - Result> rlad = artiDAO.read(trans, mechid, machine); - if (rlad.notOKorIsEmpty()) { - return Result.err(Result.ERR_NotFound, "Artifact for %s %s does not exist.", mechid, machine); - } - - return deleteArtifact(trans, rlad.value.get(0)); - } - - private Result deleteArtifact(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException { - // Policy 1: Record should be delete able only by Existing Sponsor. - String sponsor = null; - Identity muser = trans.org().getIdentity(trans, add.mechid); - if (muser != null) { - Identity ouser = muser.responsibleTo(); - if (ouser != null) { - sponsor = ouser.fullID(); - } - } - // Policy 1.a: If Sponsorship is deleted in system of Record, then - // accept deletion by sponsor in Artifact Table - if (sponsor == null) { - sponsor = add.sponsor; - } - - String ns = FQI.reverseDomain(add.mechid); - - if (trans.fish(new AAFPermission(ns,ACCESS, "*", "write")) || trans.user().equals(sponsor)) { - return artiDAO.delete(trans, add, false); - } - return Result.err(Result.ERR_Denied, "%1 is not allowed to delete this item", trans.user()); - } - - public Result deleteArtifact(AuthzTrans trans, List list) { - CertmanValidator v = new CertmanValidator().artisRequired(list, 1); - if (v.err()) { - return Result.err(Result.ERR_BadData, v.errs()); - } - - try { - boolean partial = false; - Result result = null; - for (ArtiDAO.Data add : list) { - result = deleteArtifact(trans, add); - if (result.notOK()) { - partial = true; - } - } - if (result == null) { - result = Result.err(Result.ERR_BadData, "No Artifacts to delete"); - } else if (partial) { - result.partialContent(true); - } - return result; - } catch (Exception e) { - return Result.err(e); - } - } - - private String[] compileNotes(List notes) { - String[] rv; - if (notes == null) { - rv = NO_NOTES; - } else { - rv = new String[notes.size()]; - notes.toArray(rv); - } - return rv; - } - - private ByteBuffer getChallenge256SaltedHash(String challenge, int salt) throws NoSuchAlgorithmException { - ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + challenge.length()); - bb.putInt(salt); - bb.put(challenge.getBytes()); - byte[] hash = Hash.hashSHA256(bb.array()); - return ByteBuffer.wrap(hash); - } + // If we add more CAs, may want to parameterize + private static final int STD_RENEWAL = 30; + private static final int MAX_RENEWAL = 60; + private static final int MIN_RENEWAL = 10; + + public static final String REQUEST = "request"; + public static final String IGNORE_IPS = "ignoreIPs"; + public static final String RENEW = "renew"; + public static final String DROP = "drop"; + public static final String DOMAIN = "domain"; + + private static final String CERTMAN = "certman"; + private static final String ACCESS = "access"; + + private static final String[] NO_NOTES = new String[0]; + private final Permission root_read_permission; + private final CertDAO certDAO; + private final CredDAO credDAO; + private final ArtiDAO artiDAO; + private AAF_CM certman; + + // @SuppressWarnings("unchecked") + public CMService(final AuthzTrans trans, AAF_CM certman) throws APIException, IOException { + // Jonathan 4/2015 SessionFilter unneeded... DataStax already deals with + // Multithreading well + + HistoryDAO hd = new HistoryDAO(trans, certman.cluster, CassAccess.KEYSPACE); + CacheInfoDAO cid = new CacheInfoDAO(trans, hd); + certDAO = new CertDAO(trans, hd, cid); + credDAO = new CredDAO(trans, hd, cid); + artiDAO = new ArtiDAO(trans, hd, cid); + + this.certman = certman; + + root_read_permission=new AAFPermission( + trans.getProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF), + "access", + "*", + "read" + ); + } + + public Result requestCert(final AuthzTrans trans, final Result req, final CA ca) { + if (req.isOK()) { + + if (req.value.fqdns.isEmpty()) { + return Result.err(Result.ERR_BadData, "No Machines passed in Request"); + } + + String key = req.value.fqdns.get(0); + + // Policy 6: Requester must be granted Change permission in Namespace requested + String mechNS = FQI.reverseDomain(req.value.mechid); + if (mechNS == null) { + return Result.err(Status.ERR_Denied, "%s does not reflect a valid AAF Namespace", req.value.mechid); + } + + List notes = null; + List fqdns = new ArrayList<>(req.value.fqdns); + + String email = null; + + try { + Organization org = trans.org(); + + boolean ignoreIPs = trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), IGNORE_IPS)); + + InetAddress primary = null; + // Organize incoming information to get to appropriate Artifact + if (!fqdns.isEmpty()) { + // Accept domain wild cards, but turn into real machines + // Need *domain.com:real.machine.domain.com:san.machine.domain.com:... + if (fqdns.get(0).startsWith("*")) { // Domain set + if (!trans.fish(new AAFPermission(null,ca.getPermType(), ca.getName(), DOMAIN))) { + return Result.err(Result.ERR_Denied, + "Domain based Authorizations (" + fqdns.get(0) + ") requires Exception"); + } + + // TODO check for Permission in Add Artifact? + String domain = fqdns.get(0).substring(1); + fqdns.remove(0); + if (fqdns.isEmpty()) { + return Result.err(Result.ERR_Denied, "Requests using domain require machine declaration"); + } + + if (!ignoreIPs) { + InetAddress ia = InetAddress.getByName(fqdns.get(0)); + if (ia == null) { + return Result.err(Result.ERR_Denied, + "Request not made from matching IP matching domain"); + } else if (ia.getHostName().endsWith(domain)) { + primary = ia; + } + } + + } else { + for (String cn : req.value.fqdns) { + if(!ignoreIPs) { + try { + InetAddress[] ias = InetAddress.getAllByName(cn); + Set potentialSanNames = new HashSet<>(); + for (InetAddress ia1 : ias) { + InetAddress ia2 = InetAddress.getByAddress(ia1.getAddress()); + if (primary == null && ias.length == 1 && trans.ip().equals(ia1.getHostAddress())) { + primary = ia1; + } else if (!cn.equals(ia1.getHostName()) + && !ia2.getHostName().equals(ia2.getHostAddress())) { + potentialSanNames.add(ia1.getHostName()); + } + } + } catch (UnknownHostException e1) { + return Result.err(Result.ERR_BadData, "There is no DNS lookup for %s", cn); + } + } + } + } + } + + final String host; + if(ignoreIPs) { + host = req.value.fqdns.get(0); + } else if (primary == null) { + return Result.err(Result.ERR_Denied, "Request not made from matching IP (%s)", trans.ip()); + } else { + host = primary.getHostAddress(); + } + + ArtiDAO.Data add = null; + Result> ra = artiDAO.read(trans, req.value.mechid, host); + if (ra.isOKhasData()) { + if (add == null) { + add = ra.value.get(0); // single key + } + } else { + ra = artiDAO.read(trans, req.value.mechid, key); + if (ra.isOKhasData()) { // is the Template available? + add = ra.value.get(0); + add.machine = host; + for (String s : fqdns) { + if (!s.equals(add.machine)) { + add.sans(true).add(s); + } + } + Result rc = artiDAO.create(trans, add); // Create new Artifact from Template + if (rc.notOK()) { + return Result.err(rc); + } + } else { + add = ra.value.get(0); + } + } + + // Add Artifact listed FQDNs + if (add.sans != null) { + for (String s : add.sans) { + if (!fqdns.contains(s)) { + fqdns.add(s); + } + } + } + + // Policy 2: If Config marked as Expired, do not create or renew + Date now = new Date(); + if (add.expires != null && now.after(add.expires)) { + return Result.err(Result.ERR_Policy, "Configuration for %s %s is expired %s", add.mechid, + add.machine, Chrono.dateFmt.format(add.expires)); + } + + // Policy 3: MechID must be current + Identity muser = org.getIdentity(trans, add.mechid); + if (muser == null) { + return Result.err(Result.ERR_Policy, "MechID must exist in %s", org.getName()); + } + + // Policy 4: Sponsor must be current + Identity ouser = muser.responsibleTo(); + if (ouser == null) { + return Result.err(Result.ERR_Policy, "%s does not have a current sponsor at %s", add.mechid, + org.getName()); + } else if (!ouser.isFound() || ouser.mayOwn() != null) { + return Result.err(Result.ERR_Policy, "%s reports that %s cannot be responsible for %s", + org.getName(), trans.user()); + } + + // Set Email from most current Sponsor + email = ouser.email(); + + // Policy 5: keep Artifact data current + if (!ouser.fullID().equals(add.sponsor)) { + add.sponsor = ouser.fullID(); + artiDAO.update(trans, add); + } + + // Policy 7: Caller must be the MechID or have specifically delegated + // permissions + if (!(trans.user().equals(req.value.mechid) + || trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), REQUEST)))) { + return Result.err(Status.ERR_Denied, "%s must have access to modify x509 certs in NS %s", + trans.user(), mechNS); + } + + // Make sure Primary is the first in fqdns + if (fqdns.size() > 1) { + for (int i = 0; i < fqdns.size(); ++i) { + if(primary==null) { + trans.error().log("CMService var primary is null"); + } else { + String fg = fqdns.get(i); + if (fg!=null && fg.equals(primary.getHostName())) { + if (i != 0) { + String tmp = fqdns.get(0); + fqdns.set(0, primary.getHostName()); + fqdns.set(i, tmp); + } + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + trans.error().log(e); + return Result.err(Status.ERR_Denied, + "AppID Sponsorship cannot be determined at this time. Try later."); + } + + CSRMeta csrMeta; + try { + csrMeta = BCFactory.createCSRMeta(ca, req.value.mechid, email, fqdns); + X509andChain x509ac = ca.sign(trans, csrMeta); + if (x509ac == null) { + return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA"); + } + trans.info().printf("X509 Subject: %s", x509ac.getX509().getSubjectDN()); + + X509Certificate x509 = x509ac.getX509(); + CertDAO.Data cdd = new CertDAO.Data(); + cdd.ca = ca.getName(); + cdd.serial = x509.getSerialNumber(); + cdd.id = req.value.mechid; + cdd.x500 = x509.getSubjectDN().getName(); + cdd.x509 = Factory.toString(trans, x509); + certDAO.create(trans, cdd); + + CredDAO.Data crdd = new CredDAO.Data(); + crdd.other = Question.random.nextInt(); + crdd.cred = getChallenge256SaltedHash(csrMeta.challenge(), crdd.other); + crdd.expires = x509.getNotAfter(); + crdd.id = req.value.mechid; + crdd.ns = Question.domain2ns(crdd.id); + crdd.type = CredDAO.CERT_SHA256_RSA; + credDAO.create(trans, crdd); + + CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(notes)); + return Result.ok(cr); + } catch (Exception e) { + trans.error().log(e); + return Result.err(Result.ERR_ActionNotCompleted, e.getMessage()); + } + } else { + return Result.err(req); + } + } + + public Result renewCert(AuthzTrans trans, Result renew) { + if (renew.isOK()) { + return Result.err(Result.ERR_NotImplemented, "Not implemented yet"); + } else { + return Result.err(renew); + } + } + + public Result dropCert(AuthzTrans trans, Result drop) { + if (drop.isOK()) { + return Result.err(Result.ERR_NotImplemented, "Not implemented yet"); + } else { + return Result.err(drop); + } + } + + public Result> readCertsByMechID(AuthzTrans trans, String mechID) { + // Policy 1: To Read, must have NS Read or is Sponsor + String ns = Question.domain2ns(mechID); + try { + if (trans.user().equals(mechID) || trans.fish(new AAFPermission(ns,ACCESS, "*", "read")) + || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechID)) == null) { + return certDAO.readID(trans, mechID); + } else { + return Result.err(Result.ERR_Denied, "%s is not the ID, Sponsor or NS Owner/Admin for %s at %s", + trans.user(), mechID, trans.org().getName()); + } + } catch (OrganizationException e) { + return Result.err(e); + } + } + + public Result requestPersonalCert(AuthzTrans trans, CA ca) { + if (ca.inPersonalDomains(trans.getUserPrincipal())) { + Organization org = trans.org(); + + // Policy 1: MechID must be current + Identity ouser; + try { + ouser = org.getIdentity(trans, trans.user()); + } catch (OrganizationException e1) { + trans.error().log(e1); + ouser = null; + } + if (ouser == null) { + return Result.err(Result.ERR_Policy, "Requesting User must exist in %s", org.getName()); + } + + // Set Email from most current Sponsor + + CSRMeta csrMeta; + try { + csrMeta = BCFactory.createPersonalCSRMeta(ca, trans.user(), ouser.email()); + X509andChain x509ac = ca.sign(trans, csrMeta); + if (x509ac == null) { + return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA"); + } + X509Certificate x509 = x509ac.getX509(); + CertDAO.Data cdd = new CertDAO.Data(); + cdd.ca = ca.getName(); + cdd.serial = x509.getSerialNumber(); + cdd.id = trans.user(); + cdd.x500 = x509.getSubjectDN().getName(); + cdd.x509 = Factory.toString(trans, x509); + certDAO.create(trans, cdd); + + CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(null)); + return Result.ok(cr); + } catch (Exception e) { + trans.error().log(e); + return Result.err(Result.ERR_ActionNotCompleted, e.getMessage()); + } + } else { + return Result.err(Result.ERR_Denied, trans.user(), " not supported for CA", ca.getName()); + } + } + + /////////////// + // Artifact + ////////////// + public Result createArtifact(AuthzTrans trans, List list) { + CertmanValidator v = new CertmanValidator().artisRequired(list, 1); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + for (ArtiDAO.Data add : list) { + try { + // Policy 1: MechID must exist in Org + Identity muser = trans.org().getIdentity(trans, add.mechid); + if (muser == null) { + return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName()); + } + + // Policy 2: MechID must have valid Organization Owner + Identity emailUser; + if (muser.isPerson()) { + emailUser = muser; + } else { + Identity ouser = muser.responsibleTo(); + if (ouser == null) { + return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(), + add.mechid, trans.org().getName()); + } + + // Policy 3: Calling ID must be MechID Owner + if (!trans.user().startsWith(ouser.id())) { + return Result.err(Result.ERR_Denied, "%s is not the Sponsor for %s at %s", trans.user(), + add.mechid, trans.org().getName()); + } + emailUser = ouser; + } + + // Policy 4: Renewal Days are between 10 and 60 (constants, may be + // parameterized) + if (add.renewDays < MIN_RENEWAL) { + add.renewDays = STD_RENEWAL; + } else if (add.renewDays > MAX_RENEWAL) { + add.renewDays = MAX_RENEWAL; + } + + // Policy 5: If Notify is blank, set to Owner's Email + if (add.notify == null || add.notify.length() == 0) { + add.notify = "mailto:" + emailUser.email(); + } + + // Policy 6: Only do Domain by Exception + if (add.machine.startsWith("*")) { // Domain set + CA ca = certman.getCA(add.ca); + + if (!trans.fish(new AAFPermission(ca.getPermNS(),ca.getPermType(), add.ca, DOMAIN))) { + return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission", + add.machine); + } + } + + // Set Sponsor from Golden Source + add.sponsor = emailUser.fullID(); + + } catch (OrganizationException e) { + return Result.err(e); + } + // Add to DB + Result rv = artiDAO.create(trans, add); + // TODO come up with Partial Reporting Scheme, or allow only one at a time. + if (rv.notOK()) { + return Result.err(rv); + } + } + return Result.ok(); + } + + public Result> readArtifacts(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException { + CertmanValidator v = new CertmanValidator().keys(add); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + Result> data = artiDAO.read(trans, add); + if (data.notOKorIsEmpty()) { + return data; + } + add = data.value.get(0); + if (trans.user().equals(add.mechid) + || trans.fish(root_read_permission, + new AAFPermission(add.ns,ACCESS, "*", "read"), + new AAFPermission(add.ns,CERTMAN, add.ca, "read"), + new AAFPermission(add.ns,CERTMAN, add.ca, "request")) + || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, add.mechid)) == null) { + return data; + } else { + return Result.err(Result.ERR_Denied, + "%s is not %s, is not the sponsor, and doesn't have delegated permission.", trans.user(), + add.mechid, add.ns + ".certman|" + add.ca + "|read or ...|request"); // note: reason is set by 2nd + // case, if 1st case misses + } + + } + + public Result> readArtifactsByMechID(AuthzTrans trans, String mechid) + throws OrganizationException { + CertmanValidator v = new CertmanValidator(); + v.nullOrBlank("mechid", mechid); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + String ns = FQI.reverseDomain(mechid); + + String reason; + if (trans.fish(new AAFPermission(ns, ACCESS, "*", "read")) + || (reason = trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechid)) == null) { + return artiDAO.readByMechID(trans, mechid); + } else { + return Result.err(Result.ERR_Denied, reason); // note: reason is set by 2nd case, if 1st case misses + } + + } + + public Result> readArtifactsByMachine(AuthzTrans trans, String machine) { + CertmanValidator v = new CertmanValidator(); + v.nullOrBlank("machine", machine); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + + // TODO do some checks? + + Result> rv = artiDAO.readByMachine(trans, machine); + return rv; + } + + public Result> readArtifactsByNs(AuthzTrans trans, String ns) { + CertmanValidator v = new CertmanValidator(); + v.nullOrBlank("ns", ns); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + + // TODO do some checks? + + return artiDAO.readByNs(trans, ns); + } + + public Result updateArtifact(AuthzTrans trans, List list) throws OrganizationException { + CertmanValidator v = new CertmanValidator(); + v.artisRequired(list, 1); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + + // Check if requesting User is Sponsor + // TODO - Shall we do one, or multiples? + for (ArtiDAO.Data add : list) { + // Policy 1: MechID must exist in Org + Identity muser = trans.org().getIdentity(trans, add.mechid); + if (muser == null) { + return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName()); + } + + // Policy 2: MechID must have valid Organization Owner + Identity ouser = muser.responsibleTo(); + if (ouser == null) { + return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(), add.mechid, + trans.org().getName()); + } + + // Policy 3: Renewal Days are between 10 and 60 (constants, may be + // parameterized) + if (add.renewDays < MIN_RENEWAL) { + add.renewDays = STD_RENEWAL; + } else if (add.renewDays > MAX_RENEWAL) { + add.renewDays = MAX_RENEWAL; + } + + // Policy 4: Data is always updated with the latest Sponsor + // Add to Sponsor, to make sure we are always up to date. + add.sponsor = ouser.fullID(); + + // Policy 5: If Notify is blank, set to Owner's Email + if (add.notify == null || add.notify.length() == 0) { + add.notify = "mailto:" + ouser.email(); + } + // Policy 6: Only do Domain by Exception + if (add.machine.startsWith("*")) { // Domain set + CA ca = certman.getCA(add.ca); + if (ca == null) { + return Result.err(Result.ERR_BadData, "CA is required in Artifact"); + } + if (!trans.fish(new AAFPermission(null,ca.getPermType(), add.ca, DOMAIN))) { + return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission", + add.machine); + } + } + + // Policy 7: only Owner may update info + if (trans.user().startsWith(ouser.id())) { + return artiDAO.update(trans, add); + } else { + return Result.err(Result.ERR_Denied, "%s may not update info for %s", trans.user(), muser.fullID()); + } + } + return Result.err(Result.ERR_BadData, "No Artifacts to update"); + } + + public Result deleteArtifact(AuthzTrans trans, String mechid, String machine) throws OrganizationException { + CertmanValidator v = new CertmanValidator(); + v.nullOrBlank("mechid", mechid).nullOrBlank("machine", machine); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + + Result> rlad = artiDAO.read(trans, mechid, machine); + if (rlad.notOKorIsEmpty()) { + return Result.err(Result.ERR_NotFound, "Artifact for %s %s does not exist.", mechid, machine); + } + + return deleteArtifact(trans, rlad.value.get(0)); + } + + private Result deleteArtifact(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException { + // Policy 1: Record should be delete able only by Existing Sponsor. + String sponsor = null; + Identity muser = trans.org().getIdentity(trans, add.mechid); + if (muser != null) { + Identity ouser = muser.responsibleTo(); + if (ouser != null) { + sponsor = ouser.fullID(); + } + } + // Policy 1.a: If Sponsorship is deleted in system of Record, then + // accept deletion by sponsor in Artifact Table + if (sponsor == null) { + sponsor = add.sponsor; + } + + String ns = FQI.reverseDomain(add.mechid); + + if (trans.fish(new AAFPermission(ns,ACCESS, "*", "write")) || trans.user().equals(sponsor)) { + return artiDAO.delete(trans, add, false); + } + return Result.err(Result.ERR_Denied, "%1 is not allowed to delete this item", trans.user()); + } + + public Result deleteArtifact(AuthzTrans trans, List list) { + CertmanValidator v = new CertmanValidator().artisRequired(list, 1); + if (v.err()) { + return Result.err(Result.ERR_BadData, v.errs()); + } + + try { + boolean partial = false; + Result result = null; + for (ArtiDAO.Data add : list) { + result = deleteArtifact(trans, add); + if (result.notOK()) { + partial = true; + } + } + if (result == null) { + result = Result.err(Result.ERR_BadData, "No Artifacts to delete"); + } else if (partial) { + result.partialContent(true); + } + return result; + } catch (Exception e) { + return Result.err(e); + } + } + + private String[] compileNotes(List notes) { + String[] rv; + if (notes == null) { + rv = NO_NOTES; + } else { + rv = new String[notes.size()]; + notes.toArray(rv); + } + return rv; + } + + private ByteBuffer getChallenge256SaltedHash(String challenge, int salt) throws NoSuchAlgorithmException { + ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + challenge.length()); + bb.putInt(salt); + bb.put(challenge.getBytes()); + byte[] hash = Hash.hashSHA256(bb.array()); + return ByteBuffer.wrap(hash); + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/Code.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/Code.java index ce2ca065..a6663ad7 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/Code.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/Code.java @@ -28,18 +28,18 @@ import org.onap.aaf.auth.rserv.HttpCode; public abstract class Code extends HttpCode implements Cloneable { - public Code(AAF_CM cma, String description, String ... roles) { - super(cma.facade1_0, description, roles); - // Note, the first "Code" will be created with default Facade, "JSON". - // use clone for another Code with XML - } - + public Code(AAF_CM cma, String description, String ... roles) { + super(cma.facade1_0, description, roles); + // Note, the first "Code" will be created with default Facade, "JSON". + // use clone for another Code with XML + } + - public D clone(Facade1_0 facade) throws Exception { - @SuppressWarnings("unchecked") - D d = (D)clone(); - d.context = facade; - return d; - } + public D clone(Facade1_0 facade) throws Exception { + @SuppressWarnings("unchecked") + D d = (D)clone(); + d.context = facade; + return d; + } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java index d3ce0ace..ea97dd0d 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java @@ -37,85 +37,85 @@ import org.onap.aaf.auth.validation.Validator; * */ public class CertmanValidator extends Validator{ - // Repeated Msg fragments - private static final String MECHID = "mechid"; - private static final String MACHINE = "machine"; - private static final String ARTIFACT_LIST_IS_NULL = "Artifact List is null."; - private static final String Y = "y."; - private static final String IES = "ies."; - private static final String ENTR = " entr"; - private static final String MUST_HAVE_AT_LEAST = " must have at least "; - private static final String IS_NULL = " is null."; - private static final String ARTIFACTS_MUST_HAVE_AT_LEAST = "Artifacts must have at least "; + // Repeated Msg fragments + private static final String MECHID = "mechid"; + private static final String MACHINE = "machine"; + private static final String ARTIFACT_LIST_IS_NULL = "Artifact List is null."; + private static final String Y = "y."; + private static final String IES = "ies."; + private static final String ENTR = " entr"; + private static final String MUST_HAVE_AT_LEAST = " must have at least "; + private static final String IS_NULL = " is null."; + private static final String ARTIFACTS_MUST_HAVE_AT_LEAST = "Artifacts must have at least "; - public CertmanValidator nullBlankMin(String name, List list, int min) { - if(list==null) { - msg(name + IS_NULL); - } else { - if(list.size() list, int min) { + if(list==null) { + msg(name + IS_NULL); + } else { + if(list.size() list, int min) { - if(list==null) { - msg(ARTIFACT_LIST_IS_NULL); - } else { - if(list.size() list, int min) { + if(list==null) { + msg(ARTIFACT_LIST_IS_NULL); + } else { + if(list.size() list, int min) { - if(list==null) { - msg(ARTIFACT_LIST_IS_NULL); - } else { - if(list.size() list, int min) { + if(list==null) { + msg(ARTIFACT_LIST_IS_NULL); + } else { + if(list.size() getNonCriticalExtensionOIDs() { - - return null; - } - - @Override - public byte[] getExtensionValue(String oid) { - - return null; - } - - @Override - public Set getCriticalExtensionOIDs() { - - return null; - } - - @Override - public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException { - - - } - - @Override - public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, - NoSuchProviderException, SignatureException { - - - } - - @Override - public String toString() { - - return null; - } - - @Override - public PublicKey getPublicKey() { - - return null; - } - - @Override - public byte[] getEncoded() throws CertificateEncodingException { - - return null; - } - - @Override - public int getVersion() { - - return 0; - } - - @Override - public byte[] getTBSCertificate() throws CertificateEncodingException { - - return null; - } - - @Override - public boolean[] getSubjectUniqueID() { - - return null; - } - - @Override - public Principal getSubjectDN() { - - return null; - } - - @Override - public byte[] getSignature() { - - return null; - } - - @Override - public byte[] getSigAlgParams() { - - return null; - } - - @Override - public String getSigAlgOID() { - - return null; - } - - @Override - public String getSigAlgName() { - - return null; - } - - @Override - public BigInteger getSerialNumber() { - - return null; - } - - @Override - public Date getNotBefore() { - - return null; - } - - @Override - public Date getNotAfter() { - - return null; - } - - @Override - public boolean[] getKeyUsage() { - - return null; - } - - @Override - public boolean[] getIssuerUniqueID() { - - return null; - } - - @Override - public Principal getIssuerDN() { - - return null; - } - - @Override - public int getBasicConstraints() { - - return 0; - } - - @Override - public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException { - - - } - - @Override - public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException { - - } - }; - X509andChain xac = new X509andChain(cert, new ArrayList<>()); - when(localCA.sign(Mockito.any(Trans.class), Mockito.any(CSRMeta.class))).thenReturn(xac); - certDAO = mock(CachedCertDAO.class, CALLS_REAL_METHODS); - } - - @Test - public void identity_True() throws CertificateException, IOException, CertException { - assertNotNull(localCA.sign(trans, csrMeta)); - } - - - @Test - public void identityNull() throws CertificateException { - try { - assertNotNull(localCA.sign(null, csrMeta)); - } catch (IOException e) { - - e.printStackTrace(); - } catch (CertException e) { - - e.printStackTrace(); - } - } - - @Test - public void identityBothNull() throws CertificateException { - try { - assertNotNull(localCA.sign(null, null)); - } catch (IOException e) { - - e.printStackTrace(); - } catch (CertException e) { - - e.printStackTrace(); - } - } + Principal prc = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"); + req = mock(HttpServletRequest.class); + localCA = mock(LocalCA.class); + X509Certificate cert = new X509Certificate() { + + @Override + public boolean hasUnsupportedCriticalExtension() { + return false; + } + + @Override + public Set getNonCriticalExtensionOIDs() { + + return null; + } + + @Override + public byte[] getExtensionValue(String oid) { + + return null; + } + + @Override + public Set getCriticalExtensionOIDs() { + + return null; + } + + @Override + public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, NoSuchProviderException, SignatureException { + + + } + + @Override + public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException { + + + } + + @Override + public String toString() { + + return null; + } + + @Override + public PublicKey getPublicKey() { + + return null; + } + + @Override + public byte[] getEncoded() throws CertificateEncodingException { + + return null; + } + + @Override + public int getVersion() { + + return 0; + } + + @Override + public byte[] getTBSCertificate() throws CertificateEncodingException { + + return null; + } + + @Override + public boolean[] getSubjectUniqueID() { + + return null; + } + + @Override + public Principal getSubjectDN() { + + return null; + } + + @Override + public byte[] getSignature() { + + return null; + } + + @Override + public byte[] getSigAlgParams() { + + return null; + } + + @Override + public String getSigAlgOID() { + + return null; + } + + @Override + public String getSigAlgName() { + + return null; + } + + @Override + public BigInteger getSerialNumber() { + + return null; + } + + @Override + public Date getNotBefore() { + + return null; + } + + @Override + public Date getNotAfter() { + + return null; + } + + @Override + public boolean[] getKeyUsage() { + + return null; + } + + @Override + public boolean[] getIssuerUniqueID() { + + return null; + } + + @Override + public Principal getIssuerDN() { + + return null; + } + + @Override + public int getBasicConstraints() { + + return 0; + } + + @Override + public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException { + + + } + + @Override + public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException { + + } + }; + X509andChain xac = new X509andChain(cert, new ArrayList<>()); + when(localCA.sign(Mockito.any(Trans.class), Mockito.any(CSRMeta.class))).thenReturn(xac); + certDAO = mock(CachedCertDAO.class, CALLS_REAL_METHODS); + } + + @Test + public void identity_True() throws CertificateException, IOException, CertException { + assertNotNull(localCA.sign(trans, csrMeta)); + } + + + @Test + public void identityNull() throws CertificateException { + try { + assertNotNull(localCA.sign(null, csrMeta)); + } catch (IOException e) { + + e.printStackTrace(); + } catch (CertException e) { + + e.printStackTrace(); + } + } + + @Test + public void identityBothNull() throws CertificateException { + try { + assertNotNull(localCA.sign(null, null)); + } catch (IOException e) { + + e.printStackTrace(); + } catch (CertException e) { + + e.printStackTrace(); + } + } } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/cert/JU_BCFactory.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/cert/JU_BCFactory.java index 337bc9ed..eae37640 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/cert/JU_BCFactory.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/cert/JU_BCFactory.java @@ -47,82 +47,82 @@ import org.onap.aaf.misc.env.Trans; @RunWith(MockitoJUnitRunner.class) public class JU_BCFactory { - - private static BCFactory bcFactory = new BCFactory(); - - private static BCFactory bcFact; - - private static PrivateKey pk; - - - private static Trans trans; - - - private static PKCS10CertificationRequest req; - - @BeforeClass - public static void setUp() throws IOException { - pk = new XYZKey(); - trans = mock(Trans.class); - req = mock(PKCS10CertificationRequest.class); - when(req.getEncoded()).thenReturn(new byte[1]); - when(trans.start(Mockito.anyString(), Mockito.anyInt())).thenReturn(new TimeTaken(null, 0) { - - @Override - public void output(StringBuilder sb) { - // TODO Auto-generated method stub - - } - }); - bcFact = mock(BCFactory.class); - } - - @Test - public void toStrin() throws OperatorCreationException, IOException, CertException { - assertNotNull(bcFactory.toString(req)); - } - - @Test - public void toStrinMoc() throws OperatorCreationException, IOException, CertException { - assertNotNull(bcFact.toString(req)); - } - - @Rule + + private static BCFactory bcFactory = new BCFactory(); + + private static BCFactory bcFact; + + private static PrivateKey pk; + + + private static Trans trans; + + + private static PKCS10CertificationRequest req; + + @BeforeClass + public static void setUp() throws IOException { + pk = new XYZKey(); + trans = mock(Trans.class); + req = mock(PKCS10CertificationRequest.class); + when(req.getEncoded()).thenReturn(new byte[1]); + when(trans.start(Mockito.anyString(), Mockito.anyInt())).thenReturn(new TimeTaken(null, 0) { + + @Override + public void output(StringBuilder sb) { + // TODO Auto-generated method stub + + } + }); + bcFact = mock(BCFactory.class); + } + + @Test + public void toStrin() throws OperatorCreationException, IOException, CertException { + assertNotNull(bcFactory.toString(req)); + } + + @Test + public void toStrinMoc() throws OperatorCreationException, IOException, CertException { + assertNotNull(bcFact.toString(req)); + } + + @Rule public ExpectedException thrown= ExpectedException.none(); - - @Test - public void toCSR() { - try { - assertNotNull(bcFactory.toCSR(trans, new File("/random/path"))); - thrown.expect(FileNotFoundException.class); - } catch (IOException e) { - - e.printStackTrace(); - } - } - + + @Test + public void toCSR() { + try { + assertNotNull(bcFactory.toCSR(trans, new File("/random/path"))); + thrown.expect(FileNotFoundException.class); + } catch (IOException e) { + + e.printStackTrace(); + } + } + } class XYZKey implements Key, PublicKey, PrivateKey { - - int rotValue; - public XYZKey() { - rotValue = 1200213; - } - public String getAlgorithm() { - return "XYZ"; - } + + int rotValue; + public XYZKey() { + rotValue = 1200213; + } + public String getAlgorithm() { + return "XYZ"; + } - public String getFormat() { - return "XYZ Special Format"; - } + public String getFormat() { + return "XYZ Special Format"; + } - public byte[] getEncoded() { - byte b[] = new byte[4]; - b[3] = (byte) ((rotValue << 24) & 0xff); - b[2] = (byte) ((rotValue << 16) & 0xff); - b[1] = (byte) ((rotValue << 8) & 0xff); - b[0] = (byte) ((rotValue << 0) & 0xff); - return b; - } + public byte[] getEncoded() { + byte b[] = new byte[4]; + b[3] = (byte) ((rotValue << 24) & 0xff); + b[2] = (byte) ((rotValue << 16) & 0xff); + b[1] = (byte) ((rotValue << 8) & 0xff); + b[0] = (byte) ((rotValue << 0) & 0xff); + return b; + } } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/facade/JU_FacadeImpl.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/facade/JU_FacadeImpl.java index 27ac04e5..48f5f1b6 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/facade/JU_FacadeImpl.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/facade/JU_FacadeImpl.java @@ -52,134 +52,134 @@ import org.onap.aaf.misc.env.TimeTaken; @RunWith(MockitoJUnitRunner.class) public class JU_FacadeImpl { - - private static AuthzTrans trans; - private static HttpServletResponse resp; - private static AAF_CM certman; - private static FacadeImpl hImpl; - private static CMService service; - private Mapper mapper; - private Data.TYPE dataType; - private static AuthzEnv env; - - private static FacadeImpl fImpl; - private static HttpServletRequest req; - - @Before - public void setUp() throws APIException, IOException { - fImpl = mock(FacadeImpl.class); - env = mock(AuthzEnv.class); - resp = mock(HttpServletResponse.class); - req = mock(HttpServletRequest.class); - hImpl = mock(FacadeImpl.class, CALLS_REAL_METHODS); - Result rvd = (Result) mock(Result.class); - trans = mock(AuthzTrans.class); - when(trans.error()).thenReturn(new LogTarget() { - - @Override - public void printf(String fmt, Object... vars) {} - - @Override - public void log(Throwable e, Object... msgs) { - e.getMessage(); - e.printStackTrace(); - msgs.toString(); - - } - - @Override - public void log(Object... msgs) { - } - - @Override - public boolean isLoggable() { - - return false; - } - }); - when(trans.start(Mockito.anyString(), Mockito.anyInt())).thenReturn(new TimeTaken("Now", 1) { - - @Override - public void output(StringBuilder sb) { - - } - }); - when(fImpl.check(Mockito.any(AuthzTrans.class), Mockito.any(HttpServletResponse.class), Mockito.anyString())).thenReturn(rvd); - when(resp.getOutputStream()).thenReturn(new ServletOutputStream() { - - @Override - public void write(int b) throws IOException { - - - } - }); - - } - - @Test - public void check() throws IOException { - AAFPermission ap = new AAFPermission("str0","str1","str3","str2"); - String perms = ap.getInstance(); - assertNotNull(hImpl.check(trans, resp, perms)); - } - - @Test - public void checkNull() throws IOException { - AAFPermission ap = new AAFPermission(null,null,"Str3","str2"); - String perms = ap.getInstance(); - assertNotNull(hImpl.check(trans, resp, perms)); - } - - @Test - public void checkTwoNull() throws IOException { - AAFPermission ap = new AAFPermission(null,null,null,"str2"); - String perms = ap.getInstance(); - assertNotNull(fImpl.check(trans, resp, perms)); - } - - @Test - public void checkAllNull() throws IOException { - AAFPermission ap = new AAFPermission(null,null,null,null); - String perms = ap.getInstance(); - assertNotNull(fImpl.check(trans, resp, perms)); - } - - @Test - public void checkTrans_null() throws IOException { - AAFPermission ap = new AAFPermission("str0","str1","str3","str2"); - String perms = ap.getInstance(); - assertNotNull(hImpl.check(null, resp, perms)); - } - - @Test - public void checkRespNull() throws IOException { - AAFPermission ap = new AAFPermission("str0","str1","str3","str2"); - String perms = ap.getInstance(); - assertNotNull(hImpl.check(trans, null, perms)); - } - - @Test - public void requestCert() { - assertNotNull(hImpl.requestCert(trans, req, resp, null)); - } - - @Test - public void renewCert() { - assertNotNull(hImpl.renewCert(trans, req, resp, true)); - } - - @Test - public void dropCert() { - assertNotNull(hImpl.renewCert(trans, req, resp, true)); - } - - @Test - public void createArtifacts() { - assertNotNull(hImpl.createArtifacts(trans, req, resp)); - } - - @Test - public void readArtifacts() { - assertNotNull(hImpl.readArtifacts(trans, req, resp)); - } + + private static AuthzTrans trans; + private static HttpServletResponse resp; + private static AAF_CM certman; + private static FacadeImpl hImpl; + private static CMService service; + private Mapper mapper; + private Data.TYPE dataType; + private static AuthzEnv env; + + private static FacadeImpl fImpl; + private static HttpServletRequest req; + + @Before + public void setUp() throws APIException, IOException { + fImpl = mock(FacadeImpl.class); + env = mock(AuthzEnv.class); + resp = mock(HttpServletResponse.class); + req = mock(HttpServletRequest.class); + hImpl = mock(FacadeImpl.class, CALLS_REAL_METHODS); + Result rvd = (Result) mock(Result.class); + trans = mock(AuthzTrans.class); + when(trans.error()).thenReturn(new LogTarget() { + + @Override + public void printf(String fmt, Object... vars) {} + + @Override + public void log(Throwable e, Object... msgs) { + e.getMessage(); + e.printStackTrace(); + msgs.toString(); + + } + + @Override + public void log(Object... msgs) { + } + + @Override + public boolean isLoggable() { + + return false; + } + }); + when(trans.start(Mockito.anyString(), Mockito.anyInt())).thenReturn(new TimeTaken("Now", 1) { + + @Override + public void output(StringBuilder sb) { + + } + }); + when(fImpl.check(Mockito.any(AuthzTrans.class), Mockito.any(HttpServletResponse.class), Mockito.anyString())).thenReturn(rvd); + when(resp.getOutputStream()).thenReturn(new ServletOutputStream() { + + @Override + public void write(int b) throws IOException { + + + } + }); + + } + + @Test + public void check() throws IOException { + AAFPermission ap = new AAFPermission("str0","str1","str3","str2"); + String perms = ap.getInstance(); + assertNotNull(hImpl.check(trans, resp, perms)); + } + + @Test + public void checkNull() throws IOException { + AAFPermission ap = new AAFPermission(null,null,"Str3","str2"); + String perms = ap.getInstance(); + assertNotNull(hImpl.check(trans, resp, perms)); + } + + @Test + public void checkTwoNull() throws IOException { + AAFPermission ap = new AAFPermission(null,null,null,"str2"); + String perms = ap.getInstance(); + assertNotNull(fImpl.check(trans, resp, perms)); + } + + @Test + public void checkAllNull() throws IOException { + AAFPermission ap = new AAFPermission(null,null,null,null); + String perms = ap.getInstance(); + assertNotNull(fImpl.check(trans, resp, perms)); + } + + @Test + public void checkTrans_null() throws IOException { + AAFPermission ap = new AAFPermission("str0","str1","str3","str2"); + String perms = ap.getInstance(); + assertNotNull(hImpl.check(null, resp, perms)); + } + + @Test + public void checkRespNull() throws IOException { + AAFPermission ap = new AAFPermission("str0","str1","str3","str2"); + String perms = ap.getInstance(); + assertNotNull(hImpl.check(trans, null, perms)); + } + + @Test + public void requestCert() { + assertNotNull(hImpl.requestCert(trans, req, resp, null)); + } + + @Test + public void renewCert() { + assertNotNull(hImpl.renewCert(trans, req, resp, true)); + } + + @Test + public void dropCert() { + assertNotNull(hImpl.renewCert(trans, req, resp, true)); + } + + @Test + public void createArtifacts() { + assertNotNull(hImpl.createArtifacts(trans, req, resp)); + } + + @Test + public void readArtifacts() { + assertNotNull(hImpl.readArtifacts(trans, req, resp)); + } } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java index a8f9934a..90875dab 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java @@ -58,109 +58,109 @@ import junit.framework.Assert; public class CertmanTest { - private static HMangr hman; - private static AuthzEnv env; - private static HBasicAuthSS ss; - private static RosettaDF reqDF; - private static RosettaDF certDF; + private static HMangr hman; + private static AuthzEnv env; + private static HBasicAuthSS ss; + private static RosettaDF reqDF; + private static RosettaDF certDF; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - env = new AuthzEnv(); -// InputStream ris = env.classLoader().getResource("certman.props").openStream(); -// try { -// env.load(ris); -// } finally { -// ris.close(); -// } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + env = new AuthzEnv(); +// InputStream ris = env.classLoader().getResource("certman.props").openStream(); +// try { +// env.load(ris); +// } finally { +// ris.close(); +// } // -// Locator loc = new DNSLocator(env, "https", "aaf.it.att.com", "8150"); -// for(Item item = loc.first(); item!=null; item=loc.next(item)) { -// System.out.println(loc.get(item)); -// } -// -// -// SecurityInfoC si = SecurityInfoC.instance(env, HttpURLConnection.class); -// ss = new HBasicAuthSS(si,"m12345@aaf.att.com", -// env.decrypt("enc:gvptdJyo0iKdVZw2rzMb0woxa7YKMdqLuhfQ4OQfZ8k",false)); -// env.decrypt("enc:jFfAnO3mOKb9Gzm2OFysslmXpbnyuAxuoNJK",false), si); -// SecuritySetter ss = new X509SS(si, "aaf"); - -// hman = new HMangr(env,loc); +// Locator loc = new DNSLocator(env, "https", "aaf.it.att.com", "8150"); +// for(Item item = loc.first(); item!=null; item=loc.next(item)) { +// System.out.println(loc.get(item)); +// } +// +// +// SecurityInfoC si = SecurityInfoC.instance(env, HttpURLConnection.class); +// ss = new HBasicAuthSS(si,"m12345@aaf.att.com", +// env.decrypt("enc:gvptdJyo0iKdVZw2rzMb0woxa7YKMdqLuhfQ4OQfZ8k",false)); +// env.decrypt("enc:jFfAnO3mOKb9Gzm2OFysslmXpbnyuAxuoNJK",false), si); +// SecuritySetter ss = new X509SS(si, "aaf"); + +// hman = new HMangr(env,loc); // -// reqDF = env.newDataFactory(CertificateRequest.class); -// reqDF.out(TYPE.JSON); -// certDF = env.newDataFactory(CertInfo.class); - } +// reqDF = env.newDataFactory(CertificateRequest.class); +// reqDF.out(TYPE.JSON); +// certDF = env.newDataFactory(CertInfo.class); + } -// @AfterClass -// public static void tearDownAfterClass() throws Exception { -// hman.close(); -// } +// @AfterClass +// public static void tearDownAfterClass() throws Exception { +// hman.close(); +// } - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } -// @Test -// public void testX500Name() throws Exception { -// -// for( InetAddress ia : InetAddress.getAllByName("aaf.dev.att.com")) { -// System.out.printf("%s - %s\n", ia.getHostName(), ia.getHostAddress()); -// InetAddress ia1 = InetAddress.getByName(ia.getHostAddress()); -// System.out.printf("%s - %s\n", ia1.getHostName(), ia1.getHostAddress()); -// } -// -// hman.best(ss, new Retryable() { -// @Override -// public Void code(Rcli client) throws APIException, CadiException { -// CertificateRequest cr = new CertificateRequest(); -// cr.setMechid("a12345@org.osaaf.org"); -// cr.setSponsor("something"); -// cr.getFqdns().add("mithrilcsp.sbc.com"); -// cr.getFqdns().add("zld01907.vci.att.com"); -// cr.getFqdns().add("aaftest.test.att.com"); -// -// String path = "/cert/local"; // Local Test -//// String path = "/cert/aaf"; // Official CA -// long end=0,start = System.nanoTime(); -// try { -// System.out.println(reqDF.newData().option(Data.PRETTY).load(cr).asString()); -// Future f = client.updateRespondString(path, reqDF, cr); -// if(f.get(10000)) { -// end = System.nanoTime(); -// System.out.println(f.body()); -// CertInfo capi = certDF.newData().in(Data.TYPE.JSON).load(f.body()).asObject(); -// for(String c :capi.getCerts()) { -// for( java.security.cert.Certificate x509 : Factory.toX509Certificate(c)) { -// System.out.println(x509.toString()); -// } -// } -// } else { -// end = System.nanoTime(); -// String msg = "Client returned " + f.code() + ": " + f.body(); -// System.out.println(msg); -// Assert.fail(msg); -// } -// } catch (CertificateException e) { -// throw new CadiException(e); -// } finally { -// System.out.println(Chrono.millisFromNanos(start,end) + " ms"); -// } -// return null; -// } -// }); -// -// -// } +// @Test +// public void testX500Name() throws Exception { +// +// for( InetAddress ia : InetAddress.getAllByName("aaf.dev.att.com")) { +// System.out.printf("%s - %s\n", ia.getHostName(), ia.getHostAddress()); +// InetAddress ia1 = InetAddress.getByName(ia.getHostAddress()); +// System.out.printf("%s - %s\n", ia1.getHostName(), ia1.getHostAddress()); +// } +// +// hman.best(ss, new Retryable() { +// @Override +// public Void code(Rcli client) throws APIException, CadiException { +// CertificateRequest cr = new CertificateRequest(); +// cr.setMechid("a12345@org.osaaf.org"); +// cr.setSponsor("something"); +// cr.getFqdns().add("mithrilcsp.sbc.com"); +// cr.getFqdns().add("zld01907.vci.att.com"); +// cr.getFqdns().add("aaftest.test.att.com"); +// +// String path = "/cert/local"; // Local Test +//// String path = "/cert/aaf"; // Official CA +// long end=0,start = System.nanoTime(); +// try { +// System.out.println(reqDF.newData().option(Data.PRETTY).load(cr).asString()); +// Future f = client.updateRespondString(path, reqDF, cr); +// if(f.get(10000)) { +// end = System.nanoTime(); +// System.out.println(f.body()); +// CertInfo capi = certDF.newData().in(Data.TYPE.JSON).load(f.body()).asObject(); +// for(String c :capi.getCerts()) { +// for( java.security.cert.Certificate x509 : Factory.toX509Certificate(c)) { +// System.out.println(x509.toString()); +// } +// } +// } else { +// end = System.nanoTime(); +// String msg = "Client returned " + f.code() + ": " + f.body(); +// System.out.println(msg); +// Assert.fail(msg); +// } +// } catch (CertificateException e) { +// throw new CadiException(e); +// } finally { +// System.out.println(Chrono.millisFromNanos(start,end) + " ms"); +// } +// return null; +// } +// }); +// +// +// } // -// public X500Principal ephemeral() { -// return null; -// } - +// public X500Principal ephemeral() { +// return null; +// } + } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java index 2d5e172d..c308e775 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java @@ -57,588 +57,588 @@ import org.onap.aaf.misc.env.APIException; import jline.console.ConsoleReader; public class AAFcli { - protected static PrintWriter pw; - protected HMangr hman; - // Storage for last reused client. We can do this - // because we're technically "single" threaded calls. - public Retryable prevCall; - - protected SecuritySetter ss; -// protected AuthzEnv env; - private boolean close; - private List cmds; - - // Lex State - private ArrayList expect = new ArrayList<>(); - private boolean verbose = true; - private int delay; - private SecurityInfoC si; - private boolean request = false; - private String force = null; - private boolean gui = false; - // Package on purpose - Access access; - AuthzEnv env; - - private static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); - private static boolean isConsole = false; - private static boolean isTest = false; - private static boolean showDetails = false; - private static boolean ignoreDelay = false; - private static int globalDelay=0; - - public static int timeout() { - return TIMEOUT; - } - - // Create when only have Access - public AAFcli(Access access, Writer wtr, HMangr hman, SecurityInfoC si, SecuritySetter ss) throws APIException, CadiException { - this(access,new AuthzEnv(access.getProperties()),wtr,hman, si,ss); - } - - public AAFcli(Access access, AuthzEnv env, Writer wtr, HMangr hman, SecurityInfoC si, SecuritySetter ss) throws APIException, CadiException { - this.env = env; - this.access = access; - this.ss = ss; - this.hman = hman; - this.si = si; - if (wtr instanceof PrintWriter) { - pw = (PrintWriter) wtr; - close = false; - } else { - pw = new PrintWriter(wtr); - close = true; - } - - /* - * Create Cmd Tree - */ - cmds = new ArrayList<>(); - - Role role = new Role(this); - cmds.add(new Help(this, cmds)); - cmds.add(new Version(this)); - cmds.add(new Perm(role)); - cmds.add(role); - cmds.add(new User(this)); - cmds.add(new NS(this)); - cmds.add(new Mgmt(this)); - } - - public void verbose(boolean v) { - verbose = v; - } - - public void close() { -// if (hman != null) { -// hman.close(); -// hman = null; -// } - if (close) { - pw.close(); - } - } - - public boolean eval(String line) throws Exception { - if (line.length() == 0) { - return true; - } else if (line.startsWith("#")) { - pw.println(line); - return true; - } - - String[] largs = argEval(line); - int idx = 0; - - // Variable replacement - StringBuilder sb = null; - while (idx < largs.length) { - int e = 0; - for (int v = largs[idx].indexOf("@["); v >= 0; v = largs[idx].indexOf("@[", v + 1)) { - if (sb == null) { - sb = new StringBuilder(); - } - sb.append(largs[idx], e, v); - if ((e = largs[idx].indexOf(']', v)) >= 0) { - String p = access.getProperty(largs[idx].substring(v + 2, e),null); - if(p==null) { - p = System.getProperty(largs[idx].substring(v+2,e)); - } - ++e; - if (p != null) { - sb.append(p); - } - } - } - if (sb != null && sb.length() > 0) { - sb.append(largs[idx], e, largs[idx].length()); - largs[idx] = sb.toString(); - sb.setLength(0); - } - ++idx; - } - - idx = 0; - boolean rv = true; - while (rv && idx < largs.length) { - // Allow Script to change Credential - if (!gui) { - if("as".equalsIgnoreCase(largs[idx])) { - if (largs.length > ++idx) { - // get Password from Props with ID as Key - String user = largs[idx++]; - int colon = user.indexOf(':'); - String pass; - if (colon > 0) { - pass = user.substring(colon + 1); - user = user.substring(0, colon); - } else { - pass = access.getProperty(user, null); - } - if (pass != null) { - pass = access.decrypt(pass, false); - access.getProperties().put(user, pass); - ss=new HBasicAuthSS(si, user, pass); - pw.println("as " + user); - } else { // get Pass from System Properties, under name of - // Tag - pw.println("ERROR: No password set for " + user); - rv = false; - } - continue; - } - } else if ("expect".equalsIgnoreCase(largs[idx])) { - expect.clear(); - if (largs.length > idx++) { - if (!"nothing".equals(largs[idx])) { - for (String str : largs[idx].split(",")) { - try { - if ("Exception".equalsIgnoreCase(str)) { - expect.add(-1); - } else { - expect.add(Integer.parseInt(str)); - } - } catch (NumberFormatException e) { - throw new CadiException("\"expect\" should be followed by Number"); - } - } - ++idx; - } - } - continue; - // Sleep, typically for reports, to allow DB to update - // Milliseconds - - } else if ("sleep".equalsIgnoreCase(largs[idx])) { - Integer t = Integer.parseInt(largs[++idx]); - pw.println("sleep " + t); - Thread.sleep(t); - ++idx; - continue; - } else if ("delay".equalsIgnoreCase(largs[idx])) { - delay = Integer.parseInt(largs[++idx]); - pw.println("delay " + delay); - ++idx; - continue; - } else if ("pause".equalsIgnoreCase(largs[idx])) { - pw.println("Press to continue..."); - ++idx; - // Sonar insists we do something with the string, though it's only a pause. Not very helpful... - String sonar = new BufferedReader(new InputStreamReader(System.in)).readLine(); - sonar=""; // this useless code brought to you by Sonar. - pw.print(sonar); - continue; - } else if ("exit".equalsIgnoreCase(largs[idx])) { - pw.println("Exiting..."); - return false; - } - - } - - if("REQUEST".equalsIgnoreCase(largs[idx])) { - request=true; - ++idx; - } else if("FORCE".equalsIgnoreCase(largs[idx])) { - force="true"; - ++idx; - } else if("DETAILS".equalsIgnoreCase(largs[idx])) { - showDetails=true; - ++idx; - } else if ("set".equalsIgnoreCase(largs[idx])) { - while (largs.length > ++idx) { - int equals = largs[idx].indexOf('='); - String tag, value; - if (equals < 0) { - tag = largs[idx]; - value = access.getProperty(Config.AAF_APPPASS,null); - if(value==null) { - break; - } else { - value = access.decrypt(value, false); - if(value==null) { - break; - } - access.getProperties().put(tag, value); - pw.println("set " + tag + " "); - } - } else { - tag = largs[idx].substring(0, equals); - value = largs[idx].substring(++equals); - pw.println("set " + tag + ' ' + value); - } - boolean isTrue = "TRUE".equalsIgnoreCase(value); - if("FORCE".equalsIgnoreCase(tag)) { - force = value; - } else if("REQUEST".equalsIgnoreCase(tag)) { - request = isTrue; - } else if("DETAILS".equalsIgnoreCase(tag)) { - showDetails = isTrue; - } else { - access.getProperties().put(tag, value); - } - } - continue; - // Allow Script to indicate if Failure is what is expected - } - - int ret = 0; - for (Cmd c : cmds) { - if (largs[idx].equalsIgnoreCase(c.getName())) { - if (verbose) { - pw.println(line); - if (expect.size() > 0) { - pw.print("** Expect "); - boolean first = true; - for (Integer i : expect) { - if (first) { - first = false; - } else { - pw.print(','); - } - pw.print(i); - } - pw.println(" **"); - } - } - try { - ret = c.exec(++idx, largs); - if (delay+globalDelay > 0) { - Thread.sleep((long)(delay+globalDelay)); - } - } catch (Exception e) { - if (expect.contains(-1)) { - pw.println(e.getMessage()); - ret = -1; - } else { - throw e; - } - } finally { - clearSingleLineProperties(); - } - rv = expect.isEmpty() ? true : expect.contains(ret); - if (verbose) { - if (rv) { - pw.println(); - } else { - pw.print("!!! Unexpected Return Code: "); - pw.print(ret); - pw.println(", VALIDATE OUTPUT!!!"); - } - } - return rv; - } - } - pw.write("Unknown Instruction \""); - pw.write(largs[idx]); - pw.write("\"\n"); - idx = largs.length;// always end after one command - } - return rv; - } - - private String[] argEval(String line) { - StringBuilder sb = new StringBuilder(); - ArrayList arr = new ArrayList<>(); - boolean start = true; - char quote = 0; - char last = 0; - for (int i = 0; i < line.length(); ++i) { - char ch; - if (Character.isWhitespace(ch = line.charAt(i))) { - if (start || last==',') { - continue; // trim - } else if (quote != 0) { - sb.append(ch); - } else { - arr.add(sb.toString()); - sb.setLength(0); - start = true; - } - } else if (ch == '\'' || ch == '"') { // toggle - if (quote == ch) { - quote = 0; - } else { - quote = ch; - } - } else if(ch=='|' && quote==0) { - arr.add(sb.toString()); - sb.setLength(0); - start = true; - } else { - start = false; - sb.append(ch); - last = ch; - } - } - if (sb.length() > 0) { - arr.add(sb.toString()); - } - - String[] rv = new String[arr.size()]; - arr.toArray(rv); - return rv; - } - - public static void keyboardHelp() { - System.out.println("'C-' means hold the ctrl key down while pressing the next key."); - System.out.println("'M-' means hold the alt key down while pressing the next key."); - System.out.println("For instance, C-b means hold ctrl key and press b, M-b means hold alt and press b\n"); - - System.out.println("Basic Keybindings:"); - System.out.println("\tC-l - clear screen"); - System.out.println("\tC-a - beginning of line"); - System.out.println("\tC-e - end of line"); - System.out.println("\tC-b - backward character (left arrow also works)"); - System.out.println("\tM-b - backward word"); - System.out.println("\tC-f - forward character (right arrow also works)"); - System.out.println("\tM-f - forward word"); - System.out.println("\tC-d - delete character under cursor"); - System.out.println("\tM-d - delete word forward"); - System.out.println("\tM-backspace - delete word backward"); - System.out.println("\tC-k - delete from cursor to end of line"); - System.out.println("\tC-u - delete entire line, regardless of cursor position\n"); - - System.out.println("Command History:"); - System.out.println("\tC-r - search backward in history (repeating C-r continues the search)"); - System.out.println("\tC-p - move backwards through history (up arrow also works)"); - System.out.println("\tC-n - move forwards through history (down arrow also works)\n"); - - } - - /** - * @param args - */ - public static void main(String[] args) { - int rv = 0; - - try { - AAFSSO aafsso = new AAFSSO(args); - String noexit = aafsso.access().getProperty("no_exit"); - try { - PropAccess access = aafsso.access(); - - if(aafsso.ok()) { - Define.set(access); - AuthzEnv env = new AuthzEnv(access); - - Reader rdr = null; - boolean exitOnFailure = true; - /* - * Check for "-" options anywhere in command line - */ - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < args.length; ++i) { - if ("-i".equalsIgnoreCase(args[i])) { - rdr = new InputStreamReader(System.in); - // } else if("-o".equalsIgnoreCase(args[i])) { - // // shall we do something different? Output stream is - // already done... - } else if ("-f".equalsIgnoreCase(args[i])) { - if (args.length > i + 1) { - rdr = new FileReader(args[++i]); - } - } else if ("-a".equalsIgnoreCase(args[i])) { - exitOnFailure = false; - } else if ("-c".equalsIgnoreCase(args[i])) { - isConsole = true; - } else if ("-s".equalsIgnoreCase(args[i]) && args.length > i + 1) { - access.setProperty(Cmd.STARTDATE, args[++i]); - } else if ("-e".equalsIgnoreCase(args[i]) && args.length > i + 1) { - access.setProperty(Cmd.ENDDATE, args[++i]); - } else if ("-t".equalsIgnoreCase(args[i])) { - isTest = true; - } else if ("-d".equalsIgnoreCase(args[i])) { - showDetails = true; - } else if ("-n".equalsIgnoreCase(args[i])) { - ignoreDelay = true; - } else { - if (sb.length() > 0) { - sb.append(' '); - } - sb.append(args[i]); - } - } - - AAFConHttp aafcon = new AAFConHttp(access); -// -// SecurityInfoC si = aafcon.securityInfo(); -// Locator loc; - - aafsso.setLogDefault(); - aafsso.setStdErrDefault(); - - // Note, with AAF Locator, this may not longer be necessary 3/2018 Jonathan - if(!aafsso.loginOnly()) { -// try { -// loc = new AAFLocator(si,new URI(access.getProperty(Config.AAF_URL))); -// } catch (Throwable t) { -// aafsso.setStdErrDefault(); -// throw t; -// } finally { -// // Other Access is done writing to StdOut and StdErr, reset Std out -// aafsso.setLogDefault(); -// } - - TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); -// HMangr hman = new HMangr(access, loc).readTimeout(TIMEOUT).apiVersion(Config.AAF_DEFAULT_VERSION); - - if(access.getProperty(Config.AAF_DEFAULT_REALM)==null) { - access.setProperty(Config.AAF_DEFAULT_REALM, "people.osaaf.org"); - aafsso.addProp(Config.AAF_DEFAULT_REALM, "people.osaaf.org"); - } - - AAFcli aafcli = new AAFcli(access,env, new OutputStreamWriter(System.out), - aafcon.hman(), aafcon.securityInfo(), aafcon.securityInfo().defSS); -// new HBasicAuthSS(si,aafsso.user(), access.decrypt(aafsso.enc_pass(),false))); -// } - if(!ignoreDelay) { - File delay = new File("aafcli.delay"); - if(delay.exists()) { - BufferedReader br = new BufferedReader(new FileReader(delay)); - try { - globalDelay = Integer.parseInt(br.readLine()); - } catch(Exception e) { - access.log(Level.DEBUG,e); - } finally { - br.close(); - } - } - } - try { - if (isConsole) { - System.out.println("Type 'help' for short help or 'help -d' for detailed help with aafcli commands"); - System.out.println("Type '?' for help with command line editing"); - System.out.println("Type 'q', 'quit', or 'exit' to quit aafcli\n"); - - ConsoleReader reader = new ConsoleReader(); - try { - reader.setPrompt("aafcli > "); - - String line; - while ((line = reader.readLine()) != null) { - showDetails = (line.contains("-d"))?true:false; - - if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("q") || line.equalsIgnoreCase("exit")) { - break; - } else if (line.equalsIgnoreCase("--help -d") || line.equalsIgnoreCase("help -d") - || line.equalsIgnoreCase("help")) { - line = "--help"; - } else if (line.equalsIgnoreCase("cls")) { - reader.clearScreen(); - continue; - } else if (line.equalsIgnoreCase("?")) { - keyboardHelp(); - continue; - } - try { - aafcli.eval(line); - pw.flush(); - } catch (Exception e) { - pw.println(e.getMessage()); - pw.flush(); - } - } - } finally { - reader.close(); - } - } else if (rdr != null) { - BufferedReader br = new BufferedReader(rdr); - String line; - while ((line = br.readLine()) != null) { - if (!aafcli.eval(line) && exitOnFailure) { - rv = 1; - break; - } - } - } else { // just run the command line - aafcli.verbose(false); - if (sb.length() == 0) { - sb.append("--help"); - } - rv = aafcli.eval(sb.toString()) ? 0 : 1; - } - - } finally { - aafcli.close(); - - // Don't close if No Reader, or it's a Reader of Standard In - if (rdr != null && !(rdr instanceof InputStreamReader)) { - rdr.close(); - } - } - } - } - } finally { - aafsso.close(); - StringBuilder err = aafsso.err(); - if (err != null) { - err.append("to continue..."); - System.err.println(err); - } - } - if(noexit==null) { - return; - } - - - } catch (MessageException e) { - System.out.println("MessageException caught"); - - System.err.println(e.getMessage()); - } catch (Exception e) { - e.printStackTrace(System.err); - } - System.exit(rv); - } - - public boolean isTest() { - return AAFcli.isTest; - } - - public boolean isDetailed() { - return AAFcli.showDetails; - } - - public String typeString(Class cls, boolean json) { - return "application/" + cls.getSimpleName() + "+" + (json ? "json" : "xml");//+ ";version=" + hman.apiVersion(); - } - - public String forceString() { - return force; - } - - public boolean addRequest() { - return request; - } - - public void clearSingleLineProperties() { - force = null; - request = false; - showDetails = false; - } - - public void gui(boolean b) { - gui = b; - } + protected static PrintWriter pw; + protected HMangr hman; + // Storage for last reused client. We can do this + // because we're technically "single" threaded calls. + public Retryable prevCall; + + protected SecuritySetter ss; +// protected AuthzEnv env; + private boolean close; + private List cmds; + + // Lex State + private ArrayList expect = new ArrayList<>(); + private boolean verbose = true; + private int delay; + private SecurityInfoC si; + private boolean request = false; + private String force = null; + private boolean gui = false; + // Package on purpose + Access access; + AuthzEnv env; + + private static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); + private static boolean isConsole = false; + private static boolean isTest = false; + private static boolean showDetails = false; + private static boolean ignoreDelay = false; + private static int globalDelay=0; + + public static int timeout() { + return TIMEOUT; + } + + // Create when only have Access + public AAFcli(Access access, Writer wtr, HMangr hman, SecurityInfoC si, SecuritySetter ss) throws APIException, CadiException { + this(access,new AuthzEnv(access.getProperties()),wtr,hman, si,ss); + } + + public AAFcli(Access access, AuthzEnv env, Writer wtr, HMangr hman, SecurityInfoC si, SecuritySetter ss) throws APIException, CadiException { + this.env = env; + this.access = access; + this.ss = ss; + this.hman = hman; + this.si = si; + if (wtr instanceof PrintWriter) { + pw = (PrintWriter) wtr; + close = false; + } else { + pw = new PrintWriter(wtr); + close = true; + } + + /* + * Create Cmd Tree + */ + cmds = new ArrayList<>(); + + Role role = new Role(this); + cmds.add(new Help(this, cmds)); + cmds.add(new Version(this)); + cmds.add(new Perm(role)); + cmds.add(role); + cmds.add(new User(this)); + cmds.add(new NS(this)); + cmds.add(new Mgmt(this)); + } + + public void verbose(boolean v) { + verbose = v; + } + + public void close() { +// if (hman != null) { +// hman.close(); +// hman = null; +// } + if (close) { + pw.close(); + } + } + + public boolean eval(String line) throws Exception { + if (line.length() == 0) { + return true; + } else if (line.startsWith("#")) { + pw.println(line); + return true; + } + + String[] largs = argEval(line); + int idx = 0; + + // Variable replacement + StringBuilder sb = null; + while (idx < largs.length) { + int e = 0; + for (int v = largs[idx].indexOf("@["); v >= 0; v = largs[idx].indexOf("@[", v + 1)) { + if (sb == null) { + sb = new StringBuilder(); + } + sb.append(largs[idx], e, v); + if ((e = largs[idx].indexOf(']', v)) >= 0) { + String p = access.getProperty(largs[idx].substring(v + 2, e),null); + if(p==null) { + p = System.getProperty(largs[idx].substring(v+2,e)); + } + ++e; + if (p != null) { + sb.append(p); + } + } + } + if (sb != null && sb.length() > 0) { + sb.append(largs[idx], e, largs[idx].length()); + largs[idx] = sb.toString(); + sb.setLength(0); + } + ++idx; + } + + idx = 0; + boolean rv = true; + while (rv && idx < largs.length) { + // Allow Script to change Credential + if (!gui) { + if("as".equalsIgnoreCase(largs[idx])) { + if (largs.length > ++idx) { + // get Password from Props with ID as Key + String user = largs[idx++]; + int colon = user.indexOf(':'); + String pass; + if (colon > 0) { + pass = user.substring(colon + 1); + user = user.substring(0, colon); + } else { + pass = access.getProperty(user, null); + } + if (pass != null) { + pass = access.decrypt(pass, false); + access.getProperties().put(user, pass); + ss=new HBasicAuthSS(si, user, pass); + pw.println("as " + user); + } else { // get Pass from System Properties, under name of + // Tag + pw.println("ERROR: No password set for " + user); + rv = false; + } + continue; + } + } else if ("expect".equalsIgnoreCase(largs[idx])) { + expect.clear(); + if (largs.length > idx++) { + if (!"nothing".equals(largs[idx])) { + for (String str : largs[idx].split(",")) { + try { + if ("Exception".equalsIgnoreCase(str)) { + expect.add(-1); + } else { + expect.add(Integer.parseInt(str)); + } + } catch (NumberFormatException e) { + throw new CadiException("\"expect\" should be followed by Number"); + } + } + ++idx; + } + } + continue; + // Sleep, typically for reports, to allow DB to update + // Milliseconds + + } else if ("sleep".equalsIgnoreCase(largs[idx])) { + Integer t = Integer.parseInt(largs[++idx]); + pw.println("sleep " + t); + Thread.sleep(t); + ++idx; + continue; + } else if ("delay".equalsIgnoreCase(largs[idx])) { + delay = Integer.parseInt(largs[++idx]); + pw.println("delay " + delay); + ++idx; + continue; + } else if ("pause".equalsIgnoreCase(largs[idx])) { + pw.println("Press to continue..."); + ++idx; + // Sonar insists we do something with the string, though it's only a pause. Not very helpful... + String sonar = new BufferedReader(new InputStreamReader(System.in)).readLine(); + sonar=""; // this useless code brought to you by Sonar. + pw.print(sonar); + continue; + } else if ("exit".equalsIgnoreCase(largs[idx])) { + pw.println("Exiting..."); + return false; + } + + } + + if("REQUEST".equalsIgnoreCase(largs[idx])) { + request=true; + ++idx; + } else if("FORCE".equalsIgnoreCase(largs[idx])) { + force="true"; + ++idx; + } else if("DETAILS".equalsIgnoreCase(largs[idx])) { + showDetails=true; + ++idx; + } else if ("set".equalsIgnoreCase(largs[idx])) { + while (largs.length > ++idx) { + int equals = largs[idx].indexOf('='); + String tag, value; + if (equals < 0) { + tag = largs[idx]; + value = access.getProperty(Config.AAF_APPPASS,null); + if(value==null) { + break; + } else { + value = access.decrypt(value, false); + if(value==null) { + break; + } + access.getProperties().put(tag, value); + pw.println("set " + tag + " "); + } + } else { + tag = largs[idx].substring(0, equals); + value = largs[idx].substring(++equals); + pw.println("set " + tag + ' ' + value); + } + boolean isTrue = "TRUE".equalsIgnoreCase(value); + if("FORCE".equalsIgnoreCase(tag)) { + force = value; + } else if("REQUEST".equalsIgnoreCase(tag)) { + request = isTrue; + } else if("DETAILS".equalsIgnoreCase(tag)) { + showDetails = isTrue; + } else { + access.getProperties().put(tag, value); + } + } + continue; + // Allow Script to indicate if Failure is what is expected + } + + int ret = 0; + for (Cmd c : cmds) { + if (largs[idx].equalsIgnoreCase(c.getName())) { + if (verbose) { + pw.println(line); + if (expect.size() > 0) { + pw.print("** Expect "); + boolean first = true; + for (Integer i : expect) { + if (first) { + first = false; + } else { + pw.print(','); + } + pw.print(i); + } + pw.println(" **"); + } + } + try { + ret = c.exec(++idx, largs); + if (delay+globalDelay > 0) { + Thread.sleep((long)(delay+globalDelay)); + } + } catch (Exception e) { + if (expect.contains(-1)) { + pw.println(e.getMessage()); + ret = -1; + } else { + throw e; + } + } finally { + clearSingleLineProperties(); + } + rv = expect.isEmpty() ? true : expect.contains(ret); + if (verbose) { + if (rv) { + pw.println(); + } else { + pw.print("!!! Unexpected Return Code: "); + pw.print(ret); + pw.println(", VALIDATE OUTPUT!!!"); + } + } + return rv; + } + } + pw.write("Unknown Instruction \""); + pw.write(largs[idx]); + pw.write("\"\n"); + idx = largs.length;// always end after one command + } + return rv; + } + + private String[] argEval(String line) { + StringBuilder sb = new StringBuilder(); + ArrayList arr = new ArrayList<>(); + boolean start = true; + char quote = 0; + char last = 0; + for (int i = 0; i < line.length(); ++i) { + char ch; + if (Character.isWhitespace(ch = line.charAt(i))) { + if (start || last==',') { + continue; // trim + } else if (quote != 0) { + sb.append(ch); + } else { + arr.add(sb.toString()); + sb.setLength(0); + start = true; + } + } else if (ch == '\'' || ch == '"') { // toggle + if (quote == ch) { + quote = 0; + } else { + quote = ch; + } + } else if(ch=='|' && quote==0) { + arr.add(sb.toString()); + sb.setLength(0); + start = true; + } else { + start = false; + sb.append(ch); + last = ch; + } + } + if (sb.length() > 0) { + arr.add(sb.toString()); + } + + String[] rv = new String[arr.size()]; + arr.toArray(rv); + return rv; + } + + public static void keyboardHelp() { + System.out.println("'C-' means hold the ctrl key down while pressing the next key."); + System.out.println("'M-' means hold the alt key down while pressing the next key."); + System.out.println("For instance, C-b means hold ctrl key and press b, M-b means hold alt and press b\n"); + + System.out.println("Basic Keybindings:"); + System.out.println("\tC-l - clear screen"); + System.out.println("\tC-a - beginning of line"); + System.out.println("\tC-e - end of line"); + System.out.println("\tC-b - backward character (left arrow also works)"); + System.out.println("\tM-b - backward word"); + System.out.println("\tC-f - forward character (right arrow also works)"); + System.out.println("\tM-f - forward word"); + System.out.println("\tC-d - delete character under cursor"); + System.out.println("\tM-d - delete word forward"); + System.out.println("\tM-backspace - delete word backward"); + System.out.println("\tC-k - delete from cursor to end of line"); + System.out.println("\tC-u - delete entire line, regardless of cursor position\n"); + + System.out.println("Command History:"); + System.out.println("\tC-r - search backward in history (repeating C-r continues the search)"); + System.out.println("\tC-p - move backwards through history (up arrow also works)"); + System.out.println("\tC-n - move forwards through history (down arrow also works)\n"); + + } + + /** + * @param args + */ + public static void main(String[] args) { + int rv = 0; + + try { + AAFSSO aafsso = new AAFSSO(args); + String noexit = aafsso.access().getProperty("no_exit"); + try { + PropAccess access = aafsso.access(); + + if(aafsso.ok()) { + Define.set(access); + AuthzEnv env = new AuthzEnv(access); + + Reader rdr = null; + boolean exitOnFailure = true; + /* + * Check for "-" options anywhere in command line + */ + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < args.length; ++i) { + if ("-i".equalsIgnoreCase(args[i])) { + rdr = new InputStreamReader(System.in); + // } else if("-o".equalsIgnoreCase(args[i])) { + // // shall we do something different? Output stream is + // already done... + } else if ("-f".equalsIgnoreCase(args[i])) { + if (args.length > i + 1) { + rdr = new FileReader(args[++i]); + } + } else if ("-a".equalsIgnoreCase(args[i])) { + exitOnFailure = false; + } else if ("-c".equalsIgnoreCase(args[i])) { + isConsole = true; + } else if ("-s".equalsIgnoreCase(args[i]) && args.length > i + 1) { + access.setProperty(Cmd.STARTDATE, args[++i]); + } else if ("-e".equalsIgnoreCase(args[i]) && args.length > i + 1) { + access.setProperty(Cmd.ENDDATE, args[++i]); + } else if ("-t".equalsIgnoreCase(args[i])) { + isTest = true; + } else if ("-d".equalsIgnoreCase(args[i])) { + showDetails = true; + } else if ("-n".equalsIgnoreCase(args[i])) { + ignoreDelay = true; + } else { + if (sb.length() > 0) { + sb.append(' '); + } + sb.append(args[i]); + } + } + + AAFConHttp aafcon = new AAFConHttp(access); +// +// SecurityInfoC si = aafcon.securityInfo(); +// Locator loc; + + aafsso.setLogDefault(); + aafsso.setStdErrDefault(); + + // Note, with AAF Locator, this may not longer be necessary 3/2018 Jonathan + if(!aafsso.loginOnly()) { +// try { +// loc = new AAFLocator(si,new URI(access.getProperty(Config.AAF_URL))); +// } catch (Throwable t) { +// aafsso.setStdErrDefault(); +// throw t; +// } finally { +// // Other Access is done writing to StdOut and StdErr, reset Std out +// aafsso.setLogDefault(); +// } + + TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); +// HMangr hman = new HMangr(access, loc).readTimeout(TIMEOUT).apiVersion(Config.AAF_DEFAULT_VERSION); + + if(access.getProperty(Config.AAF_DEFAULT_REALM)==null) { + access.setProperty(Config.AAF_DEFAULT_REALM, "people.osaaf.org"); + aafsso.addProp(Config.AAF_DEFAULT_REALM, "people.osaaf.org"); + } + + AAFcli aafcli = new AAFcli(access,env, new OutputStreamWriter(System.out), + aafcon.hman(), aafcon.securityInfo(), aafcon.securityInfo().defSS); +// new HBasicAuthSS(si,aafsso.user(), access.decrypt(aafsso.enc_pass(),false))); +// } + if(!ignoreDelay) { + File delay = new File("aafcli.delay"); + if(delay.exists()) { + BufferedReader br = new BufferedReader(new FileReader(delay)); + try { + globalDelay = Integer.parseInt(br.readLine()); + } catch(Exception e) { + access.log(Level.DEBUG,e); + } finally { + br.close(); + } + } + } + try { + if (isConsole) { + System.out.println("Type 'help' for short help or 'help -d' for detailed help with aafcli commands"); + System.out.println("Type '?' for help with command line editing"); + System.out.println("Type 'q', 'quit', or 'exit' to quit aafcli\n"); + + ConsoleReader reader = new ConsoleReader(); + try { + reader.setPrompt("aafcli > "); + + String line; + while ((line = reader.readLine()) != null) { + showDetails = (line.contains("-d"))?true:false; + + if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("q") || line.equalsIgnoreCase("exit")) { + break; + } else if (line.equalsIgnoreCase("--help -d") || line.equalsIgnoreCase("help -d") + || line.equalsIgnoreCase("help")) { + line = "--help"; + } else if (line.equalsIgnoreCase("cls")) { + reader.clearScreen(); + continue; + } else if (line.equalsIgnoreCase("?")) { + keyboardHelp(); + continue; + } + try { + aafcli.eval(line); + pw.flush(); + } catch (Exception e) { + pw.println(e.getMessage()); + pw.flush(); + } + } + } finally { + reader.close(); + } + } else if (rdr != null) { + BufferedReader br = new BufferedReader(rdr); + String line; + while ((line = br.readLine()) != null) { + if (!aafcli.eval(line) && exitOnFailure) { + rv = 1; + break; + } + } + } else { // just run the command line + aafcli.verbose(false); + if (sb.length() == 0) { + sb.append("--help"); + } + rv = aafcli.eval(sb.toString()) ? 0 : 1; + } + + } finally { + aafcli.close(); + + // Don't close if No Reader, or it's a Reader of Standard In + if (rdr != null && !(rdr instanceof InputStreamReader)) { + rdr.close(); + } + } + } + } + } finally { + aafsso.close(); + StringBuilder err = aafsso.err(); + if (err != null) { + err.append("to continue..."); + System.err.println(err); + } + } + if(noexit==null) { + return; + } + + + } catch (MessageException e) { + System.out.println("MessageException caught"); + + System.err.println(e.getMessage()); + } catch (Exception e) { + e.printStackTrace(System.err); + } + System.exit(rv); + } + + public boolean isTest() { + return AAFcli.isTest; + } + + public boolean isDetailed() { + return AAFcli.showDetails; + } + + public String typeString(Class cls, boolean json) { + return "application/" + cls.getSimpleName() + "+" + (json ? "json" : "xml");//+ ";version=" + hman.apiVersion(); + } + + public String forceString() { + return force; + } + + public boolean addRequest() { + return request; + } + + public void clearSingleLineProperties() { + force = null; + request = false; + showDetails = false; + } + + public void gui(boolean b) { + gui = b; + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java index 7079fed7..168d2753 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java @@ -30,39 +30,39 @@ import org.onap.aaf.misc.env.APIException; public class BaseCmd extends Cmd { - protected List cmds; + protected List cmds; - public BaseCmd(AAFcli aafcli, String name, Param ... params) { - super(aafcli, null, name, params); - cmds = new ArrayList<>(); - } - - public BaseCmd(CMD parent, String name, Param ... params) { - super(parent.aafcli, parent, name, params); - cmds = new ArrayList<>(); - } + public BaseCmd(AAFcli aafcli, String name, Param ... params) { + super(aafcli, null, name, params); + cmds = new ArrayList<>(); + } + + public BaseCmd(CMD parent, String name, Param ... params) { + super(parent.aafcli, parent, name, params); + cmds = new ArrayList<>(); + } - - @Override - public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - if(args.length-idx<1) { - pw().println(build(new StringBuilder(),null).toString()); - } else { - String s = args[idx]; - String name; - Cmd empty = null; - for(Cmd c: cmds) { - name = c.getName(); - if(name==null && empty==null) { // Mark with Command is null, and take the first one. - empty = c; - } else if(s.equalsIgnoreCase(c.getName())) - return c.exec(idx+1, args); - } - if(empty!=null) { - return empty.exec(idx, args); // If name is null, don't account for it on command line. Jonathan 4-29 - } - pw().println("Instructions not understood."); - } - return 0; - } + + @Override + public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { + if(args.length-idx<1) { + pw().println(build(new StringBuilder(),null).toString()); + } else { + String s = args[idx]; + String name; + Cmd empty = null; + for(Cmd c: cmds) { + name = c.getName(); + if(name==null && empty==null) { // Mark with Command is null, and take the first one. + empty = c; + } else if(s.equalsIgnoreCase(c.getName())) + return c.exec(idx+1, args); + } + if(empty!=null) { + return empty.exec(idx, args); // If name is null, don't account for it on command line. Jonathan 4-29 + } + pw().println("Instructions not understood."); + } + return 0; + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java index 71643cd0..9ec126b4 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java @@ -56,487 +56,487 @@ import aaf.v2_0.Request; public abstract class Cmd { - // Sonar claims DateFormat is not thread safe. Leave as Instance Variable. - private final DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); - protected static final String BLANK = ""; - protected static final String COMMA = ","; // for use in splits + // Sonar claims DateFormat is not thread safe. Leave as Instance Variable. + private final DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); + protected static final String BLANK = ""; + protected static final String COMMA = ","; // for use in splits - protected static final int lineLength = 80; + protected static final int lineLength = 80; - private final static String hformat = "%-23s %-5s %-20s %-35s\n"; + private final static String hformat = "%-23s %-5s %-20s %-35s\n"; - public static final String STARTDATE = "startdate"; - public static final String ENDDATE = "enddate"; - - private String name; - private final Param[] params; - private int required; - protected final Cmd parent; - protected final List children; - private final static ConcurrentHashMap,RosettaDF> dfs = new ConcurrentHashMap<>(); - public final AAFcli aafcli; - protected Access access; - private AuthzEnv env; - private final String defaultRealm; + public static final String STARTDATE = "startdate"; + public static final String ENDDATE = "enddate"; + + private String name; + private final Param[] params; + private int required; + protected final Cmd parent; + protected final List children; + private final static ConcurrentHashMap,RosettaDF> dfs = new ConcurrentHashMap<>(); + public final AAFcli aafcli; + protected Access access; + private AuthzEnv env; + private final String defaultRealm; - public Cmd(AAFcli aafcli, String name, Param ... params) { - this(aafcli,null, name,params); - } + public Cmd(AAFcli aafcli, String name, Param ... params) { + this(aafcli,null, name,params); + } - public Cmd(Cmd parent, String name, Param ... params) { - this(parent.aafcli,parent, name,params); - } + public Cmd(Cmd parent, String name, Param ... params) { + this(parent.aafcli,parent, name,params); + } - Cmd(AAFcli aafcli, Cmd parent, String name, Param ... params) { - this.parent = parent; - this.aafcli = aafcli; - this.env = aafcli.env; - this.access = aafcli.access; - if(parent!=null) { - parent.children.add(this); - } - children = new ArrayList<>(); - this.params = params; - this.name = name; - required=0; - for(Param p : params) { - if(p.required) { - ++required; - } - } - - String temp = access.getProperty(Config.AAF_DEFAULT_REALM,null); - if(temp!=null && !temp.startsWith("@")) { - defaultRealm = '@' + temp; - } else { - defaultRealm=""; - } - } - - public final int exec(int idx, String ... args) throws CadiException, APIException, LocatorException { - if(args.length-idx(); + this.params = params; + this.name = name; + required=0; + for(Param p : params) { + if(p.required) { + ++required; + } + } + + String temp = access.getProperty(Config.AAF_DEFAULT_REALM,null); + if(temp!=null && !temp.startsWith("@")) { + defaultRealm = '@' + temp; + } else { + defaultRealm=""; + } + } + + public final int exec(int idx, String ... args) throws CadiException, APIException, LocatorException { + if(args.length-idx cls,boolean head) { - final String smeth = meth.name(); - if(head) { - sb.append('\n'); - detailLine(sb,indent,"APIs:"); - } - indent+=2; - multiChar(sb,indent,' ',0); - sb.append(smeth); - sb.append(' '); - sb.append(pathInfo); - String cliString = aafcli.typeString(cls,true); - if(indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) { - sb.append(" ..."); - multiChar(sb,indent+3+smeth.length(),' ',0); - } else { // same line - sb.append(' '); - } - sb.append(cliString); - } + protected void api(StringBuilder sb, int indent, HttpMethods meth, String pathInfo, Class cls,boolean head) { + final String smeth = meth.name(); + if(head) { + sb.append('\n'); + detailLine(sb,indent,"APIs:"); + } + indent+=2; + multiChar(sb,indent,' ',0); + sb.append(smeth); + sb.append(' '); + sb.append(pathInfo); + String cliString = aafcli.typeString(cls,true); + if(indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) { + sb.append(" ..."); + multiChar(sb,indent+3+smeth.length(),' ',0); + } else { // same line + sb.append(' '); + } + sb.append(cliString); + } - protected void multiChar(StringBuilder sb, int length, char c, int indent) { - sb.append('\n'); - for(int i=0;i ": "] "); - } - - boolean first = true; - for(Cmd child : children) { - if(!(child instanceof DeprecatedCMD)) { - if(first) { - first = false; - } else if(detail==null) { - multiChar(sb,indent,' ',0); - } else { - // Write parents for Detailed Report - Stack stack = new Stack(); - for(Cmd c = child.parent;c!=null;c=c.parent) { - if(c.name!=null) { - stack.push(c.name); - } - } - if(!stack.isEmpty()) { - sb.append(" "); - while(!stack.isEmpty()) { - sb.append(stack.pop()); - sb.append(' '); - } - } - } - child.build(sb,detail); - if(detail!=null) { - child.detailedHelp(4, detail); - // If Child wrote something, then add, bracketing by lines - if(detail.length()>0) { - multiChar(sb,80,'-',2); - sb.append(detail); - sb.append('\n'); - multiChar(sb,80,'-',2); - sb.append('\n'); - detail.setLength(0); // reuse - } else { - sb.append('\n'); - } - } - } - } - return sb; - } - - protected void error(Future future) { - StringBuilder sb = new StringBuilder("Failed"); - String desc = future.body(); - int code = future.code(); - if(desc==null || desc.length()==0) { - withCode(sb,code); - } else if(desc.startsWith("{")) { - StringReader sr = new StringReader(desc); - try { - // Note: 11-18-2013, JonathanGathman. This rather convoluted Message Structure required by TSS Restful Specs, reflecting "Northbound" practices. - Error err = getDF(Error.class).newData().in(TYPE.JSON).load(sr).asObject(); - sb.append(" ["); - sb.append(err.getMessageId()); - sb.append("]: "); - String messageBody = err.getText(); - List vars = err.getVariables(); - int pipe; - for (int varCounter=0;varCounter= 0) { - if((pipe = var.indexOf('|'))>=0) { // In AAF, we use a PIPE for Choice - if (aafcli.isTest()) { - String expiresStr = var.substring(pipe); - var = var.replace(expiresStr, "[Placeholder]"); - } else { - StringBuilder varsb = new StringBuilder(var); - varsb.deleteCharAt(pipe); - var = varsb.toString(); - } - messageBody = messageBody.replace("%" + varCounter, varCounter-1 + ") " + var); - } else { - messageBody = messageBody.replace("%" + varCounter, var); - } - } - } - sb.append(messageBody); - } catch (Exception e) { - withCode(sb,code); - sb.append(" (Note: Details cannot be obtained from Error Structure)"); - } - } else if(desc.startsWith("")){ // Core Jetty, etc sends HTML for Browsers - withCode(sb,code); - } else { - sb.append(" with code "); - sb.append(code); - sb.append(", "); - sb.append(desc); - } - pw().println(sb); - } + public StringBuilder build(StringBuilder sb, StringBuilder detail) { + if(name!=null) { + sb.append(name); + sb.append(' '); + } + int line = sb.lastIndexOf("\n")+1; + if(line<0) { + line=0; + } + int indent = sb.length()-line; + for(Param p : params) { + sb.append(p.required?'<':'['); + sb.append(p.tag); + sb.append(p.required?"> ": "] "); + } + + boolean first = true; + for(Cmd child : children) { + if(!(child instanceof DeprecatedCMD)) { + if(first) { + first = false; + } else if(detail==null) { + multiChar(sb,indent,' ',0); + } else { + // Write parents for Detailed Report + Stack stack = new Stack(); + for(Cmd c = child.parent;c!=null;c=c.parent) { + if(c.name!=null) { + stack.push(c.name); + } + } + if(!stack.isEmpty()) { + sb.append(" "); + while(!stack.isEmpty()) { + sb.append(stack.pop()); + sb.append(' '); + } + } + } + child.build(sb,detail); + if(detail!=null) { + child.detailedHelp(4, detail); + // If Child wrote something, then add, bracketing by lines + if(detail.length()>0) { + multiChar(sb,80,'-',2); + sb.append(detail); + sb.append('\n'); + multiChar(sb,80,'-',2); + sb.append('\n'); + detail.setLength(0); // reuse + } else { + sb.append('\n'); + } + } + } + } + return sb; + } + + protected void error(Future future) { + StringBuilder sb = new StringBuilder("Failed"); + String desc = future.body(); + int code = future.code(); + if(desc==null || desc.length()==0) { + withCode(sb,code); + } else if(desc.startsWith("{")) { + StringReader sr = new StringReader(desc); + try { + // Note: 11-18-2013, JonathanGathman. This rather convoluted Message Structure required by TSS Restful Specs, reflecting "Northbound" practices. + Error err = getDF(Error.class).newData().in(TYPE.JSON).load(sr).asObject(); + sb.append(" ["); + sb.append(err.getMessageId()); + sb.append("]: "); + String messageBody = err.getText(); + List vars = err.getVariables(); + int pipe; + for (int varCounter=0;varCounter= 0) { + if((pipe = var.indexOf('|'))>=0) { // In AAF, we use a PIPE for Choice + if (aafcli.isTest()) { + String expiresStr = var.substring(pipe); + var = var.replace(expiresStr, "[Placeholder]"); + } else { + StringBuilder varsb = new StringBuilder(var); + varsb.deleteCharAt(pipe); + var = varsb.toString(); + } + messageBody = messageBody.replace("%" + varCounter, varCounter-1 + ") " + var); + } else { + messageBody = messageBody.replace("%" + varCounter, var); + } + } + } + sb.append(messageBody); + } catch (Exception e) { + withCode(sb,code); + sb.append(" (Note: Details cannot be obtained from Error Structure)"); + } + } else if(desc.startsWith("")){ // Core Jetty, etc sends HTML for Browsers + withCode(sb,code); + } else { + sb.append(" with code "); + sb.append(code); + sb.append(", "); + sb.append(desc); + } + pw().println(sb); + } - - private void withCode(StringBuilder sb, Integer code) { - sb.append(" with code "); - sb.append(code); - switch(code) { - case 401: - sb.append(" (HTTP Not Authenticated)"); - break; - case 403: - sb.append(" (HTTP Forbidden)"); - break; - case 404: - sb.append(" (HTTP Not Found)"); - break; - default: - } - } + + private void withCode(StringBuilder sb, Integer code) { + sb.append(" with code "); + sb.append(code); + switch(code) { + case 401: + sb.append(" (HTTP Not Authenticated)"); + break; + case 403: + sb.append(" (HTTP Forbidden)"); + break; + case 404: + sb.append(" (HTTP Not Found)"); + break; + default: + } + } - /** - * Consistently set start and end dates from Requests (all derived from Request) - * @param req - */ - protected void setStartEnd(Request req) { - // Set Start/End Dates, if exist - String str; - if((str = access.getProperty(Cmd.STARTDATE,null))!=null) { - req.setStart(Chrono.timeStamp(Date.valueOf(str))); - } - - if((str = access.getProperty(Cmd.ENDDATE,null))!=null) { - req.setEnd(Chrono.timeStamp(Date.valueOf(str))); - } - } + /** + * Consistently set start and end dates from Requests (all derived from Request) + * @param req + */ + protected void setStartEnd(Request req) { + // Set Start/End Dates, if exist + String str; + if((str = access.getProperty(Cmd.STARTDATE,null))!=null) { + req.setStart(Chrono.timeStamp(Date.valueOf(str))); + } + + if((str = access.getProperty(Cmd.ENDDATE,null))!=null) { + req.setEnd(Chrono.timeStamp(Date.valueOf(str))); + } + } - /** - * For Derived classes, who have ENV in this parent - * - * @param cls - * @return - * @throws APIException - */ - protected RosettaDF getDF(Class cls) throws APIException { - return getDF(env,cls); - } + /** + * For Derived classes, who have ENV in this parent + * + * @param cls + * @return + * @throws APIException + */ + protected RosettaDF getDF(Class cls) throws APIException { + return getDF(env,cls); + } - /** - * This works well, making available for GUI, etc. - * @param env - * @param cls - * @return - * @throws APIException - */ - @SuppressWarnings("unchecked") - public static RosettaDF getDF(AuthzEnv env, Class cls) throws APIException { - RosettaDF rdf = (RosettaDF)dfs.get(cls); - if(rdf == null) { - rdf = env.newDataFactory(cls); - dfs.put(cls, rdf); - } - return rdf; - } + /** + * This works well, making available for GUI, etc. + * @param env + * @param cls + * @return + * @throws APIException + */ + @SuppressWarnings("unchecked") + public static RosettaDF getDF(AuthzEnv env, Class cls) throws APIException { + RosettaDF rdf = (RosettaDF)dfs.get(cls); + if(rdf == null) { + rdf = env.newDataFactory(cls); + dfs.put(cls, rdf); + } + return rdf; + } - public void activity(History history, String header) { - if (history.getItem().isEmpty()) { - int start = header.indexOf('['); - if (start >= 0) { - pw().println("No Activity Found for " + header.substring(start)); - } - } else { - pw().println(header); - for(int i=0;i items = history.getItem(); - java.util.Collections.sort(items, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return o2.getTimestamp().compare(o1.getTimestamp()); - } - }); - - for(History.Item item : items) { - GregorianCalendar gc = item.getTimestamp().toGregorianCalendar(); - pw().format(hformat, - dateFmt.format(gc.getTime()), - item.getTarget(), - item.getUser(), - item.getMemo()); - } - } - } - - /** - * Turn String Array into a | delimited String - * @param options - * @return - */ - public static String optionsToString(String[] options) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for(String s : options) { - if(first) { - first = false; - } else { - sb.append('|'); - } - sb.append(s); - } - return sb.toString(); - } - - /** - * return which index number the Option matches. - * - * throws an Exception if not part of this Option Set - * - * @param options - * @param test - * @return - * @throws Exception - */ - public int whichOption(String[] options, String test) throws CadiException { - for(int i=0;i= 0) { + pw().println("No Activity Found for " + header.substring(start)); + } + } else { + pw().println(header); + for(int i=0;i items = history.getItem(); + java.util.Collections.sort(items, new Comparator() { + @Override + public int compare(Item o1, Item o2) { + return o2.getTimestamp().compare(o1.getTimestamp()); + } + }); + + for(History.Item item : items) { + GregorianCalendar gc = item.getTimestamp().toGregorianCalendar(); + pw().format(hformat, + dateFmt.format(gc.getTime()), + item.getTarget(), + item.getUser(), + item.getMemo()); + } + } + } + + /** + * Turn String Array into a | delimited String + * @param options + * @return + */ + public static String optionsToString(String[] options) { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for(String s : options) { + if(first) { + first = false; + } else { + sb.append('|'); + } + sb.append(s); + } + return sb.toString(); + } + + /** + * return which index number the Option matches. + * + * throws an Exception if not part of this Option Set + * + * @param options + * @param test + * @return + * @throws Exception + */ + public int whichOption(String[] options, String test) throws CadiException { + for(int i=0;i RET same(Retryable retryable) throws APIException, CadiException, LocatorException { - // We're storing in AAFCli, because we know it's always the same, and single threaded - if(aafcli.prevCall!=null) { - retryable.item(aafcli.prevCall.item()); - retryable.lastClient=aafcli.prevCall.lastClient; - } - - RET ret = aafcli.hman.same(aafcli.ss,retryable); - - // Store last call in AAFcli, because Cmds are all different instances. - aafcli.prevCall = retryable; - return ret; - } + public RET same(Retryable retryable) throws APIException, CadiException, LocatorException { + // We're storing in AAFCli, because we know it's always the same, and single threaded + if(aafcli.prevCall!=null) { + retryable.item(aafcli.prevCall.item()); + retryable.lastClient=aafcli.prevCall.lastClient; + } + + RET ret = aafcli.hman.same(aafcli.ss,retryable); + + // Store last call in AAFcli, because Cmds are all different instances. + aafcli.prevCall = retryable; + return ret; + } - public RET all(Retryable retryable) throws APIException, CadiException, LocatorException { - this.setQueryParamsOn(retryable.lastClient); - return aafcli.hman.all(aafcli.ss,retryable); - } + public RET all(Retryable retryable) throws APIException, CadiException, LocatorException { + this.setQueryParamsOn(retryable.lastClient); + return aafcli.hman.all(aafcli.ss,retryable); + } - public RET oneOf(Retryable retryable,String host) throws APIException, CadiException, LocatorException { - this.setQueryParamsOn(retryable.lastClient); - return aafcli.hman.oneOf(aafcli.ss,retryable,true,host); - } + public RET oneOf(Retryable retryable,String host) throws APIException, CadiException, LocatorException { + this.setQueryParamsOn(retryable.lastClient); + return aafcli.hman.oneOf(aafcli.ss,retryable,true,host); + } - protected PrintWriter pw() { - return AAFcli.pw; - } + protected PrintWriter pw() { + return AAFcli.pw; + } - public String getName() { - return name; - } - - public void reportHead(String ... str) { - pw().println(); - boolean first = true; - int i=0; - for(String s : str) { - if(first) { - if(++i>1) { - first = false; - pw().print("["); - } - } else { - pw().print("] ["); - } - pw().print(s); - } - if(!first) { - pw().print(']'); - } - pw().println(); - reportLine(); - } - - public String reportColHead(String format, String ... args) { - pw().format(format,(Object[])args); - reportLine(); - return format; - } + public String getName() { + return name; + } + + public void reportHead(String ... str) { + pw().println(); + boolean first = true; + int i=0; + for(String s : str) { + if(first) { + if(++i>1) { + first = false; + pw().print("["); + } + } else { + pw().print("] ["); + } + pw().print(s); + } + if(!first) { + pw().print(']'); + } + pw().println(); + reportLine(); + } + + public String reportColHead(String format, String ... args) { + pw().format(format,(Object[])args); + reportLine(); + return format; + } - public void reportLine() { - for(int i=0;i rcli) { - StringBuilder sb=null; - String force; - if((force=aafcli.forceString())!=null) { - sb = new StringBuilder("force="); - sb.append(force); - } - if(aafcli.addRequest()) { - if(sb==null) { - sb = new StringBuilder("future=true"); - } else { - sb.append("&future=true"); - } - } - if(sb!=null && rcli!=null) { - rcli.setQueryParams(sb.toString()); - } - } + public void reportLine() { + for(int i=0;i rcli) { + StringBuilder sb=null; + String force; + if((force=aafcli.forceString())!=null) { + sb = new StringBuilder("force="); + sb.append(force); + } + if(aafcli.addRequest()) { + if(sb==null) { + sb = new StringBuilder("future=true"); + } else { + sb.append("&future=true"); + } + } + if(sb!=null && rcli!=null) { + rcli.setQueryParams(sb.toString()); + } + } // -// /** -// * If Force is set, will return True once only, then revert to "FALSE". -// * -// * @return -// */ -// protected String checkForce() { -// if(TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) { -// env.setProperty(FORCE, FALSE); -// return "true"; -// } -// return FALSE; -// } +// /** +// * If Force is set, will return True once only, then revert to "FALSE". +// * +// * @return +// */ +// protected String checkForce() { +// if(TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) { +// env.setProperty(FORCE, FALSE); +// return "true"; +// } +// return FALSE; +// } - public String toString() { - StringBuilder sb = new StringBuilder(); - if(parent==null) { // ultimate parent - build(sb,null); - return sb.toString(); - } else { - return parent.toString(); - } - } - -// private String getOrgRealm() { -// return ; -// } -// - /** - * Appends shortID with Realm, but only when allowed by Organization - * @throws OrganizationException - */ - public String fullID(String id) { - if(id != null) { - if (id.indexOf('@') < 0) { - id+=defaultRealm; - } else { - return id; // is already a full ID - } - } - return id; - } + public String toString() { + StringBuilder sb = new StringBuilder(); + if(parent==null) { // ultimate parent + build(sb,null); + return sb.toString(); + } else { + return parent.toString(); + } + } + +// private String getOrgRealm() { +// return ; +// } +// + /** + * Appends shortID with Realm, but only when allowed by Organization + * @throws OrganizationException + */ + public String fullID(String id) { + if(id != null) { + if (id.indexOf('@') < 0) { + id+=defaultRealm; + } else { + return id; // is already a full ID + } + } + return id; + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/DeprecatedCMD.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/DeprecatedCMD.java index b13c7333..dad2076f 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/DeprecatedCMD.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/DeprecatedCMD.java @@ -36,18 +36,18 @@ import org.onap.aaf.misc.env.APIException; * @param */ public class DeprecatedCMD extends BaseCmd { - private String text; + private String text; - @SuppressWarnings("unchecked") - public DeprecatedCMD(Cmd cmd, String name, String text) { - super((X)cmd,name); - this.text = text; - } + @SuppressWarnings("unchecked") + public DeprecatedCMD(Cmd cmd, String name, String text) { + super((X)cmd,name); + this.text = text; + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - pw().println(text); - return _idx; - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + pw().println(text); + return _idx; + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java index ca10915d..bd70d9e5 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java @@ -28,91 +28,91 @@ import org.onap.aaf.cadi.LocatorException; import org.onap.aaf.misc.env.APIException; public class Help extends Cmd { - private List cmds; + private List cmds; - public Help(AAFcli aafcli, List cmds) { - super(aafcli, "--help", - new Param("-d (more details)", false), - new Param("command",false)); - this.cmds = cmds; - } + public Help(AAFcli aafcli, List cmds) { + super(aafcli, "--help", + new Param("-d (more details)", false), + new Param("command",false)); + this.cmds = cmds; + } - @Override - public int _exec( int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - boolean first = true; - StringBuilder sb = new StringBuilder("AAF Command Line Tool"); - StringBuilder details; - multiChar(sb, 21, '-',0); - sb.append("\n SingleLine Commands"); - multiChar(sb, 21, '-',2); - sb.append("\n force - add to regular commands to override depency checks"); - sb.append("\n details - add to role list or perm list commands for rich format"); - multiChar(sb, 48, '-',2); - // if details !=null, then extra details are written to it. - details = aafcli.isDetailed()?new StringBuilder():null; + @Override + public int _exec( int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + boolean first = true; + StringBuilder sb = new StringBuilder("AAF Command Line Tool"); + StringBuilder details; + multiChar(sb, 21, '-',0); + sb.append("\n SingleLine Commands"); + multiChar(sb, 21, '-',2); + sb.append("\n force - add to regular commands to override depency checks"); + sb.append("\n details - add to role list or perm list commands for rich format"); + multiChar(sb, 48, '-',2); + // if details !=null, then extra details are written to it. + details = aafcli.isDetailed()?new StringBuilder():null; - String comp = args.length>idx?args[idx++]:null; - if("help".equalsIgnoreCase(comp)) { - build(sb,null); - detailedHelp(4, sb); - sb.append('\n'); - } else { - for(Cmd c : cmds) { - if(!(c instanceof DeprecatedCMD)) { - if(comp!=null) { - if(comp.equals(c.getName())) { - multiChar(sb,2,' ',0); - c.build(sb,details); - } - } else { - if(first) { - first=false; - } else { - multiChar(sb,80,'-',2); - } - multiChar(sb,2,' ',0); - c.build(sb,details); - if(details!=null) { - c.detailedHelp(4, sb); - // multiChar(sb,80,'-',2); - } - } - } - } - } - pw().println(sb.toString()); - return 200 /*HttpStatus.OK_200*/; - } - - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"To print main help, enter \"aafcli\" or \"aafcli --help \""); - detailLine(sb,indent,"To print narrow the help content, enter sub-entries after aafcli,"); - detailLine(sb,indent+2,"i.e. \"aafcli perm\""); - detailLine(sb,indent,"To see version of AAF CLI, enter \"aafcli --version \""); - sb.append('\n'); - detailLine(sb,indent,"State Commands: change variables or credentials between calls."); - indent+=4; - detailLine(sb,indent,"set = - Set any System Property to a new value"); - detailLine(sb,indent,"as - Change Credentials. Password may be encrypted"); - detailLine(sb,indent,"expect [int]* - In test mode, check for proper HTTP Status Codes"); - detailLine(sb,indent,"sleep - Wait for seconds"); - detailLine(sb,indent,"force - force deletions that have relationships"); - detailLine(sb,indent,"details - cause list commands (role, perm) to print rich format"); - detailLine(sb,indent," - In GUI CmdLine, use HourGlass option (top right)"); - sb.append('\n'); - detailLine(sb,indent-4,"CmdLine Arguments: change behavior of the aafcli program"); - detailLine(sb,indent,"-i - Read commands from Shell Standard Input"); - detailLine(sb,indent,"-f - Read commands from a file"); - detailLine(sb,indent,"-r - Clear Command Line SSO credential"); - detailLine(sb,indent,"-a - In test mode, do not stop execution on unexpected error"); - detailLine(sb,indent,"-t - Test Mode will not print variable fields that could break tc runs"); - detailLine(sb,indent+6,"such as expiration dates of a credential"); - detailLine(sb,indent,"-s - Request specific Start Date (not immediately)"); - detailLine(sb,indent+6,"Format YYYY-MM-DD. Can also be set with \"set " + Cmd.STARTDATE + "=\""); - detailLine(sb,indent,"-e - Set Expiration/End Date, where commands support"); - detailLine(sb,indent+6,"Format YYYY-MM-DD. Can also be set with \"set " + Cmd.ENDDATE + "=\""); - } + String comp = args.length>idx?args[idx++]:null; + if("help".equalsIgnoreCase(comp)) { + build(sb,null); + detailedHelp(4, sb); + sb.append('\n'); + } else { + for(Cmd c : cmds) { + if(!(c instanceof DeprecatedCMD)) { + if(comp!=null) { + if(comp.equals(c.getName())) { + multiChar(sb,2,' ',0); + c.build(sb,details); + } + } else { + if(first) { + first=false; + } else { + multiChar(sb,80,'-',2); + } + multiChar(sb,2,' ',0); + c.build(sb,details); + if(details!=null) { + c.detailedHelp(4, sb); + // multiChar(sb,80,'-',2); + } + } + } + } + } + pw().println(sb.toString()); + return 200 /*HttpStatus.OK_200*/; + } + + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"To print main help, enter \"aafcli\" or \"aafcli --help \""); + detailLine(sb,indent,"To print narrow the help content, enter sub-entries after aafcli,"); + detailLine(sb,indent+2,"i.e. \"aafcli perm\""); + detailLine(sb,indent,"To see version of AAF CLI, enter \"aafcli --version \""); + sb.append('\n'); + detailLine(sb,indent,"State Commands: change variables or credentials between calls."); + indent+=4; + detailLine(sb,indent,"set = - Set any System Property to a new value"); + detailLine(sb,indent,"as - Change Credentials. Password may be encrypted"); + detailLine(sb,indent,"expect [int]* - In test mode, check for proper HTTP Status Codes"); + detailLine(sb,indent,"sleep - Wait for seconds"); + detailLine(sb,indent,"force - force deletions that have relationships"); + detailLine(sb,indent,"details - cause list commands (role, perm) to print rich format"); + detailLine(sb,indent," - In GUI CmdLine, use HourGlass option (top right)"); + sb.append('\n'); + detailLine(sb,indent-4,"CmdLine Arguments: change behavior of the aafcli program"); + detailLine(sb,indent,"-i - Read commands from Shell Standard Input"); + detailLine(sb,indent,"-f - Read commands from a file"); + detailLine(sb,indent,"-r - Clear Command Line SSO credential"); + detailLine(sb,indent,"-a - In test mode, do not stop execution on unexpected error"); + detailLine(sb,indent,"-t - Test Mode will not print variable fields that could break tc runs"); + detailLine(sb,indent+6,"such as expiration dates of a credential"); + detailLine(sb,indent,"-s - Request specific Start Date (not immediately)"); + detailLine(sb,indent+6,"Format YYYY-MM-DD. Can also be set with \"set " + Cmd.STARTDATE + "=\""); + detailLine(sb,indent,"-e - Set Expiration/End Date, where commands support"); + detailLine(sb,indent+6,"Format YYYY-MM-DD. Can also be set with \"set " + Cmd.ENDDATE + "=\""); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/MessageException.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/MessageException.java index 3ed81222..934212ca 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/MessageException.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/MessageException.java @@ -31,16 +31,16 @@ package org.onap.aaf.auth.cmd; * */ public class MessageException extends Exception { - /** - * - */ - private static final long serialVersionUID = 8143933588878259048L; + /** + * + */ + private static final long serialVersionUID = 8143933588878259048L; - /** - * @param Message - */ - public MessageException(String msg) { - super(msg); - } + /** + * @param Message + */ + public MessageException(String msg) { + super(msg); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Param.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Param.java index 0d79df0a..8e485528 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Param.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Param.java @@ -22,16 +22,16 @@ package org.onap.aaf.auth.cmd; public class Param { - public final String tag; - public final boolean required; - - /** - * - * @param t - * @param b - */ - public Param(String t, boolean required) { - tag = t; - this.required=required; - } + public final String tag; + public final boolean required; + + /** + * + * @param t + * @param b + */ + public Param(String t, boolean required) { + tag = t; + this.required=required; + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java index fe04dac7..9bb01956 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java @@ -29,15 +29,15 @@ import org.onap.aaf.misc.env.APIException; public class Version extends Cmd { - public Version(AAFcli aafcli) { - super(aafcli, "--version"); - } + public Version(AAFcli aafcli) { + super(aafcli, "--version"); + } - @Override - protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { - pw().println("AAF Command Line Tool"); - pw().print("Version: "); - pw().println(Config.AAF_DEFAULT_VERSION); - return 200 /*HttpStatus.OK_200;*/; - } + @Override + protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { + pw().println("AAF Command Line Tool"); + pw().print("Version: "); + pw().println(Config.AAF_DEFAULT_VERSION); + return 200 /*HttpStatus.OK_200;*/; + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Cache.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Cache.java index cd153537..fd257d63 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Cache.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Cache.java @@ -25,8 +25,8 @@ import org.onap.aaf.auth.cmd.BaseCmd; import org.onap.aaf.misc.env.APIException; public class Cache extends BaseCmd { - public Cache(Mgmt mgmt) throws APIException { - super(mgmt, "cache"); - cmds.add(new Clear(this)); - } + public Cache(Mgmt mgmt) throws APIException { + super(mgmt, "cache"); + cmds.add(new Clear(this)); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java index a18c1c48..ca8a72ca 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java @@ -39,47 +39,47 @@ import org.onap.aaf.misc.env.APIException; * */ public class Clear extends Cmd { - public Clear(Cache parent) { - super(parent,"clear", - new Param("name[,name]*",true)); - } + public Clear(Cache parent) { + super(parent,"clear", + new Param("name[,name]*",true)); + } - @Override - public int _exec(int _idx, String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - int rv=409; - for(final String name : args[idx++].split(COMMA)) { - rv = all(new Retryable() { - @Override - public Integer code(Rcli client) throws APIException, CadiException { - int rv = 409; - Future fp = client.delete( - "/mgmt/cache/"+name, - Void.class - ); - if(fp.get(AAFcli.timeout())) { - pw().println("Cleared Cache for " + name + " on " + client); - rv=200; - } else { - if(rv==409)rv = fp.code(); - error(fp); - } - return rv; - } - }); - } - return rv; - } + @Override + public int _exec(int _idx, String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + int rv=409; + for(final String name : args[idx++].split(COMMA)) { + rv = all(new Retryable() { + @Override + public Integer code(Rcli client) throws APIException, CadiException { + int rv = 409; + Future fp = client.delete( + "/mgmt/cache/"+name, + Void.class + ); + if(fp.get(AAFcli.timeout())) { + pw().println("Cleared Cache for " + name + " on " + client); + rv=200; + } else { + if(rv==409)rv = fp.code(); + error(fp); + } + return rv; + } + }); + } + return rv; + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Clear the cache for certain tables"); - indent+=2; - detailLine(sb,indent,"name - name of table or 'all'"); - detailLine(sb,indent+14,"Must have admin rights to '" + Define.ROOT_NS() + '\''); - indent-=2; - api(sb,indent,HttpMethods.DELETE,"mgmt/cache/:name",Void.class,true); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Clear the cache for certain tables"); + indent+=2; + detailLine(sb,indent,"name - name of table or 'all'"); + detailLine(sb,indent+14,"Must have admin rights to '" + Define.ROOT_NS() + '\''); + indent-=2; + api(sb,indent,HttpMethods.DELETE,"mgmt/cache/:name",Void.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java index b8fc4a23..17f23729 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java @@ -34,68 +34,68 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.misc.env.APIException; public class Deny extends BaseCmd { - private final static String[] options = {"add","del"}; + private final static String[] options = {"add","del"}; - public Deny(Mgmt mgmt) throws APIException { - super(mgmt, "deny"); - cmds.add(new DenySomething(this,"ip","ipv4or6[,ipv4or6]*")); - cmds.add(new DenySomething(this,"id","identity[,identity]*")); - } - - public class DenySomething extends Cmd { + public Deny(Mgmt mgmt) throws APIException { + super(mgmt, "deny"); + cmds.add(new DenySomething(this,"ip","ipv4or6[,ipv4or6]*")); + cmds.add(new DenySomething(this,"id","identity[,identity]*")); + } + + public class DenySomething extends Cmd { - private boolean isID; + private boolean isID; - public DenySomething(Deny deny, String type, String repeatable) { - super(deny, type, - new Param(optionsToString(options),true), - new Param(repeatable,true)); - isID = "id".equals(type); - } + public DenySomething(Deny deny, String type, String repeatable) { + super(deny, type, + new Param(optionsToString(options),true), + new Param(repeatable,true)); + isID = "id".equals(type); + } - @Override - protected int _exec(int _idx, String... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - String action = args[idx++]; - final int option = whichOption(options, action); - int rv=409; - for(final String name : args[idx++].split(COMMA)) { - final String append; - if(isID && name.indexOf("@")<0) { - append='@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); - } else { - append = ""; - } - final String path = "/mgmt/deny/"+getName() + '/'+ name + append; - rv = all(new Retryable() { - @Override - public Integer code(Rcli client) throws APIException, CadiException { - int rv = 409; - Future fp; - String resp; - switch(option) { - case 0: - fp = client.create(path, Void.class); - resp = " added"; - break; - default: - fp = client.delete(path, Void.class); - resp = " deleted"; - } - if(fp.get(AAFcli.timeout())) { - pw().println(name + append + resp + " on " + client); - rv=fp.code(); - } else { - if(rv==409)rv = fp.code(); - error(fp); - } - return rv; - } - }); - } - return rv; - } + @Override + protected int _exec(int _idx, String... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + String action = args[idx++]; + final int option = whichOption(options, action); + int rv=409; + for(final String name : args[idx++].split(COMMA)) { + final String append; + if(isID && name.indexOf("@")<0) { + append='@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); + } else { + append = ""; + } + final String path = "/mgmt/deny/"+getName() + '/'+ name + append; + rv = all(new Retryable() { + @Override + public Integer code(Rcli client) throws APIException, CadiException { + int rv = 409; + Future fp; + String resp; + switch(option) { + case 0: + fp = client.create(path, Void.class); + resp = " added"; + break; + default: + fp = client.delete(path, Void.class); + resp = " deleted"; + } + if(fp.get(AAFcli.timeout())) { + pw().println(name + append + resp + " on " + client); + rv=fp.code(); + } else { + if(rv==409)rv = fp.code(); + error(fp); + } + return rv; + } + }); + } + return rv; + } - } + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java index 80ad8a46..535de3bb 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java @@ -35,74 +35,74 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.misc.env.APIException; public class Log extends BaseCmd { - private final static String[] options = {"add","del"}; + private final static String[] options = {"add","del"}; - public Log(Mgmt mgmt) throws APIException { - super(mgmt, "log", - new Param(optionsToString(options),true), - new Param("id[,id]*",true)); - } - - @Override - public int _exec(int _idx, String ... args) throws CadiException, APIException, LocatorException { - int rv=409; - int idx = _idx; - final int option = whichOption(options, args[idx++]); + public Log(Mgmt mgmt) throws APIException { + super(mgmt, "log", + new Param(optionsToString(options),true), + new Param("id[,id]*",true)); + } + + @Override + public int _exec(int _idx, String ... args) throws CadiException, APIException, LocatorException { + int rv=409; + int idx = _idx; + final int option = whichOption(options, args[idx++]); - for(String name : args[idx++].split(COMMA)) { - final String fname; - if(name.indexOf("@")<0) { - fname=name+'@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); - } else { - fname = name; - } - - rv = all(new Retryable() { - @Override - public Integer code(Rcli client) throws APIException, CadiException { - int rv = 409; - Future fp; - String str = "/mgmt/log/id/"+fname; - String msg; - switch(option) { - case 0: - fp = client.create(str,Void.class); - msg = "Added"; - break; - case 1: - fp = client.delete(str,Void.class); - msg = "Deleted"; - break; - default: - fp = null; - msg = "Ignored"; - } - - if(fp!=null) { - if(fp.get(AAFcli.timeout())) { - pw().println(msg + " Special Log for " + fname + " on " + client); - rv=200; - } else { - if(rv==409)rv = fp.code(); - error(fp); - } - return rv; - } - return rv; - } - }); - } - return rv; - } + for(String name : args[idx++].split(COMMA)) { + final String fname; + if(name.indexOf("@")<0) { + fname=name+'@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); + } else { + fname = name; + } + + rv = all(new Retryable() { + @Override + public Integer code(Rcli client) throws APIException, CadiException { + int rv = 409; + Future fp; + String str = "/mgmt/log/id/"+fname; + String msg; + switch(option) { + case 0: + fp = client.create(str,Void.class); + msg = "Added"; + break; + case 1: + fp = client.delete(str,Void.class); + msg = "Deleted"; + break; + default: + fp = null; + msg = "Ignored"; + } + + if(fp!=null) { + if(fp.get(AAFcli.timeout())) { + pw().println(msg + " Special Log for " + fname + " on " + client); + rv=200; + } else { + if(rv==409)rv = fp.code(); + error(fp); + } + return rv; + } + return rv; + } + }); + } + return rv; + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Clear the cache for certain tables"); - indent+=2; - detailLine(sb,indent,"name - name of table or 'all'"); - detailLine(sb,indent+14,"Must have admin rights to '" + Define.ROOT_NS() + '\''); - indent-=2; - api(sb,indent,HttpMethods.DELETE,"mgmt/cache/:name",Void.class,true); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Clear the cache for certain tables"); + indent+=2; + detailLine(sb,indent,"name - name of table or 'all'"); + detailLine(sb,indent+14,"Must have admin rights to '" + Define.ROOT_NS() + '\''); + indent-=2; + api(sb,indent,HttpMethods.DELETE,"mgmt/cache/:name",Void.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Mgmt.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Mgmt.java index 6b5e2d66..e5097a32 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Mgmt.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Mgmt.java @@ -26,11 +26,11 @@ import org.onap.aaf.auth.cmd.BaseCmd; import org.onap.aaf.misc.env.APIException; public class Mgmt extends BaseCmd { - public Mgmt(AAFcli aafcli) throws APIException { - super(aafcli, "mgmt"); - cmds.add(new Cache(this)); - cmds.add(new Deny(this)); - cmds.add(new Log(this)); - cmds.add(new Session(this)); - } + public Mgmt(AAFcli aafcli) throws APIException { + super(aafcli, "mgmt"); + cmds.add(new Cache(this)); + cmds.add(new Deny(this)); + cmds.add(new Log(this)); + cmds.add(new Session(this)); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java index cfd2fa8d..a52d5dc7 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java @@ -39,45 +39,45 @@ import org.onap.aaf.misc.env.APIException; * */ public class SessClear extends Cmd { - public SessClear(Session parent) { - super(parent,"clear", - new Param("machine",true)); - } + public SessClear(Session parent) { + super(parent,"clear", + new Param("machine",true)); + } - @Override - public int _exec(int idx, String ... args) throws CadiException, APIException, LocatorException { - int rv=409; - String machine = args[idx++]; - rv = oneOf(new Retryable() { - @Override - public Integer code(Rcli client) throws APIException, CadiException { - int rv = 409; - Future fp = client.delete( - "/mgmt/dbsession", - Void.class - ); - if(fp.get(AAFcli.timeout())) { - pw().println("Cleared DBSession on " + client); - rv=200; - } else { - if(rv==409)rv = fp.code(); - error(fp); - } - return rv; - } - },machine); - return rv; - } + @Override + public int _exec(int idx, String ... args) throws CadiException, APIException, LocatorException { + int rv=409; + String machine = args[idx++]; + rv = oneOf(new Retryable() { + @Override + public Integer code(Rcli client) throws APIException, CadiException { + int rv = 409; + Future fp = client.delete( + "/mgmt/dbsession", + Void.class + ); + if(fp.get(AAFcli.timeout())) { + pw().println("Cleared DBSession on " + client); + rv=200; + } else { + if(rv==409)rv = fp.code(); + error(fp); + } + return rv; + } + },machine); + return rv; + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Clear the cache for certain tables"); - indent+=2; - detailLine(sb,indent,"name - name of table or 'all'"); - detailLine(sb,indent+14,"Must have admin rights to " + Define.ROOT_NS() + '\''); - indent-=2; - api(sb,indent,HttpMethods.DELETE,"mgmt/cache/:name",Void.class,true); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Clear the cache for certain tables"); + indent+=2; + detailLine(sb,indent,"name - name of table or 'all'"); + detailLine(sb,indent+14,"Must have admin rights to " + Define.ROOT_NS() + '\''); + indent-=2; + api(sb,indent,HttpMethods.DELETE,"mgmt/cache/:name",Void.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Session.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Session.java index 5929caea..fa3eb522 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Session.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Session.java @@ -25,8 +25,8 @@ import org.onap.aaf.auth.cmd.BaseCmd; import org.onap.aaf.misc.env.APIException; public class Session extends BaseCmd { - public Session(Mgmt mgmt) throws APIException { - super(mgmt, "dbsession"); - cmds.add(new SessClear(this)); - } + public Session(Mgmt mgmt) throws APIException { + super(mgmt, "dbsession"); + cmds.add(new SessClear(this)); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java index 363c7482..f1952fa9 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java @@ -33,71 +33,71 @@ import org.onap.aaf.cadi.client.Retryable; import org.onap.aaf.misc.env.APIException; public class Admin extends BaseCmd { - private final static String[] options = {"add","del"}; + private final static String[] options = {"add","del"}; - public Admin(NS ns) throws APIException { - super(ns,"admin", - new Param(optionsToString(options),true), - new Param("ns-name",true), - new Param("id[,id]*",true) - ); - } + public Admin(NS ns) throws APIException { + super(ns,"admin", + new Param(optionsToString(options),true), + new Param("ns-name",true), + new Param("id[,id]*",true) + ); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final int option = whichOption(options, args[idx++]); - final String ns = args[idx++]; - final String ids[] = args[idx++].split(","); + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final int option = whichOption(options, args[idx++]); + final String ns = args[idx++]; + final String ids[] = args[idx++].split(","); - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = null; - for(String id : ids) { - id = fullID(id); - String verb; - switch(option) { - case 0: - fp = client.create("/authz/ns/"+ns+"/admin/"+id,Void.class); - verb = " added to "; - break; - case 1: - fp = client.delete("/authz/ns/"+ns+"/admin/"+id,Void.class); - verb = " deleted from "; - break; - default: - throw new CadiException("Bad Argument"); - }; - - if(fp.get(AAFcli.timeout())) { - pw().append("Admin "); - pw().append(id); - pw().append(verb); - pw().println(ns); - } else { - error(fp); - return fp.code(); - } - - } - return fp==null?500:fp.code(); - } - }); - } + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = null; + for(String id : ids) { + id = fullID(id); + String verb; + switch(option) { + case 0: + fp = client.create("/authz/ns/"+ns+"/admin/"+id,Void.class); + verb = " added to "; + break; + case 1: + fp = client.delete("/authz/ns/"+ns+"/admin/"+id,Void.class); + verb = " deleted from "; + break; + default: + throw new CadiException("Bad Argument"); + }; + + if(fp.get(AAFcli.timeout())) { + pw().append("Admin "); + pw().append(id); + pw().append(verb); + pw().println(ns); + } else { + error(fp); + return fp.code(); + } + + } + return fp==null?500:fp.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Add or Delete Administrator to/from Namespace"); - indent+=4; - detailLine(sb,indent,"name - Name of Namespace"); - detailLine(sb,indent,"id - Credential of Person(s) to be Administrator"); - sb.append('\n'); - detailLine(sb,indent,"aafcli will call API on each ID presented."); - indent-=4; - api(sb,indent,HttpMethods.POST,"authz/ns//admin/",Void.class,true); - api(sb,indent,HttpMethods.DELETE,"authz/ns//admin/",Void.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Add or Delete Administrator to/from Namespace"); + indent+=4; + detailLine(sb,indent,"name - Name of Namespace"); + detailLine(sb,indent,"id - Credential of Person(s) to be Administrator"); + sb.append('\n'); + detailLine(sb,indent,"aafcli will call API on each ID presented."); + indent-=4; + api(sb,indent,HttpMethods.POST,"authz/ns//admin/",Void.class,true); + api(sb,indent,HttpMethods.DELETE,"authz/ns//admin/",Void.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java index 19caa4f4..f1b2621d 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java @@ -33,83 +33,83 @@ import org.onap.aaf.cadi.client.Retryable; import org.onap.aaf.misc.env.APIException; public class Attrib extends BaseCmd { - private final static String[] options = {"add","upd","del"}; + private final static String[] options = {"add","upd","del"}; - public Attrib(NS ns) throws APIException { - super(ns,"attrib", - new Param(optionsToString(options),true), - new Param("ns-name",true), - new Param("key",true), - new Param("value",false) - ); - } + public Attrib(NS ns) throws APIException { + super(ns,"attrib", + new Param(optionsToString(options),true), + new Param("ns-name",true), + new Param("key",true), + new Param("value",false) + ); + } - @Override - public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { - final int option = whichOption(options, args[idx]); - final String ns = args[idx+1]; - final String key = args[idx+2]; - final String value; - if(option!=2) { - if(args.length<=idx+3) { - throw new CadiException("Not added: Need more Data"); - } - value = args[idx+3]; - } else { - value = ""; - } - - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = null; - String message; - switch(option) { - case 0: - fp = client.create("/authz/ns/"+ns+"/attrib/"+key+'/'+value,Void.class); - message = String.format("Add Attrib %s=%s to %s", - key,value,ns); - break; - case 1: - fp = client.update("/authz/ns/"+ns+"/attrib/"+key+'/'+value); - message = String.format("Update Attrib %s=%s for %s", - key,value,ns); - break; - case 2: - fp = client.delete("/authz/ns/"+ns+"/attrib/"+key,Void.class); - message = String.format("Attrib %s deleted from %s", - key,ns); - break; - default: - throw new CadiException("Bad Argument"); - }; - if(fp==null) { - return 500; - } else { - if(fp.get(AAFcli.timeout())) { - pw().println(message); - } else { - error(fp); - } - - return fp.code(); - } - } - }); - } + @Override + public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { + final int option = whichOption(options, args[idx]); + final String ns = args[idx+1]; + final String key = args[idx+2]; + final String value; + if(option!=2) { + if(args.length<=idx+3) { + throw new CadiException("Not added: Need more Data"); + } + value = args[idx+3]; + } else { + value = ""; + } + + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = null; + String message; + switch(option) { + case 0: + fp = client.create("/authz/ns/"+ns+"/attrib/"+key+'/'+value,Void.class); + message = String.format("Add Attrib %s=%s to %s", + key,value,ns); + break; + case 1: + fp = client.update("/authz/ns/"+ns+"/attrib/"+key+'/'+value); + message = String.format("Update Attrib %s=%s for %s", + key,value,ns); + break; + case 2: + fp = client.delete("/authz/ns/"+ns+"/attrib/"+key,Void.class); + message = String.format("Attrib %s deleted from %s", + key,ns); + break; + default: + throw new CadiException("Bad Argument"); + }; + if(fp==null) { + return 500; + } else { + if(fp.get(AAFcli.timeout())) { + pw().println(message); + } else { + error(fp); + } + + return fp.code(); + } + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Add or Delete Administrator to/from Namespace"); - indent+=4; - detailLine(sb,indent,"name - Name of Namespace"); - detailLine(sb,indent,"id - Credential of Person(s) to be Administrator"); - sb.append('\n'); - detailLine(sb,indent,"aafcli will call API on each ID presented."); - indent-=4; - api(sb,indent,HttpMethods.POST,"authz/ns//admin/",Void.class,true); - api(sb,indent,HttpMethods.DELETE,"authz/ns//admin/",Void.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Add or Delete Administrator to/from Namespace"); + indent+=4; + detailLine(sb,indent,"name - Name of Namespace"); + detailLine(sb,indent,"id - Credential of Person(s) to be Administrator"); + sb.append('\n'); + detailLine(sb,indent,"aafcli will call API on each ID presented."); + indent-=4; + api(sb,indent,HttpMethods.POST,"authz/ns//admin/",Void.class,true); + api(sb,indent,HttpMethods.DELETE,"authz/ns//admin/",Void.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java index a62d5531..1719ada7 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java @@ -39,85 +39,85 @@ import aaf.v2_0.NsRequest; * */ public class Create extends Cmd { - private static final String COMMA = ","; + private static final String COMMA = ","; - public Create(NS parent) { - super(parent,"create", - new Param("ns-name",true), - new Param("owner (id[,id]*)",true), - new Param("admin (id[,id]*)",false)); - } + public Create(NS parent) { + super(parent,"create", + new Param("ns-name",true), + new Param("owner (id[,id]*)",true), + new Param("admin (id[,id]*)",false)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; - final NsRequest nr = new NsRequest(); - - nr.setName(args[idx++]); - String[] responsible = args[idx++].split(COMMA); - for(String s : responsible) { - nr.getResponsible().add(fullID(s)); - } - String[] admin; - if(args.length>idx) { - admin = args[idx++].split(COMMA); - } else { - admin = responsible; - } - for(String s : admin) { - nr.getAdmin().add(fullID(s)); - } - - // Set Start/End commands - setStartEnd(nr); - - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - // Requestable - setQueryParamsOn(client); - Future fp = client.create( - "/authz/ns", - getDF(NsRequest.class), - nr - ); - if(fp.get(AAFcli.timeout())) { - pw().println("Created Namespace"); - } else { - if(fp.code()==202) { - pw().println("Namespace Creation Accepted, but requires Approvals before actualizing"); - } else { - error(fp); - } - } - return fp.code(); - } - }); - } + final NsRequest nr = new NsRequest(); + + nr.setName(args[idx++]); + String[] responsible = args[idx++].split(COMMA); + for(String s : responsible) { + nr.getResponsible().add(fullID(s)); + } + String[] admin; + if(args.length>idx) { + admin = args[idx++].split(COMMA); + } else { + admin = responsible; + } + for(String s : admin) { + nr.getAdmin().add(fullID(s)); + } + + // Set Start/End commands + setStartEnd(nr); + + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + // Requestable + setQueryParamsOn(client); + Future fp = client.create( + "/authz/ns", + getDF(NsRequest.class), + nr + ); + if(fp.get(AAFcli.timeout())) { + pw().println("Created Namespace"); + } else { + if(fp.code()==202) { + pw().println("Namespace Creation Accepted, but requires Approvals before actualizing"); + } else { + error(fp); + } + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Create a Namespace"); - indent+=2; - detailLine(sb,indent,"name - Namespaces are dot-delimited, ex com.att.myapp"); - detailLine(sb,indent+14,"and must be created with parent credentials."); - detailLine(sb,indent+14,"Ex: to create com.att.myapp, you must be admin for com.att"); - detailLine(sb,indent+14,"or com"); - detailLine(sb,indent,"owner - This is the person(s) who is responsible for the "); - detailLine(sb,indent+14,"app. These person or persons receive Notifications and"); - detailLine(sb,indent+14,"approves Requests regarding this Namespace. Companies have"); - detailLine(sb,indent+14,"Policies as to who may take on this responsibility"); - detailLine(sb,indent,"admin - These are the people who are allowed to make changes on"); - detailLine(sb,indent+14,"the Namespace, including creating Roles, Permissions"); - detailLine(sb,indent+14,"and Credentials"); - sb.append('\n'); - detailLine(sb,indent,"Namespaces can be created even though there are Roles/Permissions which"); - detailLine(sb,indent,"start with the requested sub-namespace. They are reassigned to the"); - detailLine(sb,indent,"Child Namespace"); - indent-=2; - api(sb,indent,HttpMethods.POST,"authz/ns",NsRequest.class,true); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Create a Namespace"); + indent+=2; + detailLine(sb,indent,"name - Namespaces are dot-delimited, ex com.att.myapp"); + detailLine(sb,indent+14,"and must be created with parent credentials."); + detailLine(sb,indent+14,"Ex: to create com.att.myapp, you must be admin for com.att"); + detailLine(sb,indent+14,"or com"); + detailLine(sb,indent,"owner - This is the person(s) who is responsible for the "); + detailLine(sb,indent+14,"app. These person or persons receive Notifications and"); + detailLine(sb,indent+14,"approves Requests regarding this Namespace. Companies have"); + detailLine(sb,indent+14,"Policies as to who may take on this responsibility"); + detailLine(sb,indent,"admin - These are the people who are allowed to make changes on"); + detailLine(sb,indent+14,"the Namespace, including creating Roles, Permissions"); + detailLine(sb,indent+14,"and Credentials"); + sb.append('\n'); + detailLine(sb,indent,"Namespaces can be created even though there are Roles/Permissions which"); + detailLine(sb,indent,"start with the requested sub-namespace. They are reassigned to the"); + detailLine(sb,indent,"Child Namespace"); + indent-=2; + api(sb,indent,HttpMethods.POST,"authz/ns",NsRequest.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java index 19915f4e..99ac7ed2 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java @@ -38,52 +38,52 @@ import org.onap.aaf.misc.env.APIException; * */ public class Delete extends Cmd { - public Delete(NS parent) { - super(parent,"delete", - new Param("ns-name",true)); - } + public Delete(NS parent) { + super(parent,"delete", + new Param("ns-name",true)); + } - @Override - public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int index = idx; - StringBuilder path = new StringBuilder("/authz/ns/"); - path.append(args[index++]); - - // Send "Force" if set - setQueryParamsOn(client); - Future fp = client.delete(path.toString(),Void.class); - - if(fp.get(AAFcli.timeout())) { - pw().println("Deleted Namespace"); - } else { - error(fp); - } - return fp.code(); - } - }); - } + @Override + public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int index = idx; + StringBuilder path = new StringBuilder("/authz/ns/"); + path.append(args[index++]); + + // Send "Force" if set + setQueryParamsOn(client); + Future fp = client.delete(path.toString(),Void.class); + + if(fp.get(AAFcli.timeout())) { + pw().println("Deleted Namespace"); + } else { + error(fp); + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Delete a Namespace"); - indent+=4; - detailLine(sb,indent,"Namespaces cannot normally be deleted when there are still credentials,"); - detailLine(sb,indent,"permissions or roles associated with them. These can be deleted"); - detailLine(sb,indent,"automatically by setting \"force\" property."); - detailLine(sb,indent,"i.e. set force=true or just starting with \"force\""); - detailLine(sb,indent," (note force is unset after first use)"); - sb.append('\n'); - detailLine(sb,indent,"If \"set force=move\" is set, credentials are deleted, but "); - detailLine(sb,indent,"Permissions and Roles are assigned to the Parent Namespace instead of"); - detailLine(sb,indent,"being deleted. Similarly, Namespaces can be created even though there"); - detailLine(sb,indent,"are Roles/Perms whose type starts with the requested sub-namespace."); - detailLine(sb,indent,"They are simply reassigned to the Child Namespace"); - indent-=4; - api(sb,indent,HttpMethods.DELETE,"authz/ns/[?force=true]",Void.class,true); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Delete a Namespace"); + indent+=4; + detailLine(sb,indent,"Namespaces cannot normally be deleted when there are still credentials,"); + detailLine(sb,indent,"permissions or roles associated with them. These can be deleted"); + detailLine(sb,indent,"automatically by setting \"force\" property."); + detailLine(sb,indent,"i.e. set force=true or just starting with \"force\""); + detailLine(sb,indent," (note force is unset after first use)"); + sb.append('\n'); + detailLine(sb,indent,"If \"set force=move\" is set, credentials are deleted, but "); + detailLine(sb,indent,"Permissions and Roles are assigned to the Parent Namespace instead of"); + detailLine(sb,indent,"being deleted. Similarly, Namespaces can be created even though there"); + detailLine(sb,indent,"are Roles/Perms whose type starts with the requested sub-namespace."); + detailLine(sb,indent,"They are simply reassigned to the Child Namespace"); + indent-=4; + api(sb,indent,HttpMethods.DELETE,"authz/ns/[?force=true]",Void.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java index af40ff99..18823297 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java @@ -35,60 +35,60 @@ import org.onap.aaf.misc.env.APIException; import aaf.v2_0.NsRequest; public class Describe extends Cmd { - private static final String NS_PATH = "/authz/ns"; - public Describe(NS parent) { - super(parent,"describe", - new Param("ns-name",true), - new Param("description",true)); - } + private static final String NS_PATH = "/authz/ns"; + public Describe(NS parent) { + super(parent,"describe", + new Param("ns-name",true), + new Param("description",true)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String name = args[idx++]; - StringBuilder desc = new StringBuilder(); - while (idx < args.length) { - desc.append(args[idx++] + ' '); - } - - NsRequest nsr = new NsRequest(); - nsr.setName(name); - nsr.setDescription(desc.toString()); - - // Set Start/End commands - setStartEnd(nsr); - - Future fn = null; - int rv; + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String name = args[idx++]; + StringBuilder desc = new StringBuilder(); + while (idx < args.length) { + desc.append(args[idx++] + ' '); + } + + NsRequest nsr = new NsRequest(); + nsr.setName(name); + nsr.setDescription(desc.toString()); + + // Set Start/End commands + setStartEnd(nsr); + + Future fn = null; + int rv; - fn = client.update( - NS_PATH, - getDF(NsRequest.class), - nsr - ); + fn = client.update( + NS_PATH, + getDF(NsRequest.class), + nsr + ); - if(fn.get(AAFcli.timeout())) { - rv=fn.code(); - pw().println("Description added to Namespace"); - } else { - if((rv=fn.code())==202) { - pw().print("Adding description"); - pw().println(" Accepted, but requires Approvals before actualizing"); - } else { - error(fn); - } - } - return rv; - } - }); - } + if(fn.get(AAFcli.timeout())) { + rv=fn.code(); + pw().println("Description added to Namespace"); + } else { + if((rv=fn.code())==202) { + pw().print("Adding description"); + pw().println(" Accepted, but requires Approvals before actualizing"); + } else { + error(fn); + } + } + return rv; + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Add a description to a namespace"); - api(sb,indent,HttpMethods.PUT,"authz/ns",NsRequest.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Add a description to a namespace"); + api(sb,indent,HttpMethods.PUT,"authz/ns",NsRequest.class,true); + } } \ No newline at end of file diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java index 387bae00..01b3ad14 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java @@ -38,139 +38,139 @@ import aaf.v2_0.Users.User; public class List extends BaseCmd { - public List(NS parent) { - super(parent,"list"); - cmds.add(new ListByName(this)); - -// TODO: uncomment when on cassandra 2.1.2 if we like cli command to get all ns's -// a user is admin or responsible for - cmds.add(new ListAdminResponsible(this)); - cmds.add(new DeprecatedCMD(this,"responsible","'responsible' is deprecated. use 'owner'")); // deprecated - cmds.add(new ListActivity(this)); - cmds.add(new ListUsers(this)); - cmds.add(new ListChildren(this)); - cmds.add(new ListNsKeysByAttrib(this)); - } + public List(NS parent) { + super(parent,"list"); + cmds.add(new ListByName(this)); + +// TODO: uncomment when on cassandra 2.1.2 if we like cli command to get all ns's +// a user is admin or responsible for + cmds.add(new ListAdminResponsible(this)); + cmds.add(new DeprecatedCMD(this,"responsible","'responsible' is deprecated. use 'owner'")); // deprecated + cmds.add(new ListActivity(this)); + cmds.add(new ListUsers(this)); + cmds.add(new ListChildren(this)); + cmds.add(new ListNsKeysByAttrib(this)); + } - private static final String sformat = " %-72s\n"; - protected static final String kformat = " %-72s\n"; + private static final String sformat = " %-72s\n"; + protected static final String kformat = " %-72s\n"; - - public void report(Future fp, String ... str) { - reportHead(str); - if(fp==null) { - pw().println(" *** Namespace Not Found ***"); - } - - if(fp!=null && fp.value!=null) { - for(Ns ns : fp.value.getNs()) { - pw().println(ns.getName()); - if (this.aafcli.isDetailed()) { - pw().println(" Description"); - pw().format(sformat,ns.getDescription()==null?"":ns.getDescription()); - } - if(ns.getAdmin().size()>0) { - pw().println(" Administrators"); - for(String admin : ns.getAdmin()) { - pw().format(sformat,admin); - } - } - if(ns.getResponsible().size()>0) { - pw().println(" Owners (Responsible for Namespace)"); - for(String responsible : ns.getResponsible()) { - pw().format(sformat,responsible); - } - } - if(ns.getAttrib().size()>0) { - pw().println(" Namespace Attributes"); - for( Ns.Attrib attr : ns.getAttrib()) { - StringBuilder sb = new StringBuilder(attr.getKey()); - if(attr.getValue()==null || attr.getValue().length()>0) { - sb.append('='); - sb.append(attr.getValue()); - } - pw().format(sformat,sb.toString()); - } - - } - } - } - } - - public void reportName(Future fp, String ... str) { - reportHead(str); - if(fp!=null && fp.value!=null) { - java.util.List nss = fp.value.getNs(); - Collections.sort(nss, new Comparator() { - @Override - public int compare(Ns ns1, Ns ns2) { - return ns1.getName().compareTo(ns2.getName()); - } - }); - - for(Ns ns : nss) { - pw().println(ns.getName()); - if (this.aafcli.isDetailed() && ns.getDescription() != null) { - pw().println(" " + ns.getDescription()); - } - } - } - } + + public void report(Future fp, String ... str) { + reportHead(str); + if(fp==null) { + pw().println(" *** Namespace Not Found ***"); + } + + if(fp!=null && fp.value!=null) { + for(Ns ns : fp.value.getNs()) { + pw().println(ns.getName()); + if (this.aafcli.isDetailed()) { + pw().println(" Description"); + pw().format(sformat,ns.getDescription()==null?"":ns.getDescription()); + } + if(ns.getAdmin().size()>0) { + pw().println(" Administrators"); + for(String admin : ns.getAdmin()) { + pw().format(sformat,admin); + } + } + if(ns.getResponsible().size()>0) { + pw().println(" Owners (Responsible for Namespace)"); + for(String responsible : ns.getResponsible()) { + pw().format(sformat,responsible); + } + } + if(ns.getAttrib().size()>0) { + pw().println(" Namespace Attributes"); + for( Ns.Attrib attr : ns.getAttrib()) { + StringBuilder sb = new StringBuilder(attr.getKey()); + if(attr.getValue()==null || attr.getValue().length()>0) { + sb.append('='); + sb.append(attr.getValue()); + } + pw().format(sformat,sb.toString()); + } + + } + } + } + } + + public void reportName(Future fp, String ... str) { + reportHead(str); + if(fp!=null && fp.value!=null) { + java.util.List nss = fp.value.getNs(); + Collections.sort(nss, new Comparator() { + @Override + public int compare(Ns ns1, Ns ns2) { + return ns1.getName().compareTo(ns2.getName()); + } + }); + + for(Ns ns : nss) { + pw().println(ns.getName()); + if (this.aafcli.isDetailed() && ns.getDescription() != null) { + pw().println(" " + ns.getDescription()); + } + } + } + } - public void reportRole(Future fr) { - if(fr!=null && fr.value!=null && fr.value.getRole().size()>0) { - pw().println(" Roles"); - for(aaf.v2_0.Role r : fr.value.getRole()) { - pw().format(sformat,r.getName()); - } - } - } + public void reportRole(Future fr) { + if(fr!=null && fr.value!=null && fr.value.getRole().size()>0) { + pw().println(" Roles"); + for(aaf.v2_0.Role r : fr.value.getRole()) { + pw().format(sformat,r.getName()); + } + } + } - private static final String pformat = " %-30s %-24s %-15s\n"; - public void reportPerm(Future fp) { - if(fp!=null && fp.value!=null && fp.value.getPerm().size()>0) { - pw().println(" Permissions"); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { - pw().format(pformat,p.getType(),p.getInstance(),p.getAction()); - } - } - } - - - private static final String cformat = " %-30s %-6s %-24s\n"; - public void reportCred(Future fc) { - if(fc!=null && fc.value!=null && fc.value.getUser().size()>0) { - pw().println(" Credentials"); - java.util.List users = fc.value.getUser(); - Collections.sort(users, new Comparator() { - @Override - public int compare(User u1, User u2) { - return u1.getId().compareTo(u2.getId()); - } - }); - for(aaf.v2_0.Users.User u : users) { - if (this.aafcli.isTest()) { - pw().format(sformat,u.getId()); - } else { - pw().format(cformat,u.getId(),getType(u),Chrono.niceDateStamp(u.getExpires())); - } - } - } - } + private static final String pformat = " %-30s %-24s %-15s\n"; + public void reportPerm(Future fp) { + if(fp!=null && fp.value!=null && fp.value.getPerm().size()>0) { + pw().println(" Permissions"); + for(aaf.v2_0.Perm p : fp.value.getPerm()) { + pw().format(pformat,p.getType(),p.getInstance(),p.getAction()); + } + } + } + + + private static final String cformat = " %-30s %-6s %-24s\n"; + public void reportCred(Future fc) { + if(fc!=null && fc.value!=null && fc.value.getUser().size()>0) { + pw().println(" Credentials"); + java.util.List users = fc.value.getUser(); + Collections.sort(users, new Comparator() { + @Override + public int compare(User u1, User u2) { + return u1.getId().compareTo(u2.getId()); + } + }); + for(aaf.v2_0.Users.User u : users) { + if (this.aafcli.isTest()) { + pw().format(sformat,u.getId()); + } else { + pw().format(cformat,u.getId(),getType(u),Chrono.niceDateStamp(u.getExpires())); + } + } + } + } - public static String getType(User u) { - Integer type; - if((type=u.getType())==null) { - type = 9999; - } - switch(type) { - case 1: return "U/P"; - case 2: return "U/P2"; - case 10: return "Cert"; - case 200: return "x509"; - default: - return "n/a"; - } - } + public static String getType(User u) { + Integer type; + if((type=u.getType())==null) { + type = 9999; + } + switch(type) { + case 1: return "U/P"; + case 2: return "U/P2"; + case 10: return "Cert"; + case 200: return "x509"; + default: + return "n/a"; + } + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java index 4cc4236e..52b9a108 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java @@ -39,41 +39,41 @@ import aaf.v2_0.History; * */ public class ListActivity extends Cmd { - private static final String HEADER = "List Activity of Namespace"; - - public ListActivity(List parent) { - super(parent,"activity", - new Param("ns-name",true)); - } + private static final String HEADER = "List Activity of Namespace"; + + public ListActivity(List parent) { + super(parent,"activity", + new Param("ns-name",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String ns = args[idx++]; - - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/hist/ns/"+ns, - getDF(History.class) - ); - - if(fp.get(AAFcli.timeout())) { - activity(fp.value, HEADER + " [ " + ns + " ]"); - } else { - error(fp); - } - return fp.code(); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/hist/ns/",History.class,true); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String ns = args[idx++]; + + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authz/hist/ns/"+ns, + getDF(History.class) + ); + + if(fp.get(AAFcli.timeout())) { + activity(fp.value, HEADER + " [ " + ns + " ]"); + } else { + error(fp); + } + return fp.code(); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/hist/ns/",History.class,true); + } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java index e17436a2..06de6cab 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java @@ -35,43 +35,43 @@ import org.onap.aaf.misc.env.APIException; import aaf.v2_0.Nss; public class ListAdminResponsible extends Cmd { - private static final String HEADER="List Namespaces with "; - private final static String[] options = {"admin","owner"}; - - public ListAdminResponsible(List parent) { - super(parent,null, - new Param(optionsToString(options),true), - new Param("user",true)); - } + private static final String HEADER="List Namespaces with "; + private final static String[] options = {"admin","owner"}; + + public ListAdminResponsible(List parent) { + super(parent,null, + new Param(optionsToString(options),true), + new Param("user",true)); + } - @Override - protected int _exec(final int index, final String... args) throws CadiException, APIException, LocatorException { + @Override + protected int _exec(final int index, final String... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String title = args[idx++]; - String user = fullID(args[idx++]); - String apipart = "owner".equals(title)?"responsible":title; - - Future fn = client.read("/authz/nss/"+apipart+"/"+user,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - ((List)parent).reportName(fn,HEADER + title + " privileges for ",user); - } else if(fn.code()==404) { - ((List)parent).report(null,HEADER + title + " privileges for ",user); - return 200; - } else { - error(fn); - } - return fn.code(); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER + "admin or owner privileges for user"); - api(sb,indent,HttpMethods.GET,"authz/nss//",Nss.class,true); - } + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String title = args[idx++]; + String user = fullID(args[idx++]); + String apipart = "owner".equals(title)?"responsible":title; + + Future fn = client.read("/authz/nss/"+apipart+"/"+user,getDF(Nss.class)); + if(fn.get(AAFcli.timeout())) { + ((List)parent).reportName(fn,HEADER + title + " privileges for ",user); + } else if(fn.code()==404) { + ((List)parent).report(null,HEADER + title + " privileges for ",user); + return 200; + } else { + error(fn); + } + return fn.code(); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER + "admin or owner privileges for user"); + api(sb,indent,HttpMethods.GET,"authz/nss//",Nss.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java index ffc1af89..ffd3cf01 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java @@ -44,62 +44,62 @@ import aaf.v2_0.Users; * */ public class ListByName extends Cmd { - private static final String HEADER="List Namespaces by Name"; - - public ListByName(List parent) { - super(parent,"name", - new Param("ns-name",true)); - } + private static final String HEADER="List Namespaces by Name"; + + public ListByName(List parent) { + super(parent,"name", + new Param("ns-name",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String ns=args[idx++]; - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - ((List)parent).report(fn,HEADER,ns); - if(fn.value!=null) { - for(Ns n : fn.value.getNs()) { - Future fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); - if(fr.get(AAFcli.timeout())) { - ((List)parent).reportRole(fr); - } - } - for(Ns n : fn.value.getNs()) { - Future fp = client.read("/authz/perms/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":""), getDF(Perms.class)); - if(fp.get(AAFcli.timeout())) { - ((List)parent).reportPerm(fp); - } - } - for(Ns n : fn.value.getNs()) { - Future fu = client.read("/authn/creds/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":""), getDF(Users.class)); - if(fu.get(AAFcli.timeout())) { - ((List)parent).reportCred(fu); - } - } - } - } else if(fn.code()==404) { - ((List)parent).report(null,HEADER,ns); - return 200; - } else { - error(fn); - } - return fn.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String ns=args[idx++]; + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); + if(fn.get(AAFcli.timeout())) { + ((List)parent).report(fn,HEADER,ns); + if(fn.value!=null) { + for(Ns n : fn.value.getNs()) { + Future fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); + if(fr.get(AAFcli.timeout())) { + ((List)parent).reportRole(fr); + } + } + for(Ns n : fn.value.getNs()) { + Future fp = client.read("/authz/perms/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":""), getDF(Perms.class)); + if(fp.get(AAFcli.timeout())) { + ((List)parent).reportPerm(fp); + } + } + for(Ns n : fn.value.getNs()) { + Future fu = client.read("/authn/creds/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":""), getDF(Users.class)); + if(fu.get(AAFcli.timeout())) { + ((List)parent).reportCred(fu); + } + } + } + } else if(fn.code()==404) { + ((List)parent).report(null,HEADER,ns); + return 200; + } else { + error(fn); + } + return fn.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); - detailLine(sb,indent,"Indirectly uses:"); - api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); - api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,false); - api(sb,indent,HttpMethods.GET,"authn/creds/ns/",Users.class,false); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); + detailLine(sb,indent,"Indirectly uses:"); + api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); + api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,false); + api(sb,indent,HttpMethods.GET,"authn/creds/ns/",Users.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java index 07dcf701..6d514df8 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java @@ -41,41 +41,41 @@ import aaf.v2_0.Nss.Ns; * */ public class ListChildren extends Cmd { - private static final String HEADER="List Child Namespaces"; - - public ListChildren(List parent) { - super(parent,"children", - new Param("ns-name",true)); - } + private static final String HEADER="List Child Namespaces"; + + public ListChildren(List parent) { + super(parent,"children", + new Param("ns-name",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String ns=args[idx++]; - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fn = client.read("/authz/nss/children/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - parent.reportHead(HEADER); - for(Ns ns : fn.value.getNs()) { - pw().format(List.kformat, ns.getName()); - } - } else if(fn.code()==404) { - ((List)parent).report(null,HEADER,ns); - return 200; - } else { - error(fn); - } - return fn.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String ns=args[idx++]; + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fn = client.read("/authz/nss/children/"+ns,getDF(Nss.class)); + if(fn.get(AAFcli.timeout())) { + parent.reportHead(HEADER); + for(Ns ns : fn.value.getNs()) { + pw().format(List.kformat, ns.getName()); + } + } else if(fn.code()==404) { + ((List)parent).report(null,HEADER,ns); + return 200; + } else { + error(fn); + } + return fn.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/nss/children/",Nss.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/nss/children/",Nss.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java index 7c449565..df72ff08 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java @@ -44,45 +44,45 @@ import aaf.v2_0.Users; * */ public class ListNsKeysByAttrib extends Cmd { - private static final String HEADER="List Namespace Names by Attribute"; - - public ListNsKeysByAttrib(List parent) { - super(parent,"keys", - new Param("attrib",true)); - } + private static final String HEADER="List Namespace Names by Attribute"; + + public ListNsKeysByAttrib(List parent) { + super(parent,"keys", + new Param("attrib",true)); + } - @Override - public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { - final String attrib=args[idx]; - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fn = client.read("/authz/ns/attrib/"+attrib,getDF(Keys.class)); - if(fn.get(AAFcli.timeout())) { - parent.reportHead(HEADER); - for(String key : fn.value.getKey()) { - pw().printf(List.kformat, key); - } - } else if(fn.code()==404) { - parent.reportHead(HEADER); - pw().println(" *** No Namespaces Found ***"); - return 200; - } else { - error(fn); - } - return fn.code(); - } - }); - } + @Override + public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { + final String attrib=args[idx]; + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fn = client.read("/authz/ns/attrib/"+attrib,getDF(Keys.class)); + if(fn.get(AAFcli.timeout())) { + parent.reportHead(HEADER); + for(String key : fn.value.getKey()) { + pw().printf(List.kformat, key); + } + } else if(fn.code()==404) { + parent.reportHead(HEADER); + pw().println(" *** No Namespaces Found ***"); + return 200; + } else { + error(fn); + } + return fn.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); - detailLine(sb,indent,"Indirectly uses:"); - api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); - api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,false); - api(sb,indent,HttpMethods.GET,"authn/creds/ns/",Users.class,false); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); + detailLine(sb,indent,"Indirectly uses:"); + api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); + api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,false); + api(sb,indent,HttpMethods.GET,"authn/creds/ns/",Users.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsers.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsers.java index 7106ba6d..4bd3aed4 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsers.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsers.java @@ -31,46 +31,46 @@ import aaf.v2_0.Nss; import aaf.v2_0.Users.User; public class ListUsers extends BaseCmd { - - public ListUsers(List parent) { - super(parent,"user"); - cmds.add(new ListUsersWithPerm(this)); - cmds.add(new ListUsersInRole(this)); - } - private static final Future dummy = new Future(){ + + public ListUsers(List parent) { + super(parent,"user"); + cmds.add(new ListUsersWithPerm(this)); + cmds.add(new ListUsersInRole(this)); + } + private static final Future dummy = new Future(){ - @Override - public boolean get(int timeout) throws CadiException { - return false; - } + @Override + public boolean get(int timeout) throws CadiException { + return false; + } - @Override - public int code() { - return 0; - } + @Override + public int code() { + return 0; + } - @Override - public String body() { - return null; - } + @Override + public String body() { + return null; + } - @Override - public String header(String tag) { - return null; - } - }; - public void report(String header, String ns) { - ((List)parent).report(dummy, header,ns); - } + @Override + public String header(String tag) { + return null; + } + }; + public void report(String header, String ns) { + ((List)parent).report(dummy, header,ns); + } - public void report(String subHead) { - pw().println(subHead); - } + public void report(String subHead) { + pw().println(subHead); + } - private static final String uformat = "%s%-50s expires:%02d/%02d/%04d\n"; - public void report(String prefix, User u) { - XMLGregorianCalendar xgc = u.getExpires(); - pw().format(uformat,prefix,u.getId(),xgc.getMonth()+1,xgc.getDay(),xgc.getYear()); - } + private static final String uformat = "%s%-50s expires:%02d/%02d/%04d\n"; + public void report(String prefix, User u) { + XMLGregorianCalendar xgc = u.getExpires(); + pw().format(uformat,prefix,u.getId(),xgc.getMonth()+1,xgc.getDay(),xgc.getYear()); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java index 01017e03..1347b918 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java @@ -48,81 +48,81 @@ import aaf.v2_0.Users.User; * */ public class ListUsersContact extends Cmd { - private static final String HEADER="List Contacts of Namespace "; - - public ListUsersContact(ListUsers parent) { - super(parent,"contact", - new Param("ns-name",true)); - } + private static final String HEADER="List Contacts of Namespace "; + + public ListUsersContact(ListUsers parent) { + super(parent,"contact", + new Param("ns-name",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String ns=args[idx++]; - final boolean detail = aafcli.isDetailed(); - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - ((ListUsers)parent).report(HEADER,ns); - Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - if(fn.value!=null) { - Set uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { - Future fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); - if(fr.get(AAFcli.timeout())) { - for(Role r : fr.value.getRole()) { - if(detail) { - ((ListUsers)parent).report(r.getName()); - } - Future fus = client.read( - "/authz/users/role/"+r.getName(), - getDF(Users.class) - ); - if(fus.get(AAFcli.timeout())) { - for(User u : fus.value.getUser()) { - if(detail) { - ((ListUsers)parent).report(" ",u); - } else { - uset.add(u.getId()); - } - } - } else if(fn.code()==404) { - return 200; - } - } - } - } - if(uset!=null) { - for(String u : uset) { - pw().print(" "); - pw().println(u); - } - } - } - } else if(fn.code()==404) { - return 200; - } else { - error(fn); - } - return fn.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String ns=args[idx++]; + final boolean detail = aafcli.isDetailed(); + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + ((ListUsers)parent).report(HEADER,ns); + Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); + if(fn.get(AAFcli.timeout())) { + if(fn.value!=null) { + Set uset = detail?null:new HashSet<>(); + for(Ns n : fn.value.getNs()) { + Future fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); + if(fr.get(AAFcli.timeout())) { + for(Role r : fr.value.getRole()) { + if(detail) { + ((ListUsers)parent).report(r.getName()); + } + Future fus = client.read( + "/authz/users/role/"+r.getName(), + getDF(Users.class) + ); + if(fus.get(AAFcli.timeout())) { + for(User u : fus.value.getUser()) { + if(detail) { + ((ListUsers)parent).report(" ",u); + } else { + uset.add(u.getId()); + } + } + } else if(fn.code()==404) { + return 200; + } + } + } + } + if(uset!=null) { + for(String u : uset) { + pw().print(" "); + pw().println(u); + } + } + } + } else if(fn.code()==404) { + return 200; + } else { + error(fn); + } + return fn.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=4; - detailLine(sb,indent,"Report Users associated with this Namespace's Roles"); - sb.append('\n'); - detailLine(sb,indent,"If \"set details=true\" is specified, then all roles are printed "); - detailLine(sb,indent,"with the associated users and expiration dates"); - indent-=4; - api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); - api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); - api(sb,indent,HttpMethods.GET,"authz/users/role/",Users.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=4; + detailLine(sb,indent,"Report Users associated with this Namespace's Roles"); + sb.append('\n'); + detailLine(sb,indent,"If \"set details=true\" is specified, then all roles are printed "); + detailLine(sb,indent,"with the associated users and expiration dates"); + indent-=4; + api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); + api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); + api(sb,indent,HttpMethods.GET,"authz/users/role/",Users.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java index e49a6e97..301e1508 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java @@ -48,81 +48,81 @@ import aaf.v2_0.Users.User; * */ public class ListUsersInRole extends Cmd { - private static final String HEADER="List Users in Roles of Namespace "; - - public ListUsersInRole(ListUsers parent) { - super(parent,"role", - new Param("ns-name",true)); - } + private static final String HEADER="List Users in Roles of Namespace "; + + public ListUsersInRole(ListUsers parent) { + super(parent,"role", + new Param("ns-name",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String ns=args[idx++]; - final boolean detail = aafcli.isDetailed(); - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - ((ListUsers)parent).report(HEADER,ns); - Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - if(fn.value!=null) { - Set uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { - Future fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); - if(fr.get(AAFcli.timeout())) { - for(Role r : fr.value.getRole()) { - if(detail) { - ((ListUsers)parent).report(r.getName()); - } - Future fus = client.read( - "/authz/users/role/"+r.getName(), - getDF(Users.class) - ); - if(fus.get(AAFcli.timeout())) { - for(User u : fus.value.getUser()) { - if(detail) { - ((ListUsers)parent).report(" ",u); - } else { - uset.add(u.getId()); - } - } - } else if(fn.code()==404) { - return 200; - } - } - } - } - if(uset!=null) { - for(String u : uset) { - pw().print(" "); - pw().println(u); - } - } - } - } else if(fn.code()==404) { - return 200; - } else { - error(fn); - } - return fn.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String ns=args[idx++]; + final boolean detail = aafcli.isDetailed(); + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + ((ListUsers)parent).report(HEADER,ns); + Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); + if(fn.get(AAFcli.timeout())) { + if(fn.value!=null) { + Set uset = detail?null:new HashSet<>(); + for(Ns n : fn.value.getNs()) { + Future fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); + if(fr.get(AAFcli.timeout())) { + for(Role r : fr.value.getRole()) { + if(detail) { + ((ListUsers)parent).report(r.getName()); + } + Future fus = client.read( + "/authz/users/role/"+r.getName(), + getDF(Users.class) + ); + if(fus.get(AAFcli.timeout())) { + for(User u : fus.value.getUser()) { + if(detail) { + ((ListUsers)parent).report(" ",u); + } else { + uset.add(u.getId()); + } + } + } else if(fn.code()==404) { + return 200; + } + } + } + } + if(uset!=null) { + for(String u : uset) { + pw().print(" "); + pw().println(u); + } + } + } + } else if(fn.code()==404) { + return 200; + } else { + error(fn); + } + return fn.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=4; - detailLine(sb,indent,"Report Users associated with this Namespace's Roles"); - sb.append('\n'); - detailLine(sb,indent,"If \"set details=true\" is specified, then all roles are printed "); - detailLine(sb,indent,"with the associated users and expiration dates"); - indent-=4; - api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); - api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); - api(sb,indent,HttpMethods.GET,"authz/users/role/",Users.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=4; + detailLine(sb,indent,"Report Users associated with this Namespace's Roles"); + sb.append('\n'); + detailLine(sb,indent,"If \"set details=true\" is specified, then all roles are printed "); + detailLine(sb,indent,"with the associated users and expiration dates"); + indent-=4; + api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); + api(sb,indent,HttpMethods.GET,"authz/roles/ns/",Roles.class,false); + api(sb,indent,HttpMethods.GET,"authz/users/role/",Users.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java index 1a4ed7a7..472070d9 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java @@ -48,81 +48,81 @@ import aaf.v2_0.Users.User; * */ public class ListUsersWithPerm extends Cmd { - private static final String HEADER="List Users of Permissions of Namespace "; - - public ListUsersWithPerm(ListUsers parent) { - super(parent,"perm", - new Param("ns-name",true)); - } + private static final String HEADER="List Users of Permissions of Namespace "; + + public ListUsersWithPerm(ListUsers parent) { + super(parent,"perm", + new Param("ns-name",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String ns=args[idx++]; - final boolean detail = aafcli.isDetailed(); - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - ((ListUsers)parent).report(HEADER,ns); - Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - if(fn.value!=null) { - Set uset = detail?null:new HashSet<>(); - - for(Ns n : fn.value.getNs()) { - Future fp = client.read("/authz/perms/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":"") - , getDF(Perms.class)); - if(fp.get(AAFcli.timeout())) { - for(Perm p : fp.value.getPerm()) { - String perm = p.getType()+'/'+p.getInstance()+'/'+p.getAction(); - if(detail)((ListUsers)parent).report(perm); - Future fus = client.read( - "/authz/users/perm/"+perm, - getDF(Users.class) - ); - if(fus.get(AAFcli.timeout())) { - for(User u : fus.value.getUser()) { - if(detail) - ((ListUsers)parent).report(" ",u); - else - uset.add(u.getId()); - } - } else if(fn.code()==404) { - return 200; - } - } - } - } - if(uset!=null) { - for(String u : uset) { - pw().print(" "); - pw().println(u); - } - } - } - } else if(fn.code()==404) { - return 200; - } else { - error(fn); - } - return fn.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String ns=args[idx++]; + final boolean detail = aafcli.isDetailed(); + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + ((ListUsers)parent).report(HEADER,ns); + Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); + if(fn.get(AAFcli.timeout())) { + if(fn.value!=null) { + Set uset = detail?null:new HashSet<>(); + + for(Ns n : fn.value.getNs()) { + Future fp = client.read("/authz/perms/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":"") + , getDF(Perms.class)); + if(fp.get(AAFcli.timeout())) { + for(Perm p : fp.value.getPerm()) { + String perm = p.getType()+'/'+p.getInstance()+'/'+p.getAction(); + if(detail)((ListUsers)parent).report(perm); + Future fus = client.read( + "/authz/users/perm/"+perm, + getDF(Users.class) + ); + if(fus.get(AAFcli.timeout())) { + for(User u : fus.value.getUser()) { + if(detail) + ((ListUsers)parent).report(" ",u); + else + uset.add(u.getId()); + } + } else if(fn.code()==404) { + return 200; + } + } + } + } + if(uset!=null) { + for(String u : uset) { + pw().print(" "); + pw().println(u); + } + } + } + } else if(fn.code()==404) { + return 200; + } else { + error(fn); + } + return fn.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=4; - detailLine(sb,indent,"Report Users associated with this Namespace's Permissions"); - sb.append('\n'); - detailLine(sb,indent,"If \"set detail=true\" is specified, then Permissions are printed with the associated"); - detailLine(sb,indent,"users and expiration dates"); - indent-=4; - api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); - api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,false); - api(sb,indent,HttpMethods.GET,"authz/users/perm///",Users.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=4; + detailLine(sb,indent,"Report Users associated with this Namespace's Permissions"); + sb.append('\n'); + detailLine(sb,indent,"If \"set detail=true\" is specified, then Permissions are printed with the associated"); + detailLine(sb,indent,"users and expiration dates"); + indent-=4; + api(sb,indent,HttpMethods.GET,"authz/nss/",Nss.class,true); + api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,false); + api(sb,indent,HttpMethods.GET,"authz/users/perm///",Users.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/NS.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/NS.java index 8ceffde7..6a645733 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/NS.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/NS.java @@ -27,19 +27,19 @@ import org.onap.aaf.auth.cmd.DeprecatedCMD; import org.onap.aaf.misc.env.APIException; public class NS extends BaseCmd { -// final Role role; +// final Role role; - public NS(AAFcli aafcli) throws APIException { - super(aafcli, "ns"); -// this.role = role; - - cmds.add(new Create(this)); - cmds.add(new Delete(this)); - cmds.add(new Admin(this)); - cmds.add(new Owner(this)); - cmds.add(new DeprecatedCMD(this,"responsible","'responsible' is deprecated. use 'owner'")); // deprecated - cmds.add(new Describe(this)); - cmds.add(new Attrib(this)); - cmds.add(new List(this)); - } + public NS(AAFcli aafcli) throws APIException { + super(aafcli, "ns"); +// this.role = role; + + cmds.add(new Create(this)); + cmds.add(new Delete(this)); + cmds.add(new Admin(this)); + cmds.add(new Owner(this)); + cmds.add(new DeprecatedCMD(this,"responsible","'responsible' is deprecated. use 'owner'")); // deprecated + cmds.add(new Describe(this)); + cmds.add(new Attrib(this)); + cmds.add(new List(this)); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java index 5d1df496..e5e50187 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java @@ -33,77 +33,77 @@ import org.onap.aaf.cadi.client.Retryable; import org.onap.aaf.misc.env.APIException; public class Owner extends BaseCmd { - private final static String[] options = {"add","del"}; + private final static String[] options = {"add","del"}; - public Owner(NS ns) throws APIException { - super(ns,"owner", - new Param(optionsToString(options),true), - new Param("ns-name",true), - new Param("id[,id]*",true) - ); - } + public Owner(NS ns) throws APIException { + super(ns,"owner", + new Param(optionsToString(options),true), + new Param("ns-name",true), + new Param("id[,id]*",true) + ); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; - final int option = whichOption(options, args[idx++]); - final String ns = args[idx++]; - final String ids[] = args[idx++].split(","); + final int option = whichOption(options, args[idx++]); + final String ns = args[idx++]; + final String ids[] = args[idx++].split(","); - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp=null; - for(String id : ids) { - id=fullID(id); - String verb; - switch(option) { - case 0: - fp = client.create("/authz/ns/"+ns+"/responsible/"+id,Void.class); - verb = " is now "; - break; - case 1: - fp = client.delete("/authz/ns/"+ns+"/responsible/"+id,Void.class); - verb = " is no longer "; - break; - default: - throw new CadiException("Bad Argument"); - }; - - if(fp.get(AAFcli.timeout())) { - pw().append(id); - pw().append(verb); - pw().append("responsible for "); - pw().println(ns); - } else { - error(fp); - return fp.code(); - } - } - return fp==null?500:fp.code(); - } - }); - } + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp=null; + for(String id : ids) { + id=fullID(id); + String verb; + switch(option) { + case 0: + fp = client.create("/authz/ns/"+ns+"/responsible/"+id,Void.class); + verb = " is now "; + break; + case 1: + fp = client.delete("/authz/ns/"+ns+"/responsible/"+id,Void.class); + verb = " is no longer "; + break; + default: + throw new CadiException("Bad Argument"); + }; + + if(fp.get(AAFcli.timeout())) { + pw().append(id); + pw().append(verb); + pw().append("responsible for "); + pw().println(ns); + } else { + error(fp); + return fp.code(); + } + } + return fp==null?500:fp.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Add or Delete Responsible person to/from Namespace"); - indent+=2; - detailLine(sb,indent,"Namespace Owners are responsible to receive Notifications and "); - detailLine(sb,indent,"approve Requests regarding this Namespace. Companies have "); - detailLine(sb,indent,"Policies as to who may take on this responsibility"); + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Add or Delete Responsible person to/from Namespace"); + indent+=2; + detailLine(sb,indent,"Namespace Owners are responsible to receive Notifications and "); + detailLine(sb,indent,"approve Requests regarding this Namespace. Companies have "); + detailLine(sb,indent,"Policies as to who may take on this responsibility"); - indent+=2; - detailLine(sb,indent,"name - Name of Namespace"); - detailLine(sb,indent,"id - Credential of Person(s) to be made responsible"); - sb.append('\n'); - detailLine(sb,indent,"aafcli will call API on each ID presented."); - indent-=4; - api(sb,indent,HttpMethods.POST,"authz/ns//responsible/",Void.class,true); - api(sb,indent,HttpMethods.DELETE,"authz/ns//responsible/",Void.class,false); - } + indent+=2; + detailLine(sb,indent,"name - Name of Namespace"); + detailLine(sb,indent,"id - Credential of Person(s) to be made responsible"); + sb.append('\n'); + detailLine(sb,indent,"aafcli will call API on each ID presented."); + indent-=4; + api(sb,indent,HttpMethods.POST,"authz/ns//responsible/",Void.class,true); + api(sb,indent,HttpMethods.DELETE,"authz/ns//responsible/",Void.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java index cc674568..1f123cff 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java @@ -41,123 +41,123 @@ import aaf.v2_0.RoleRequest; * */ public class Create extends Cmd { - public Create(Perm parent) { - super(parent,"create", - new Param("type",true), - new Param("instance",true), - new Param("action", true), - new Param("role[,role]* (to Grant to)", false) - ); - } + public Create(Perm parent) { + super(parent,"create", + new Param("type",true), + new Param("instance",true), + new Param("action", true), + new Param("role[,role]* (to Grant to)", false) + ); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - final PermRequest pr = new PermRequest(); - pr.setType(args[idx++]); - pr.setInstance(args[idx++]); - pr.setAction(args[idx++]); - String roleCommas = (args.length>idx)?args[idx++]:null; - String[] roles = roleCommas==null?null:roleCommas.split("\\s*,\\s*"); - boolean force = aafcli.forceString()!=null; - int rv; - - if(roles!=null && force) { // Make sure Roles are Created - RoleRequest rr = new RoleRequest(); - for(String role : roles) { - rr.setName(role);; - Future fr = client.create( - "/authz/role", - getDF(RoleRequest.class), - rr - ); - fr.get(AAFcli.timeout()); - switch(fr.code()){ - case 201: - pw().println("Created Role [" + role + ']'); - break; - case 409: - break; - default: - pw().println("Role [" + role + "] does not exist, and cannot be created."); - return 206 /*HttpStatus.PARTIAL_CONTENT_206*/; - } - } - } + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + final PermRequest pr = new PermRequest(); + pr.setType(args[idx++]); + pr.setInstance(args[idx++]); + pr.setAction(args[idx++]); + String roleCommas = (args.length>idx)?args[idx++]:null; + String[] roles = roleCommas==null?null:roleCommas.split("\\s*,\\s*"); + boolean force = aafcli.forceString()!=null; + int rv; + + if(roles!=null && force) { // Make sure Roles are Created + RoleRequest rr = new RoleRequest(); + for(String role : roles) { + rr.setName(role);; + Future fr = client.create( + "/authz/role", + getDF(RoleRequest.class), + rr + ); + fr.get(AAFcli.timeout()); + switch(fr.code()){ + case 201: + pw().println("Created Role [" + role + ']'); + break; + case 409: + break; + default: + pw().println("Role [" + role + "] does not exist, and cannot be created."); + return 206 /*HttpStatus.PARTIAL_CONTENT_206*/; + } + } + } - // Set Start/End commands - setStartEnd(pr); - setQueryParamsOn(client); - Future fp = client.create( - "/authz/perm", - getDF(PermRequest.class), - pr - ); - if(fp.get(AAFcli.timeout())) { - rv = fp.code(); - pw().println("Created Permission"); - if(roles!=null) { - if(aafcli.forceString()!=null) { // Make sure Roles are Created - RoleRequest rr = new RoleRequest(); - for(String role : roles) { - rr.setName(role);; - Future fr = client.create( - "/authz/role", - getDF(RoleRequest.class), - rr - ); - fr.get(AAFcli.timeout()); - switch(fr.code()){ - case 201: - case 409:break; - default: - - } - } - } - - try { - if(201!=(rv=((Perm)parent)._exec(0, - new String[] {"grant",pr.getType(),pr.getInstance(),pr.getAction(),roleCommas}))) { - rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; - } - } catch (LocatorException e) { - throw new CadiException(e); - } - } - } else { - rv = fp.code(); - if(rv==409 && force) { - rv = 201; - } else if(rv==202) { - pw().println("Permission Creation Accepted, but requires Approvals before actualizing"); - if (roles!=null) - pw().println("You need to grant the roles after approval."); - } else { - error(fp); - } - } - return rv; - } - }); - } - - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Create a Permission with:"); - detailLine(sb,indent+=2,"type - A Namespace qualified identifier identifying the kind of"); - detailLine(sb,indent+11,"resource to be protected"); - detailLine(sb,indent,"instance - A name that distinguishes a particular instance of resource"); - detailLine(sb,indent,"action - What kind of action is allowed"); - detailLine(sb,indent,"role(s) - Perms granted to these Comma separated Role(s)"); - detailLine(sb,indent+11,"Nonexistent role(s) will be created, if in same namespace"); - sb.append('\n'); - detailLine(sb,indent+2,"Note: Instance and Action can be a an '*' (enter \\\\* on Unix Shell)"); - api(sb,indent,HttpMethods.POST,"authz/perm",PermRequest.class,true); - } + // Set Start/End commands + setStartEnd(pr); + setQueryParamsOn(client); + Future fp = client.create( + "/authz/perm", + getDF(PermRequest.class), + pr + ); + if(fp.get(AAFcli.timeout())) { + rv = fp.code(); + pw().println("Created Permission"); + if(roles!=null) { + if(aafcli.forceString()!=null) { // Make sure Roles are Created + RoleRequest rr = new RoleRequest(); + for(String role : roles) { + rr.setName(role);; + Future fr = client.create( + "/authz/role", + getDF(RoleRequest.class), + rr + ); + fr.get(AAFcli.timeout()); + switch(fr.code()){ + case 201: + case 409:break; + default: + + } + } + } + + try { + if(201!=(rv=((Perm)parent)._exec(0, + new String[] {"grant",pr.getType(),pr.getInstance(),pr.getAction(),roleCommas}))) { + rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; + } + } catch (LocatorException e) { + throw new CadiException(e); + } + } + } else { + rv = fp.code(); + if(rv==409 && force) { + rv = 201; + } else if(rv==202) { + pw().println("Permission Creation Accepted, but requires Approvals before actualizing"); + if (roles!=null) + pw().println("You need to grant the roles after approval."); + } else { + error(fp); + } + } + return rv; + } + }); + } + + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Create a Permission with:"); + detailLine(sb,indent+=2,"type - A Namespace qualified identifier identifying the kind of"); + detailLine(sb,indent+11,"resource to be protected"); + detailLine(sb,indent,"instance - A name that distinguishes a particular instance of resource"); + detailLine(sb,indent,"action - What kind of action is allowed"); + detailLine(sb,indent,"role(s) - Perms granted to these Comma separated Role(s)"); + detailLine(sb,indent+11,"Nonexistent role(s) will be created, if in same namespace"); + sb.append('\n'); + detailLine(sb,indent+2,"Note: Instance and Action can be a an '*' (enter \\\\* on Unix Shell)"); + api(sb,indent,HttpMethods.POST,"authz/perm",PermRequest.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java index ba123d58..ed52a071 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java @@ -40,50 +40,50 @@ import aaf.v2_0.PermRequest; * */ public class Delete extends Cmd { - public Delete(Perm parent) { - super(parent,"delete", - new Param("type",true), - new Param("instance",true), - new Param("action", true)); - } + public Delete(Perm parent) { + super(parent,"delete", + new Param("type",true), + new Param("instance",true), + new Param("action", true)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - // Object Style Delete - PermRequest pk = new PermRequest(); - pk.setType(args[idx++]); - pk.setInstance(args[idx++]); - pk.setAction(args[idx++]); - - // Set "Force" if set - setQueryParamsOn(client); - Future fp = client.delete( - "/authz/perm", - getDF(PermRequest.class), - pk); - if(fp.get(AAFcli.timeout())) { - pw().println("Deleted Permission"); - } else { - if(fp.code()==202) { - pw().println("Permission Deletion Accepted, but requires Approvals before actualizing"); - } else { - error(fp); - } - } - return fp.code(); - } - }); - } + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + // Object Style Delete + PermRequest pk = new PermRequest(); + pk.setType(args[idx++]); + pk.setInstance(args[idx++]); + pk.setAction(args[idx++]); + + // Set "Force" if set + setQueryParamsOn(client); + Future fp = client.delete( + "/authz/perm", + getDF(PermRequest.class), + pk); + if(fp.get(AAFcli.timeout())) { + pw().println("Deleted Permission"); + } else { + if(fp.code()==202) { + pw().println("Permission Deletion Accepted, but requires Approvals before actualizing"); + } else { + error(fp); + } + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Delete a Permission with type,instance and action"); - detailLine(sb,indent+4,"see Create for definitions"); - api(sb,indent,HttpMethods.DELETE,"authz/perm",PermRequest.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Delete a Permission with type,instance and action"); + detailLine(sb,indent+4,"see Create for definitions"); + api(sb,indent,HttpMethods.DELETE,"authz/perm",PermRequest.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java index 5a3fad3e..8396f7d3 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java @@ -35,66 +35,66 @@ import org.onap.aaf.misc.env.APIException; import aaf.v2_0.PermRequest; public class Describe extends Cmd { - private static final String PERM_PATH = "/authz/perm"; - public Describe(Perm parent) { - super(parent,"describe", - new Param("type",true), - new Param("instance", true), - new Param("action", true), - new Param("description",true)); - } + private static final String PERM_PATH = "/authz/perm"; + public Describe(Perm parent) { + super(parent,"describe", + new Param("type",true), + new Param("instance", true), + new Param("action", true), + new Param("description",true)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String type = args[idx++]; - String instance = args[idx++]; - String action = args[idx++]; - StringBuilder desc = new StringBuilder(); - while (idx < args.length) { - desc.append(args[idx++] + ' '); - } - - PermRequest pr = new PermRequest(); - pr.setType(type); - pr.setInstance(instance); - pr.setAction(action); - pr.setDescription(desc.toString()); - - // Set Start/End commands - setStartEnd(pr); - - Future fp = null; - int rv; + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String type = args[idx++]; + String instance = args[idx++]; + String action = args[idx++]; + StringBuilder desc = new StringBuilder(); + while (idx < args.length) { + desc.append(args[idx++] + ' '); + } + + PermRequest pr = new PermRequest(); + pr.setType(type); + pr.setInstance(instance); + pr.setAction(action); + pr.setDescription(desc.toString()); + + // Set Start/End commands + setStartEnd(pr); + + Future fp = null; + int rv; - fp = client.update( - PERM_PATH, - getDF(PermRequest.class), - pr - ); + fp = client.update( + PERM_PATH, + getDF(PermRequest.class), + pr + ); - if(fp.get(AAFcli.timeout())) { - rv=fp.code(); - pw().println("Description added to Permission"); - } else { - if((rv=fp.code())==202) { - pw().print("Adding description"); - pw().println(" Accepted, but requires Approvals before actualizing"); - } else { - error(fp); - } - } - return rv; - } - }); - } + if(fp.get(AAFcli.timeout())) { + rv=fp.code(); + pw().println("Description added to Permission"); + } else { + if((rv=fp.code())==202) { + pw().print("Adding description"); + pw().println(" Accepted, but requires Approvals before actualizing"); + } else { + error(fp); + } + } + return rv; + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Add a description to a permission"); - api(sb,indent,HttpMethods.PUT,"authz/perm",PermRequest.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Add a description to a permission"); + api(sb,indent,HttpMethods.PUT,"authz/perm",PermRequest.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java index d4b26a84..4ed411ba 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java @@ -41,110 +41,110 @@ import aaf.v2_0.RolePermRequest; * */ public class Grant extends Cmd { - private final static String[] options = {"grant","ungrant","setTo"}; + private final static String[] options = {"grant","ungrant","setTo"}; - public Grant(Perm parent) { - super(parent,null, - new Param(optionsToString(options),true), - new Param("type",true), - new Param("instance",true), - new Param("action",true), - new Param("role[,role]* (!REQ S)",false) - ); - } + public Grant(Perm parent) { + super(parent,null, + new Param(optionsToString(options),true), + new Param("type",true), + new Param("instance",true), + new Param("action",true), + new Param("role[,role]* (!REQ S)",false) + ); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String action = args[idx++]; - int option = whichOption(options, action); - - RolePermRequest rpr = new RolePermRequest(); - Pkey pk = new Pkey(); - pk.setType(args[idx++]); - pk.setInstance(args[idx++]); - pk.setAction(args[idx++]); - rpr.setPerm(pk); - setStartEnd(rpr); - - Future frpr = null; - - if (option != 2) { - String[] roles = args[idx++].split(","); - String strA,strB; - for(String role : roles) { - rpr.setRole(role); - if(option==0) { - // You can request to Grant Permission to a Role - setQueryParamsOn(client); - frpr = client.create( - "/authz/role/perm", - getDF(RolePermRequest.class), - rpr - ); - strA = "Granted Permission ["; - strB = "] to Role ["; - } else { - // You can request to UnGrant Permission to a Role - setQueryParamsOn(client); - frpr = client.delete( - "/authz/role/" + role + "/perm", - getDF(RolePermRequest.class), - rpr - ); - strA = "UnGranted Permission ["; - strB = "] from Role ["; - } - if(frpr.get(AAFcli.timeout())) { - pw().println(strA + pk.getType() + '|' + pk.getInstance() + '|' + pk.getAction() - + strB + role +']'); - } else { - if (frpr.code()==202) { - pw().print("Permission Role "); - pw().print(option==0?"Granted":"Ungranted"); - pw().println(" Accepted, but requires Approvals before actualizing"); - } else { - error(frpr); - idx=Integer.MAX_VALUE; - } - } - } - } else { - String allRoles = ""; - if (idx < args.length) - allRoles = args[idx++]; - - rpr.setRole(allRoles); - frpr = client.update( - "/authz/role/perm", - getDF(RolePermRequest.class), - rpr); - if(frpr.get(AAFcli.timeout())) { - pw().println("Set Permission's Roles to [" + allRoles + "]"); - } else { - error(frpr); - } - } - return frpr==null?0:frpr.code(); - } - }); - } + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String action = args[idx++]; + int option = whichOption(options, action); + + RolePermRequest rpr = new RolePermRequest(); + Pkey pk = new Pkey(); + pk.setType(args[idx++]); + pk.setInstance(args[idx++]); + pk.setAction(args[idx++]); + rpr.setPerm(pk); + setStartEnd(rpr); + + Future frpr = null; + + if (option != 2) { + String[] roles = args[idx++].split(","); + String strA,strB; + for(String role : roles) { + rpr.setRole(role); + if(option==0) { + // You can request to Grant Permission to a Role + setQueryParamsOn(client); + frpr = client.create( + "/authz/role/perm", + getDF(RolePermRequest.class), + rpr + ); + strA = "Granted Permission ["; + strB = "] to Role ["; + } else { + // You can request to UnGrant Permission to a Role + setQueryParamsOn(client); + frpr = client.delete( + "/authz/role/" + role + "/perm", + getDF(RolePermRequest.class), + rpr + ); + strA = "UnGranted Permission ["; + strB = "] from Role ["; + } + if(frpr.get(AAFcli.timeout())) { + pw().println(strA + pk.getType() + '|' + pk.getInstance() + '|' + pk.getAction() + + strB + role +']'); + } else { + if (frpr.code()==202) { + pw().print("Permission Role "); + pw().print(option==0?"Granted":"Ungranted"); + pw().println(" Accepted, but requires Approvals before actualizing"); + } else { + error(frpr); + idx=Integer.MAX_VALUE; + } + } + } + } else { + String allRoles = ""; + if (idx < args.length) + allRoles = args[idx++]; + + rpr.setRole(allRoles); + frpr = client.update( + "/authz/role/perm", + getDF(RolePermRequest.class), + rpr); + if(frpr.get(AAFcli.timeout())) { + pw().println("Set Permission's Roles to [" + allRoles + "]"); + } else { + error(frpr); + } + } + return frpr==null?0:frpr.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Grant a Permission to a Role or Roles OR"); - detailLine(sb,indent,"Ungrant a Permission from a Role or Roles OR"); - detailLine(sb,indent,"Set a Permission's roles to roles supplied."); - detailLine(sb,indent+4,"WARNING: Roles supplied with setTo will be the ONLY roles attached to this permission"); - detailLine(sb,indent+8,"If no roles are supplied, permission's roles are reset."); - detailLine(sb,indent,"see Create for definitions of type,instance and action"); - api(sb,indent,HttpMethods.POST,"authz/role/perm",RolePermRequest.class,true); - api(sb,indent,HttpMethods.DELETE,"authz/role//perm",RolePermRequest.class,false); - api(sb,indent,HttpMethods.PUT,"authz/role/perm",RolePermRequest.class,false); + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Grant a Permission to a Role or Roles OR"); + detailLine(sb,indent,"Ungrant a Permission from a Role or Roles OR"); + detailLine(sb,indent,"Set a Permission's roles to roles supplied."); + detailLine(sb,indent+4,"WARNING: Roles supplied with setTo will be the ONLY roles attached to this permission"); + detailLine(sb,indent+8,"If no roles are supplied, permission's roles are reset."); + detailLine(sb,indent,"see Create for definitions of type,instance and action"); + api(sb,indent,HttpMethods.POST,"authz/role/perm",RolePermRequest.class,true); + api(sb,indent,HttpMethods.DELETE,"authz/role//perm",RolePermRequest.class,false); + api(sb,indent,HttpMethods.PUT,"authz/role/perm",RolePermRequest.class,false); - } + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java index 2eadd38c..48b8a488 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java @@ -34,83 +34,83 @@ import org.onap.aaf.misc.env.APIException; import aaf.v2_0.Perms; public class List extends BaseCmd { -// private static final String LIST_PERM_DETAILS = "list permission details"; - - public List(Perm parent) { - super(parent,"list"); +// private static final String LIST_PERM_DETAILS = "list permission details"; + + public List(Perm parent) { + super(parent,"list"); - cmds.add(new ListByUser(this)); - cmds.add(new ListByName(this)); - cmds.add(new ListByNS(this)); - cmds.add(new ListByRole(this)); - cmds.add(new ListActivity(this)); - } - // Package Level on purpose - abstract class ListPerms extends Retryable { - protected int list(Future fp,String header, String parentPerm) throws CadiException, APIException { - if(fp.get(AAFcli.timeout())) { - report(fp,header, parentPerm); - } else { - error(fp); - } - return fp.code(); - } - } + cmds.add(new ListByUser(this)); + cmds.add(new ListByName(this)); + cmds.add(new ListByNS(this)); + cmds.add(new ListByRole(this)); + cmds.add(new ListActivity(this)); + } + // Package Level on purpose + abstract class ListPerms extends Retryable { + protected int list(Future fp,String header, String parentPerm) throws CadiException, APIException { + if(fp.get(AAFcli.timeout())) { + report(fp,header, parentPerm); + } else { + error(fp); + } + return fp.code(); + } + } - private static final Comparator permCompare = new Comparator() { - @Override - public int compare(aaf.v2_0.Perm a, aaf.v2_0.Perm b) { - int rc; - if((rc=a.getType().compareTo(b.getType()))!=0) { - return rc; - } - if((rc=a.getInstance().compareTo(b.getInstance()))!=0) { - return rc; - } - return a.getAction().compareTo(b.getAction()); - } - }; - - private static final String permFormat = "%-30s %-30s %-10s\n"; - - void report(Future fp, String ... str) { - reportHead(str); - if (this.aafcli.isDetailed()) { - String format = "%-36s %-30s %-15s\n"; - String descFmt = " %-75s\n"; - reportColHead(format + descFmt,"[PERM NS].Type","Instance","Action", "Description"); - Collections.sort(fp.value.getPerm(),permCompare); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { - String pns = p.getNs(); - if(pns==null) { - pw().format(format, - p.getType(), - p.getInstance(), - p.getAction()); - } else { - pw().format(format, - '['+pns + "]." + p.getType().substring(pns.length()+1), - p.getInstance(), - p.getAction()); - } - String desc = p.getDescription(); - if(desc!=null && desc.length()>0) { - pw().format(descFmt,p.getDescription()); - } - } - pw().println(); - } else { - String format = reportColHead(permFormat,"PERM Type","Instance","Action"); + private static final Comparator permCompare = new Comparator() { + @Override + public int compare(aaf.v2_0.Perm a, aaf.v2_0.Perm b) { + int rc; + if((rc=a.getType().compareTo(b.getType()))!=0) { + return rc; + } + if((rc=a.getInstance().compareTo(b.getInstance()))!=0) { + return rc; + } + return a.getAction().compareTo(b.getAction()); + } + }; + + private static final String permFormat = "%-30s %-30s %-10s\n"; + + void report(Future fp, String ... str) { + reportHead(str); + if (this.aafcli.isDetailed()) { + String format = "%-36s %-30s %-15s\n"; + String descFmt = " %-75s\n"; + reportColHead(format + descFmt,"[PERM NS].Type","Instance","Action", "Description"); + Collections.sort(fp.value.getPerm(),permCompare); + for(aaf.v2_0.Perm p : fp.value.getPerm()) { + String pns = p.getNs(); + if(pns==null) { + pw().format(format, + p.getType(), + p.getInstance(), + p.getAction()); + } else { + pw().format(format, + '['+pns + "]." + p.getType().substring(pns.length()+1), + p.getInstance(), + p.getAction()); + } + String desc = p.getDescription(); + if(desc!=null && desc.length()>0) { + pw().format(descFmt,p.getDescription()); + } + } + pw().println(); + } else { + String format = reportColHead(permFormat,"PERM Type","Instance","Action"); - Collections.sort(fp.value.getPerm(),permCompare); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { - pw().format(format, - p.getType(), - p.getInstance(), - p.getAction()); - } - pw().println(); - } - } + Collections.sort(fp.value.getPerm(),permCompare); + for(aaf.v2_0.Perm p : fp.value.getPerm()) { + pw().format(format, + p.getType(), + p.getInstance(), + p.getAction()); + } + pw().println(); + } + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java index 4b5f569b..c59e9b5a 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java @@ -39,38 +39,38 @@ import aaf.v2_0.History; * */ public class ListActivity extends Cmd { - private static final String HEADER = "List Activity of Permission"; - - public ListActivity(List parent) { - super(parent,"activity", - new Param("type",true)); - } + private static final String HEADER = "List Activity of Permission"; + + public ListActivity(List parent) { + super(parent,"activity", + new Param("type",true)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String type = args[idx++]; - Future fp = client.read( - "/authz/hist/perm/"+type, - getDF(History.class) - ); - if(fp.get(AAFcli.timeout())) { - activity(fp.value, HEADER + " [ " + type + " ]"); - } else { - error(fp); - } - return fp.code(); - } - }); - } + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String type = args[idx++]; + Future fp = client.read( + "/authz/hist/perm/"+type, + getDF(History.class) + ); + if(fp.get(AAFcli.timeout())) { + activity(fp.value, HEADER + " [ " + type + " ]"); + } else { + error(fp); + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/hist/perm/",History.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/hist/perm/",History.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByNS.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByNS.java index 304055bf..7469eed5 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByNS.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByNS.java @@ -39,33 +39,33 @@ import aaf.v2_0.Perms; * */ public class ListByNS extends Cmd { - private static final String HEADER = "List Perms by NS "; - - public ListByNS(List parent) { - super(parent,"ns", - new Param("name",true)); - } + private static final String HEADER = "List Perms by NS "; + + public ListByNS(List parent) { + super(parent,"ns", + new Param("name",true)); + } - public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - final String ns=args[idx]; + public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { + final String ns=args[idx]; - return same(((List)parent).new ListPerms() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/perms/ns/"+ns+(aafcli.isDetailed()?"?ns":""), - getDF(Perms.class) - ); - return list(fp, HEADER, ns); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,true); - } + return same(((List)parent).new ListPerms() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authz/perms/ns/"+ns+(aafcli.isDetailed()?"?ns":""), + getDF(Perms.class) + ); + return list(fp, HEADER, ns); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/perms/ns/",Perms.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByName.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByName.java index 6310e24b..099fb5f8 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByName.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByName.java @@ -38,32 +38,32 @@ import aaf.v2_0.Perms; * */ public class ListByName extends Cmd { - private static final String HEADER = "List Child Permissions"; - - public ListByName(List parent) { - super(parent,"name", - new Param("root perm name",true)); - } + private static final String HEADER = "List Child Permissions"; + + public ListByName(List parent) { + super(parent,"name", + new Param("root perm name",true)); + } - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(((List)parent).new ListPerms() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - String parentPerm=args[index]; - - Future fp = client.read( - "/authz/perms/"+parentPerm+(aafcli.isDetailed()?"?ns":""), - getDF(Perms.class) - ); - return list(fp,HEADER,parentPerm); - } - }); - } + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(((List)parent).new ListPerms() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + String parentPerm=args[index]; + + Future fp = client.read( + "/authz/perms/"+parentPerm+(aafcli.isDetailed()?"?ns":""), + getDF(Perms.class) + ); + return list(fp,HEADER,parentPerm); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/perms/",Perms.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/perms/",Perms.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByRole.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByRole.java index 75b88538..32b78a6b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByRole.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByRole.java @@ -39,34 +39,34 @@ import aaf.v2_0.Perms; * */ public class ListByRole extends Cmd { - private static final String HEADER = "List Perms by Role "; - - public ListByRole(List parent) { - super(parent,"role", - new Param("name",true)); - } + private static final String HEADER = "List Perms by Role "; + + public ListByRole(List parent) { + super(parent,"role", + new Param("name",true)); + } - public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { - final String role=args[idx]; + public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { + final String role=args[idx]; - return same(((List)parent).new ListPerms() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { + return same(((List)parent).new ListPerms() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/perms/role/"+role+(aafcli.isDetailed()?"?ns":""), - getDF(Perms.class) - ); - return list(fp, HEADER, role); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/perms/role/",Perms.class,true); - } + Future fp = client.read( + "/authz/perms/role/"+role+(aafcli.isDetailed()?"?ns":""), + getDF(Perms.class) + ); + return list(fp, HEADER, role); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/perms/role/",Perms.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java index ba708273..550386cf 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java @@ -38,45 +38,45 @@ import aaf.v2_0.Perms; * */ public class ListByUser extends Cmd { - private static final String HEADER = "List Permissions by User"; - public ListByUser(List parent) { - super(parent,"user", - new Param("id",true)); - } + private static final String HEADER = "List Permissions by User"; + public ListByUser(List parent) { + super(parent,"user", + new Param("id",true)); + } - public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - final String user=fullID(args[idx]); - - return same(((List)parent).new ListPerms() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - StringBuilder sb = null; - if("true".equalsIgnoreCase(aafcli.forceString())) { - sb = new StringBuilder(); - sb.append("?force"); - } - if(aafcli.isDetailed()) { - if(sb==null) { - sb = new StringBuilder('?'); - } else { - sb.append('&'); - } - sb.append("ns"); - } - Future fp = client.read( - "/authz/perms/user/"+user+(sb==null?"":sb), - getDF(Perms.class) - ); - return list(fp,HEADER, user); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/perms/user/",Perms.class,true); - } + public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { + final String user=fullID(args[idx]); + + return same(((List)parent).new ListPerms() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + StringBuilder sb = null; + if("true".equalsIgnoreCase(aafcli.forceString())) { + sb = new StringBuilder(); + sb.append("?force"); + } + if(aafcli.isDetailed()) { + if(sb==null) { + sb = new StringBuilder('?'); + } else { + sb.append('&'); + } + sb.append("ns"); + } + Future fp = client.read( + "/authz/perms/user/"+user+(sb==null?"":sb), + getDF(Perms.class) + ); + return list(fp,HEADER, user); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/perms/user/",Perms.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Perm.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Perm.java index 805b6e62..02030211 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Perm.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Perm.java @@ -26,17 +26,17 @@ import org.onap.aaf.auth.cmd.role.Role; import org.onap.aaf.misc.env.APIException; public class Perm extends BaseCmd { - Role role; + Role role; - public Perm(Role role) throws APIException { - super(role.aafcli, "perm"); - this.role = role; + public Perm(Role role) throws APIException { + super(role.aafcli, "perm"); + this.role = role; - cmds.add(new Create(this)); - cmds.add(new Delete(this)); - cmds.add(new Grant(this)); - cmds.add(new Rename(this)); - cmds.add(new Describe(this)); - cmds.add(new List(this)); - } + cmds.add(new Create(this)); + cmds.add(new Delete(this)); + cmds.add(new Grant(this)); + cmds.add(new Rename(this)); + cmds.add(new Describe(this)); + cmds.add(new List(this)); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java index fa65f61a..620e1e04 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java @@ -36,67 +36,67 @@ import org.onap.aaf.misc.env.APIException; import aaf.v2_0.PermRequest; public class Rename extends Cmd { - public Rename(Perm parent) { - super(parent,"rename", - new Param("type",true), - new Param("instance",true), - new Param("action", true), - new Param("new type",true), - new Param("new instance",true), - new Param("new action", true) - ); - } - - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String origType = args[idx++]; - String origInstance = args[idx++]; - String origAction = args[idx++]; - - //Create new permission - PermRequest pr = new PermRequest(); - pr.setType(args[idx++]); - pr.setInstance(args[idx++]); - pr.setAction(args[idx++]); - - // Set Start/End commands - setStartEnd(pr); - Future fp = client.update( - "/authz/perm/"+origType+"/"+origInstance+"/"+origAction, - getDF(PermRequest.class), - pr - ); - int rv; - if(fp.get(AAFcli.timeout())) { - rv = fp.code(); - pw().println("Updated Permission"); - } else { - rv = fp.code(); - if(rv==202) { - pw().println("Permission Update Accepted, but requires Approvals before actualizing"); - } else { - error(fp); - } - } - return rv; - } - }); - - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Rename a Permission from:"); - detailLine(sb,indent+2," "); - detailLine(sb,indent,"to:"); - detailLine(sb,indent+2," "); - sb.append('\n'); - detailLine(sb,indent,"Namespace must be the same in and "); - detailLine(sb,indent+4,"see Create for definitions of type,instance and action"); - api(sb,indent,HttpMethods.PUT,"authz/perm///",PermRequest.class,true); - } + public Rename(Perm parent) { + super(parent,"rename", + new Param("type",true), + new Param("instance",true), + new Param("action", true), + new Param("new type",true), + new Param("new instance",true), + new Param("new action", true) + ); + } + + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String origType = args[idx++]; + String origInstance = args[idx++]; + String origAction = args[idx++]; + + //Create new permission + PermRequest pr = new PermRequest(); + pr.setType(args[idx++]); + pr.setInstance(args[idx++]); + pr.setAction(args[idx++]); + + // Set Start/End commands + setStartEnd(pr); + Future fp = client.update( + "/authz/perm/"+origType+"/"+origInstance+"/"+origAction, + getDF(PermRequest.class), + pr + ); + int rv; + if(fp.get(AAFcli.timeout())) { + rv = fp.code(); + pw().println("Updated Permission"); + } else { + rv = fp.code(); + if(rv==202) { + pw().println("Permission Update Accepted, but requires Approvals before actualizing"); + } else { + error(fp); + } + } + return rv; + } + }); + + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Rename a Permission from:"); + detailLine(sb,indent+2," "); + detailLine(sb,indent,"to:"); + detailLine(sb,indent+2," "); + sb.append('\n'); + detailLine(sb,indent,"Namespace must be the same in and "); + detailLine(sb,indent+4,"see Create for definitions of type,instance and action"); + api(sb,indent,HttpMethods.PUT,"authz/perm///",PermRequest.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java index 3234fe9c..f9dcbcd8 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java @@ -40,94 +40,94 @@ import aaf.v2_0.RoleRequest; * */ public class CreateDelete extends Cmd { - private static final String ROLE_PATH = "/authz/role"; - private final static String[] options = {"create","delete"}; - public CreateDelete(Role parent) { - super(parent,null, - new Param(optionsToString(options),true), - new Param("name",true)); - } + private static final String ROLE_PATH = "/authz/role"; + private final static String[] options = {"create","delete"}; + public CreateDelete(Role parent) { + super(parent,null, + new Param(optionsToString(options),true), + new Param("name",true)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String action = args[idx++]; - int option = whichOption(options, action); - - RoleRequest rr = new RoleRequest(); - rr.setName(args[idx++]); - - // Set Start/End commands - setStartEnd(rr); - - Future fp = null; - String verb = null; - int rv; - switch(option) { - case 0: - fp = client.create( - ROLE_PATH, - getDF(RoleRequest.class), - rr - ); - verb = "Create"; - break; - case 1: - // Send "Force" if set - setQueryParamsOn(client); - fp = client.delete( - ROLE_PATH, // +args[idx++], - getDF(RoleRequest.class), - rr - ); - verb = "Delete"; - break; - default: // note, if not an option, whichOption throws Exception - break; - - } - boolean rolesSupplied = (args.length>idx); - if(fp == null) {// This useless code brought to you by Sonar. - throw new CadiException("No call made."); - } - if(fp.get(AAFcli.timeout())) { - rv=fp.code(); - pw().print(verb); - pw().println("d Role"); - if(rolesSupplied) { - for(;args.length>idx;++idx ) { - try { - if(201!=(rv=((Role)parent)._exec(0,new String[] {"user","add",rr.getName(),args[idx]}))) { - rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; - } - } catch (LocatorException e) { - throw new CadiException(e); - } - } - } - } else { - if((rv=fp.code())==202) { - pw().print("Role "); - pw().print(verb); - pw().println(" Accepted, but requires Approvals before actualizing"); - } else { - error(fp); - } - } - return rv; - } - }); - } + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String action = args[idx++]; + int option = whichOption(options, action); + + RoleRequest rr = new RoleRequest(); + rr.setName(args[idx++]); + + // Set Start/End commands + setStartEnd(rr); + + Future fp = null; + String verb = null; + int rv; + switch(option) { + case 0: + fp = client.create( + ROLE_PATH, + getDF(RoleRequest.class), + rr + ); + verb = "Create"; + break; + case 1: + // Send "Force" if set + setQueryParamsOn(client); + fp = client.delete( + ROLE_PATH, // +args[idx++], + getDF(RoleRequest.class), + rr + ); + verb = "Delete"; + break; + default: // note, if not an option, whichOption throws Exception + break; + + } + boolean rolesSupplied = (args.length>idx); + if(fp == null) {// This useless code brought to you by Sonar. + throw new CadiException("No call made."); + } + if(fp.get(AAFcli.timeout())) { + rv=fp.code(); + pw().print(verb); + pw().println("d Role"); + if(rolesSupplied) { + for(;args.length>idx;++idx ) { + try { + if(201!=(rv=((Role)parent)._exec(0,new String[] {"user","add",rr.getName(),args[idx]}))) { + rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; + } + } catch (LocatorException e) { + throw new CadiException(e); + } + } + } + } else { + if((rv=fp.code())==202) { + pw().print("Role "); + pw().print(verb); + pw().println(" Accepted, but requires Approvals before actualizing"); + } else { + error(fp); + } + } + return rv; + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Create OR Delete a Role"); - detailLine(sb,indent+2,"name - Name of Role to create"); - api(sb,indent,HttpMethods.POST,"authz/role",RoleRequest.class,true); - api(sb,indent,HttpMethods.DELETE,"authz/role",RoleRequest.class,false); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Create OR Delete a Role"); + detailLine(sb,indent+2,"name - Name of Role to create"); + api(sb,indent,HttpMethods.POST,"authz/role",RoleRequest.class,true); + api(sb,indent,HttpMethods.DELETE,"authz/role",RoleRequest.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java index 5498f29a..e8001040 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java @@ -35,60 +35,60 @@ import org.onap.aaf.misc.env.APIException; import aaf.v2_0.RoleRequest; public class Describe extends Cmd { - private static final String ROLE_PATH = "/authz/role"; - public Describe(Role parent) { - super(parent,"describe", - new Param("name",true), - new Param("description",true)); - } + private static final String ROLE_PATH = "/authz/role"; + public Describe(Role parent) { + super(parent,"describe", + new Param("name",true), + new Param("description",true)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String role = args[idx++]; - StringBuilder desc = new StringBuilder(); - while (idx < args.length) { - desc.append(args[idx++] + ' '); - } - - RoleRequest rr = new RoleRequest(); - rr.setName(role); - rr.setDescription(desc.toString()); - - // Set Start/End commands - setStartEnd(rr); - - Future fp = null; - int rv; + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String role = args[idx++]; + StringBuilder desc = new StringBuilder(); + while (idx < args.length) { + desc.append(args[idx++] + ' '); + } + + RoleRequest rr = new RoleRequest(); + rr.setName(role); + rr.setDescription(desc.toString()); + + // Set Start/End commands + setStartEnd(rr); + + Future fp = null; + int rv; - fp = client.update( - ROLE_PATH, - getDF(RoleRequest.class), - rr - ); + fp = client.update( + ROLE_PATH, + getDF(RoleRequest.class), + rr + ); - if(fp.get(AAFcli.timeout())) { - rv=fp.code(); - pw().println("Description added to role"); - } else { - if((rv=fp.code())==202) { - pw().print("Adding description"); - pw().println(" Accepted, but requires Approvals before actualizing"); - } else { - error(fp); - } - } - return rv; - } - }); - } + if(fp.get(AAFcli.timeout())) { + rv=fp.code(); + pw().println("Description added to role"); + } else { + if((rv=fp.code())==202) { + pw().print("Adding description"); + pw().println(" Accepted, but requires Approvals before actualizing"); + } else { + error(fp); + } + } + return rv; + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Add a description to a role"); - api(sb,indent,HttpMethods.PUT,"authz/role",RoleRequest.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Add a description to a role"); + api(sb,indent,HttpMethods.PUT,"authz/role",RoleRequest.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java index 2e09b03b..ec8d8ee3 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java @@ -45,167 +45,167 @@ import aaf.v2_0.UserRoles; public class List extends BaseCmd { - private static final String XXXX_XX_XX = "XXXX-XX-XX"; - private static final String LIST_ROLES_BY_NAME = "list roles for role"; + private static final String XXXX_XX_XX = "XXXX-XX-XX"; + private static final String LIST_ROLES_BY_NAME = "list roles for role"; - public List(Role parent) { - super(parent,"list"); - cmds.add(new ListByUser(this)); - cmds.add(new ListByRole(this)); - cmds.add(new ListByNS(this)); - cmds.add(new ListByNameOnly(this)); - cmds.add(new ListByPerm(this)); - cmds.add(new ListActivity(this)); - } - - // Package Level on purpose - abstract class ListRoles extends Retryable { - protected int list(Future fr,Rcli client, String header) throws APIException, CadiException { - if(fr.get(AAFcli.timeout())) { - Perms perms=null; - if (aafcli.isDetailed()) { - for(aaf.v2_0.Role r : fr.value.getRole()) { - Future fp = client.read( - "/authz/perms/role/"+r.getName()+(aafcli.isDetailed()?"?ns":""), - getDF(Perms.class) - ); - if(fp.get(AAFcli.timeout())) { - if(perms==null) { - perms = fp.value; - } else { - perms.getPerm().addAll(fp.value.getPerm()); - } - } - } - } - report(fr.value,perms,null,header); - } else { - error(fr); - } - return fr.code(); - } - } + public List(Role parent) { + super(parent,"list"); + cmds.add(new ListByUser(this)); + cmds.add(new ListByRole(this)); + cmds.add(new ListByNS(this)); + cmds.add(new ListByNameOnly(this)); + cmds.add(new ListByPerm(this)); + cmds.add(new ListActivity(this)); + } + + // Package Level on purpose + abstract class ListRoles extends Retryable { + protected int list(Future fr,Rcli client, String header) throws APIException, CadiException { + if(fr.get(AAFcli.timeout())) { + Perms perms=null; + if (aafcli.isDetailed()) { + for(aaf.v2_0.Role r : fr.value.getRole()) { + Future fp = client.read( + "/authz/perms/role/"+r.getName()+(aafcli.isDetailed()?"?ns":""), + getDF(Perms.class) + ); + if(fp.get(AAFcli.timeout())) { + if(perms==null) { + perms = fp.value; + } else { + perms.getPerm().addAll(fp.value.getPerm()); + } + } + } + } + report(fr.value,perms,null,header); + } else { + error(fr); + } + return fr.code(); + } + } - private final static String roleFormat = "%-56s Expires %s\n"; - private final static String roleFormatNoDate = "%-61s\n"; - private final static String roleExpiredFormat = "%-53s !!! EXPIRED !!! %s\n"; - private final static String permFormat = " %-30s %-30s %-15s\n"; + private final static String roleFormat = "%-56s Expires %s\n"; + private final static String roleFormatNoDate = "%-61s\n"; + private final static String roleExpiredFormat = "%-53s !!! EXPIRED !!! %s\n"; + private final static String permFormat = " %-30s %-30s %-15s\n"; - - private static final Comparator roleCompare = new Comparator() { - @Override - public int compare(aaf.v2_0.Role a, aaf.v2_0.Role b) { - return a.getName().compareTo(b.getName()); - } - }; - public void report(Roles roles, Perms perms, UserRoles urs, String ... str) { - reportHead(str); - XMLGregorianCalendar now = Chrono.timeStamp().normalize(); - if(roles==null || roles.getRole().isEmpty()) { - pw().println(""); - } else if (aafcli.isDetailed()){ - if (aafcli.isDetailed() && str[0].toLowerCase().contains(LIST_ROLES_BY_NAME)) { - String description = roles.getRole().get(0).getDescription(); - if (description == null) description = ""; - reportColHead("%-80s\n","Description: " + description); - } + + private static final Comparator roleCompare = new Comparator() { + @Override + public int compare(aaf.v2_0.Role a, aaf.v2_0.Role b) { + return a.getName().compareTo(b.getName()); + } + }; + public void report(Roles roles, Perms perms, UserRoles urs, String ... str) { + reportHead(str); + XMLGregorianCalendar now = Chrono.timeStamp().normalize(); + if(roles==null || roles.getRole().isEmpty()) { + pw().println(""); + } else if (aafcli.isDetailed()){ + if (aafcli.isDetailed() && str[0].toLowerCase().contains(LIST_ROLES_BY_NAME)) { + String description = roles.getRole().get(0).getDescription(); + if (description == null) description = ""; + reportColHead("%-80s\n","Description: " + description); + } - String fullFormat = roleFormat+permFormat; - reportColHead(fullFormat,"[ROLE NS].Name","","[PERM NS].Type","Instance","Action"); - Collections.sort(roles.getRole(),roleCompare); - for(aaf.v2_0.Role r : roles.getRole()) { - String roleName = r.getName(); - String ns = r.getNs(); - if(aafcli.isTest()) { - if(ns==null) { - pw().format(roleFormat, roleName,XXXX_XX_XX); - } else { - pw().format(roleFormat, "["+ns+"]"+roleName.substring(ns.length()),XXXX_XX_XX); - } - } else { - UserRole ur = get(roleName,urs); - if(ur!=null && now.compare(ur.getExpires().normalize())>0) { - if(ns==null) { - pw().format(roleExpiredFormat, roleName,Chrono.dateOnlyStamp(ur.getExpires())); - } else { - pw().format(roleExpiredFormat, "["+ns+"]"+roleName.substring(ns.length()),Chrono.dateOnlyStamp(ur.getExpires())); - } - } else { - if(ns==null) { - pw().format(roleFormat, roleName,ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); - } else { - pw().format(roleFormat, "["+ns+"]"+roleName.substring(ns.length()),ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); - } - } - } + String fullFormat = roleFormat+permFormat; + reportColHead(fullFormat,"[ROLE NS].Name","","[PERM NS].Type","Instance","Action"); + Collections.sort(roles.getRole(),roleCompare); + for(aaf.v2_0.Role r : roles.getRole()) { + String roleName = r.getName(); + String ns = r.getNs(); + if(aafcli.isTest()) { + if(ns==null) { + pw().format(roleFormat, roleName,XXXX_XX_XX); + } else { + pw().format(roleFormat, "["+ns+"]"+roleName.substring(ns.length()),XXXX_XX_XX); + } + } else { + UserRole ur = get(roleName,urs); + if(ur!=null && now.compare(ur.getExpires().normalize())>0) { + if(ns==null) { + pw().format(roleExpiredFormat, roleName,Chrono.dateOnlyStamp(ur.getExpires())); + } else { + pw().format(roleExpiredFormat, "["+ns+"]"+roleName.substring(ns.length()),Chrono.dateOnlyStamp(ur.getExpires())); + } + } else { + if(ns==null) { + pw().format(roleFormat, roleName,ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); + } else { + pw().format(roleFormat, "["+ns+"]"+roleName.substring(ns.length()),ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); + } + } + } - for(Pkey pkey : r.getPerms()) { - Perm perm = get(pkey,perms); - if(perm==null || perm.getNs()==null) { - pw().format(permFormat, - pkey.getType(), - pkey.getInstance(), - pkey.getAction()); - } else { - String ns1 = perm.getNs(); - pw().format(permFormat, - '['+ns1+"]"+perm.getType().substring(ns1.length()), - perm.getInstance(), - perm.getAction()); - } - } - } - } else { - String fullFormat = roleFormat; - reportColHead(fullFormat,"ROLE Name","","PERM Type","Instance","Action"); - Collections.sort(roles.getRole(),roleCompare); - for(aaf.v2_0.Role r : roles.getRole()) { - if (urs != null) { - String roleName = r.getName(); - if(!aafcli.isTest()) { - UserRole ur = get(roleName,urs); - if(ur!=null && now.compare(ur.getExpires().normalize())>0) { - pw().format(roleExpiredFormat, roleName+"*",Chrono.dateOnlyStamp(ur.getExpires())); - } else { - pw().format(roleFormat, roleName,ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); - } - } else { - pw().format(roleFormat, roleName,XXXX_XX_XX); - } - } else { - pw().format(roleFormatNoDate, r.getName()); - for(Pkey perm : r.getPerms()) { - pw().format(permFormat, - perm.getType(), - perm.getInstance(), - perm.getAction()); - } - } - } - } - } - private Perm get(Pkey pkey, Perms perms) { - if(perms!=null) { - for(Perm p : perms.getPerm()) { - if(pkey.getAction().equals(p.getAction()) && - pkey.getInstance().equals(p.getInstance()) && - pkey.getType().equals(p.getType())) { - return p; - } - } - } - return null; - } - // The assumption is that these UserRoles are already pulled in by User... no need to check - private UserRole get(String roleName, UserRoles urs) { - if(urs!=null) { - for(UserRole ur : urs.getUserRole()) { - if(roleName.equals(ur.getRole())) { - return ur; - } - } - } - return null; - } + for(Pkey pkey : r.getPerms()) { + Perm perm = get(pkey,perms); + if(perm==null || perm.getNs()==null) { + pw().format(permFormat, + pkey.getType(), + pkey.getInstance(), + pkey.getAction()); + } else { + String ns1 = perm.getNs(); + pw().format(permFormat, + '['+ns1+"]"+perm.getType().substring(ns1.length()), + perm.getInstance(), + perm.getAction()); + } + } + } + } else { + String fullFormat = roleFormat; + reportColHead(fullFormat,"ROLE Name","","PERM Type","Instance","Action"); + Collections.sort(roles.getRole(),roleCompare); + for(aaf.v2_0.Role r : roles.getRole()) { + if (urs != null) { + String roleName = r.getName(); + if(!aafcli.isTest()) { + UserRole ur = get(roleName,urs); + if(ur!=null && now.compare(ur.getExpires().normalize())>0) { + pw().format(roleExpiredFormat, roleName+"*",Chrono.dateOnlyStamp(ur.getExpires())); + } else { + pw().format(roleFormat, roleName,ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); + } + } else { + pw().format(roleFormat, roleName,XXXX_XX_XX); + } + } else { + pw().format(roleFormatNoDate, r.getName()); + for(Pkey perm : r.getPerms()) { + pw().format(permFormat, + perm.getType(), + perm.getInstance(), + perm.getAction()); + } + } + } + } + } + private Perm get(Pkey pkey, Perms perms) { + if(perms!=null) { + for(Perm p : perms.getPerm()) { + if(pkey.getAction().equals(p.getAction()) && + pkey.getInstance().equals(p.getInstance()) && + pkey.getType().equals(p.getType())) { + return p; + } + } + } + return null; + } + // The assumption is that these UserRoles are already pulled in by User... no need to check + private UserRole get(String roleName, UserRoles urs) { + if(urs!=null) { + for(UserRole ur : urs.getUserRole()) { + if(roleName.equals(ur.getRole())) { + return ur; + } + } + } + return null; + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java index 0331ae09..1f6f18f7 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java @@ -39,37 +39,37 @@ import aaf.v2_0.History; * */ public class ListActivity extends Cmd { - private static final String HEADER = "List Activity of Role"; + private static final String HEADER = "List Activity of Role"; - public ListActivity(List parent) { - super(parent,"activity", - new Param("name",true)); - } + public ListActivity(List parent) { + super(parent,"activity", + new Param("name",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String role = args[idx++]; - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/hist/role/"+role, - getDF(History.class) - ); - if(fp.get(AAFcli.timeout())) { - activity(fp.value,HEADER + " [ " + role + " ]"); - } else { - error(fp); - } - return fp.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String role = args[idx++]; + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authz/hist/role/"+role, + getDF(History.class) + ); + if(fp.get(AAFcli.timeout())) { + activity(fp.value,HEADER + " [ " + role + " ]"); + } else { + error(fp); + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/hist/role/",History.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/hist/role/",History.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNS.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNS.java index 11476f10..361676a4 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNS.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNS.java @@ -39,34 +39,34 @@ import aaf.v2_0.Roles; * */ public class ListByNS extends Cmd { - private static final String HEADER = "List Roles by NS "; - - public ListByNS(List parent) { - super(parent,"ns", - new Param("name",true)); - } + private static final String HEADER = "List Roles by NS "; + + public ListByNS(List parent) { + super(parent,"ns", + new Param("name",true)); + } - @Override - public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - final String ns=args[idx]; + @Override + public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { + final String ns=args[idx]; - return same(((List)parent).new ListRoles() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/roles/ns/"+ns+(aafcli.isDetailed()?"?ns":""), - getDF(Roles.class) - ); - return list(fp,client, HEADER+"["+ns+"]"); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/roles/name/",Roles.class,true); - } + return same(((List)parent).new ListRoles() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authz/roles/ns/"+ns+(aafcli.isDetailed()?"?ns":""), + getDF(Roles.class) + ); + return list(fp,client, HEADER+"["+ns+"]"); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/roles/name/",Roles.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNameOnly.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNameOnly.java index 81b86718..4d77c460 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNameOnly.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByNameOnly.java @@ -39,34 +39,34 @@ import aaf.v2_0.Roles; * */ public class ListByNameOnly extends Cmd { - private static final String HEADER = "List Roles by Name "; - - public ListByNameOnly(List parent) { - super(parent,"name", - new Param("name",true)); - } + private static final String HEADER = "List Roles by Name "; + + public ListByNameOnly(List parent) { + super(parent,"name", + new Param("name",true)); + } - @Override - public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - final String name=args[idx]; + @Override + public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { + final String name=args[idx]; - return same(((List)parent).new ListRoles() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/roles/name/"+name+(aafcli.isDetailed()?"?ns":""), - getDF(Roles.class) - ); - return list(fp,client, HEADER+"["+name+"]"); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/roles/name/",Roles.class,true); - } + return same(((List)parent).new ListRoles() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authz/roles/name/"+name+(aafcli.isDetailed()?"?ns":""), + getDF(Roles.class) + ); + return list(fp,client, HEADER+"["+name+"]"); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/roles/name/",Roles.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByPerm.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByPerm.java index cb18eb34..3431a0ea 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByPerm.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByPerm.java @@ -39,40 +39,40 @@ import aaf.v2_0.Roles; * */ public class ListByPerm extends Cmd { - private static final String HEADER = "List Roles by Perm "; - - public ListByPerm(List parent) { - super(parent,"perm", - new Param("type",true), - new Param("instance", true), - new Param("action", true)); - } + private static final String HEADER = "List Roles by Perm "; + + public ListByPerm(List parent) { + super(parent,"perm", + new Param("type",true), + new Param("instance", true), + new Param("action", true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String type=args[idx]; - final String instance=args[++idx]; - final String action=args[++idx]; + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String type=args[idx]; + final String instance=args[++idx]; + final String action=args[++idx]; - return same(((List)parent).new ListRoles() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { + return same(((List)parent).new ListRoles() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/roles/perm/"+type+'/'+instance+'/'+action, - getDF(Roles.class) - ); - return list(fp,client, HEADER+type+'|'+instance+'|'+action); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/roles/user/",Roles.class,true); - } + Future fp = client.read( + "/authz/roles/perm/"+type+'/'+instance+'/'+action, + getDF(Roles.class) + ); + return list(fp,client, HEADER+type+'|'+instance+'|'+action); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/roles/user/",Roles.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByRole.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByRole.java index 0fafbd92..761df695 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByRole.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByRole.java @@ -38,32 +38,32 @@ import aaf.v2_0.Roles; * */ public class ListByRole extends Cmd { - private static final String HEADER="List Roles for Role"; - - public ListByRole(List parent) { - super(parent,"role", - new Param("role",true)); - } + private static final String HEADER="List Roles for Role"; + + public ListByRole(List parent) { + super(parent,"role", + new Param("role",true)); + } - @Override - public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { - return same(((List)parent).new ListRoles() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - String role=args[idx]; - Future fp = client.read( - "/authz/roles/"+role+(aafcli.isDetailed()?"?ns":""), - getDF(Roles.class) - ); - return list(fp,client,HEADER+"["+role+"]"); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/roles/",Roles.class,true); - } + @Override + public int _exec(final int idx, final String ... args) throws CadiException, APIException, LocatorException { + return same(((List)parent).new ListRoles() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + String role=args[idx]; + Future fp = client.read( + "/authz/roles/"+role+(aafcli.isDetailed()?"?ns":""), + getDF(Roles.class) + ); + return list(fp,client,HEADER+"["+role+"]"); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/roles/",Roles.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java index 7165de67..c9ed37a4 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java @@ -42,58 +42,58 @@ import aaf.v2_0.UserRoles; * */ public class ListByUser extends Cmd { - private static final String HEADER = "List Roles for User "; - - public ListByUser(List parent) { - super(parent,"user", - new Param("id",true), - new Param("detail", false)); - } + private static final String HEADER = "List Roles for User "; + + public ListByUser(List parent) { + super(parent,"user", + new Param("id",true), + new Param("detail", false)); + } - @Override - public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - final String user=fullID(args[idx]); - + @Override + public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { + final String user=fullID(args[idx]); + - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Perms perms=null; - UserRoles urs=null; - Future fr = client.read( - "/authz/roles/user/"+user+(aafcli.isDetailed()?"?ns":""), - getDF(Roles.class) - ); - Future fur = client.read( - "/authz/userRoles/user/"+user, - getDF(UserRoles.class) - ); - if(fr.get(AAFcli.timeout())) { - if (aafcli.isDetailed()) { - Future fp = client.read( - "/authz/perms/user/"+user+(aafcli.isDetailed()?"?ns":""), - getDF(Perms.class) - ); - if(fp.get(AAFcli.timeout())) { - perms = fp.value; - } - } - if (fur.get(AAFcli.timeout())) { - urs = fur.value; - } - - ((List)parent).report(fr.value,perms,urs,HEADER,user); - } else { - error(fr); - } - return fr.code(); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/roles/user/",Roles.class,true); - } + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Perms perms=null; + UserRoles urs=null; + Future fr = client.read( + "/authz/roles/user/"+user+(aafcli.isDetailed()?"?ns":""), + getDF(Roles.class) + ); + Future fur = client.read( + "/authz/userRoles/user/"+user, + getDF(UserRoles.class) + ); + if(fr.get(AAFcli.timeout())) { + if (aafcli.isDetailed()) { + Future fp = client.read( + "/authz/perms/user/"+user+(aafcli.isDetailed()?"?ns":""), + getDF(Perms.class) + ); + if(fp.get(AAFcli.timeout())) { + perms = fp.value; + } + } + if (fur.get(AAFcli.timeout())) { + urs = fur.value; + } + + ((List)parent).report(fr.value,perms,urs,HEADER,user); + } else { + error(fr); + } + return fr.code(); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/roles/user/",Roles.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Role.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Role.java index f28654ee..e3c838af 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Role.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Role.java @@ -26,14 +26,14 @@ import org.onap.aaf.auth.cmd.BaseCmd; import org.onap.aaf.misc.env.APIException; public class Role extends BaseCmd { - public List list; + public List list; - public Role(AAFcli aafcli) throws APIException { - super(aafcli, "role"); - cmds.add(new CreateDelete(this)); -// cmds.add(new Delete(this)); - cmds.add(new User(this)); - cmds.add(new Describe(this)); - cmds.add(list = new List(this)); - } + public Role(AAFcli aafcli) throws APIException { + super(aafcli, "role"); + cmds.add(new CreateDelete(this)); +// cmds.add(new Delete(this)); + cmds.add(new User(this)); + cmds.add(new Describe(this)); + cmds.add(list = new List(this)); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java index 181804b9..c628eb17 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java @@ -40,130 +40,130 @@ import aaf.v2_0.UserRoleRequest; * */ public class User extends Cmd { - private final static String[] options = {"add","del","setTo","extend"}; - public User(Role parent) { - super(parent,"user", - new Param(optionsToString(options),true), - new Param("role",true), - new Param("id[,id]* (not required for setTo)",false)); - } + private final static String[] options = {"add","del","setTo","extend"}; + public User(Role parent) { + super(parent,"user", + new Param(optionsToString(options),true), + new Param("role",true), + new Param("id[,id]* (not required for setTo)",false)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String action = args[idx++]; - int option = whichOption(options, action); - UserRoleRequest urr = new UserRoleRequest(); - urr.setRole(args[idx++]); - // Set Start/End commands - setStartEnd(urr); - - Future fp = null; - - if (option != 2) { - String[] ids = args[idx++].split(","); - String verb=null,participle=null; - // You can request to be added or removed from role. - setQueryParamsOn(client); + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String action = args[idx++]; + int option = whichOption(options, action); + UserRoleRequest urr = new UserRoleRequest(); + urr.setRole(args[idx++]); + // Set Start/End commands + setStartEnd(urr); + + Future fp = null; + + if (option != 2) { + String[] ids = args[idx++].split(","); + String verb=null,participle=null; + // You can request to be added or removed from role. + setQueryParamsOn(client); - for(String id: ids) { - id=fullID(id); - urr.setUser(id); - switch(option) { - case 0: - fp = client.create( - "/authz/userRole", - getDF(UserRoleRequest.class), - urr); - verb = "Added"; - participle = "] to Role [" ; - break; - case 1: - fp = client.delete( - "/authz/userRole/"+urr.getUser()+'/'+urr.getRole(), - Void.class); - verb = "Removed"; - participle = "] from Role [" ; - break; - case 3: - fp = client.update("/authz/userRole/extend/" + urr.getUser() + '/' + urr.getRole()); - verb = "Extended"; - participle = "] in Role [" ; - break; + for(String id: ids) { + id=fullID(id); + urr.setUser(id); + switch(option) { + case 0: + fp = client.create( + "/authz/userRole", + getDF(UserRoleRequest.class), + urr); + verb = "Added"; + participle = "] to Role [" ; + break; + case 1: + fp = client.delete( + "/authz/userRole/"+urr.getUser()+'/'+urr.getRole(), + Void.class); + verb = "Removed"; + participle = "] from Role [" ; + break; + case 3: + fp = client.update("/authz/userRole/extend/" + urr.getUser() + '/' + urr.getRole()); + verb = "Extended"; + participle = "] in Role [" ; + break; - default: // actually, should never get here... - throw new CadiException("Invalid action [" + action + ']'); - } - if(fp.get(AAFcli.timeout())) { - pw().print(verb); - pw().print(" User ["); - pw().print(urr.getUser()); - pw().print(participle); - pw().print(urr.getRole()); - pw().println(']'); - } else { - switch(fp.code()) { - case 202: - pw().print("User Role "); - pw().print(action); - pw().println(" is Accepted, but requires Approvals before actualizing"); - break; - case 404: - if(option==3) { - pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); - break; - } - default: - error(fp); - } - } - } - } else { - String allUsers = ""; - if (idx < args.length) - allUsers = args[idx++]; - StringBuilder finalUsers = new StringBuilder(); - for (String u : allUsers.split(",")) { - if (u != "") { - u=fullID(u); - if (finalUsers.length() > 0) finalUsers.append(","); - finalUsers.append(u); - } - } + default: // actually, should never get here... + throw new CadiException("Invalid action [" + action + ']'); + } + if(fp.get(AAFcli.timeout())) { + pw().print(verb); + pw().print(" User ["); + pw().print(urr.getUser()); + pw().print(participle); + pw().print(urr.getRole()); + pw().println(']'); + } else { + switch(fp.code()) { + case 202: + pw().print("User Role "); + pw().print(action); + pw().println(" is Accepted, but requires Approvals before actualizing"); + break; + case 404: + if(option==3) { + pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); + break; + } + default: + error(fp); + } + } + } + } else { + String allUsers = ""; + if (idx < args.length) + allUsers = args[idx++]; + StringBuilder finalUsers = new StringBuilder(); + for (String u : allUsers.split(",")) { + if (u != "") { + u=fullID(u); + if (finalUsers.length() > 0) finalUsers.append(","); + finalUsers.append(u); + } + } - urr.setUser(finalUsers.toString()); - fp = client.update( - "/authz/userRole/role", - getDF(UserRoleRequest.class), - urr); - if(fp.get(AAFcli.timeout())) { - pw().println("Set the Role to Users [" + allUsers + "]"); - } else { - error(fp); - } - } - return fp==null?0:fp.code(); - } - }); - } - - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,"Add OR Delete a User to/from a Role OR"); - detailLine(sb,indent,"Set a User's Roles to the roles supplied"); - detailLine(sb,indent+2,"role - Name of Role to create"); - detailLine(sb,indent+2,"id(s) - ID or IDs to add to the Role"); - sb.append('\n'); - detailLine(sb,indent+2,"Note: this is the same as \"user role add...\" except allows"); - detailLine(sb,indent+2,"assignment of role to multiple userss"); - detailLine(sb,indent+2,"WARNING: Users supplied with setTo will be the ONLY users attached to this role"); - detailLine(sb,indent+2,"If no users are supplied, the users attached to this role are reset."); - api(sb,indent,HttpMethods.POST,"authz/userRole",UserRoleRequest.class,true); - api(sb,indent,HttpMethods.DELETE,"authz/userRole//",Void.class,false); - api(sb,indent,HttpMethods.PUT,"authz/userRole/",UserRoleRequest.class,false); - } + urr.setUser(finalUsers.toString()); + fp = client.update( + "/authz/userRole/role", + getDF(UserRoleRequest.class), + urr); + if(fp.get(AAFcli.timeout())) { + pw().println("Set the Role to Users [" + allUsers + "]"); + } else { + error(fp); + } + } + return fp==null?0:fp.code(); + } + }); + } + + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,"Add OR Delete a User to/from a Role OR"); + detailLine(sb,indent,"Set a User's Roles to the roles supplied"); + detailLine(sb,indent+2,"role - Name of Role to create"); + detailLine(sb,indent+2,"id(s) - ID or IDs to add to the Role"); + sb.append('\n'); + detailLine(sb,indent+2,"Note: this is the same as \"user role add...\" except allows"); + detailLine(sb,indent+2,"assignment of role to multiple userss"); + detailLine(sb,indent+2,"WARNING: Users supplied with setTo will be the ONLY users attached to this role"); + detailLine(sb,indent+2,"If no users are supplied, the users attached to this role are reset."); + api(sb,indent,HttpMethods.POST,"authz/userRole",UserRoleRequest.class,true); + api(sb,indent,HttpMethods.DELETE,"authz/userRole//",Void.class,false); + api(sb,indent,HttpMethods.PUT,"authz/userRole/",UserRoleRequest.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java index 10333091..40447c19 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java @@ -35,123 +35,123 @@ import org.onap.aaf.misc.env.APIException; import aaf.v2_0.CredRequest; public class Cred extends Cmd { - public static final String ATTEMPT_FAILED_SPECIFICS_WITHELD = "Attempt Failed. Specifics witheld."; - private static final String CRED_PATH = "/authn/cred"; - private static final String[] options = {"add","del","reset","extend"/*,"clean"*/}; -// private Clean clean; - public Cred(User parent) { - super(parent,"cred", - new Param(optionsToString(options),true), - new Param("id",true), - new Param("password (! D|E)",false), - new Param("entry# (if multi)",false) - ); -// clean = new Clean(this); - } + public static final String ATTEMPT_FAILED_SPECIFICS_WITHELD = "Attempt Failed. Specifics witheld."; + private static final String CRED_PATH = "/authn/cred"; + private static final String[] options = {"add","del","reset","extend"/*,"clean"*/}; +// private Clean clean; + public Cred(User parent) { + super(parent,"cred", + new Param(optionsToString(options),true), + new Param("id",true), + new Param("password (! D|E)",false), + new Param("entry# (if multi)",false) + ); +// clean = new Clean(this); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - String key = args[idx++]; - final int option = whichOption(options,key); + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + String key = args[idx++]; + final int option = whichOption(options,key); - final CredRequest cr = new CredRequest(); - cr.setId(args[idx++]); - if(option!=1 && option!=3) { - if(idx>=args.length) throw new CadiException("Password Required"); - cr.setPassword(args[idx++]); - } - if(args.length>idx) - cr.setEntry(args[idx++]); - - // Set Start/End commands - setStartEnd(cr); -// final int cleanIDX = _idx+1; - Integer ret = same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp=null; - String verb =null; - switch(option) { - case 0: - fp = client.create( - CRED_PATH, - getDF(CredRequest.class), - cr - ); - verb = "Added Credential ["; - break; - case 1: -// if(aafcli.addForce())cr.setForce("TRUE"); - setQueryParamsOn(client); - fp = client.delete(CRED_PATH, - getDF(CredRequest.class), - cr - ); - verb = "Deleted Credential ["; - break; - case 2: - fp = client.update( - CRED_PATH, - getDF(CredRequest.class), - cr - ); - verb = "Reset Credential ["; - break; - case 3: - fp = client.update( - CRED_PATH+"/5", - getDF(CredRequest.class), - cr - ); - verb = "Extended Credential ["; - break; -// case 4: -// return clean.exec(cleanIDX, args); - } - if(fp==null) { - return null; // get by Sonar check. - } - if(fp.get(AAFcli.timeout())) { - pw().print(verb); - pw().print(cr.getId()); - pw().println(']'); - } else if(fp.code()==202) { - pw().println("Credential Action Accepted, but requires Approvals before actualizing"); - } else if(fp.code()==406 && option==1) { - pw().println("You cannot delete this Credential"); - } else { - pw().println(ATTEMPT_FAILED_SPECIFICS_WITHELD); - } - return fp.code(); - } - }); - if(ret==null)ret = -1; - return ret; - } - - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Add, Delete or Reset Credential"); - indent+=2; - detailLine(sb,indent,"id - the ID to create/delete/reset within AAF"); - detailLine(sb,indent,"password - Company Policy compliant Password (not required for Delete)"); - detailLine(sb,indent,"entry - selected option when deleting/resetting a cred with multiple entries"); - sb.append('\n'); - detailLine(sb,indent,"The Domain can be related to any Namespace you have access to *"); - detailLine(sb,indent,"The Domain is in reverse order of Namespace, i.e. "); - detailLine(sb,indent+2,"NS of com.att.myapp can create user of XY1234@myapp.att.com"); - sb.append('\n'); - detailLine(sb,indent,"NOTE: AAF does support multiple creds with the same ID. Check with your org if you"); - detailLine(sb,indent+2,"have this implemented. (For example, this is implemented for MechIDs at AT&T)"); - sb.append('\n'); - detailLine(sb,indent,"*NOTE: com.att.csp is a reserved Domain for Global Sign On"); + final CredRequest cr = new CredRequest(); + cr.setId(args[idx++]); + if(option!=1 && option!=3) { + if(idx>=args.length) throw new CadiException("Password Required"); + cr.setPassword(args[idx++]); + } + if(args.length>idx) + cr.setEntry(args[idx++]); + + // Set Start/End commands + setStartEnd(cr); +// final int cleanIDX = _idx+1; + Integer ret = same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp=null; + String verb =null; + switch(option) { + case 0: + fp = client.create( + CRED_PATH, + getDF(CredRequest.class), + cr + ); + verb = "Added Credential ["; + break; + case 1: +// if(aafcli.addForce())cr.setForce("TRUE"); + setQueryParamsOn(client); + fp = client.delete(CRED_PATH, + getDF(CredRequest.class), + cr + ); + verb = "Deleted Credential ["; + break; + case 2: + fp = client.update( + CRED_PATH, + getDF(CredRequest.class), + cr + ); + verb = "Reset Credential ["; + break; + case 3: + fp = client.update( + CRED_PATH+"/5", + getDF(CredRequest.class), + cr + ); + verb = "Extended Credential ["; + break; +// case 4: +// return clean.exec(cleanIDX, args); + } + if(fp==null) { + return null; // get by Sonar check. + } + if(fp.get(AAFcli.timeout())) { + pw().print(verb); + pw().print(cr.getId()); + pw().println(']'); + } else if(fp.code()==202) { + pw().println("Credential Action Accepted, but requires Approvals before actualizing"); + } else if(fp.code()==406 && option==1) { + pw().println("You cannot delete this Credential"); + } else { + pw().println(ATTEMPT_FAILED_SPECIFICS_WITHELD); + } + return fp.code(); + } + }); + if(ret==null)ret = -1; + return ret; + } + + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Add, Delete or Reset Credential"); + indent+=2; + detailLine(sb,indent,"id - the ID to create/delete/reset within AAF"); + detailLine(sb,indent,"password - Company Policy compliant Password (not required for Delete)"); + detailLine(sb,indent,"entry - selected option when deleting/resetting a cred with multiple entries"); + sb.append('\n'); + detailLine(sb,indent,"The Domain can be related to any Namespace you have access to *"); + detailLine(sb,indent,"The Domain is in reverse order of Namespace, i.e. "); + detailLine(sb,indent+2,"NS of com.att.myapp can create user of XY1234@myapp.att.com"); + sb.append('\n'); + detailLine(sb,indent,"NOTE: AAF does support multiple creds with the same ID. Check with your org if you"); + detailLine(sb,indent+2,"have this implemented. (For example, this is implemented for MechIDs at AT&T)"); + sb.append('\n'); + detailLine(sb,indent,"*NOTE: com.att.csp is a reserved Domain for Global Sign On"); - detailLine(sb,indent,"Delegates can be listed by the User or by the Delegate"); - indent-=2; - api(sb,indent,HttpMethods.POST,"authn/cred",CredRequest.class,true); - api(sb,indent,HttpMethods.DELETE,"authn/cred",CredRequest.class,false); - api(sb,indent,HttpMethods.PUT,"authn/cred",CredRequest.class,false); - } + detailLine(sb,indent,"Delegates can be listed by the User or by the Delegate"); + indent-=2; + api(sb,indent,HttpMethods.POST,"authn/cred",CredRequest.class,true); + api(sb,indent,HttpMethods.DELETE,"authn/cred",CredRequest.class,false); + api(sb,indent,HttpMethods.PUT,"authn/cred",CredRequest.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java index ec1aa5a0..8587ac3d 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java @@ -40,92 +40,92 @@ import org.onap.aaf.misc.rosetta.env.RosettaDF; import aaf.v2_0.DelgRequest; public class Delg extends BaseCmd { - static final String AUTHZ_DELG = "/authz/delegate"; - private final static String[] options = {"add","upd","del"}; + static final String AUTHZ_DELG = "/authz/delegate"; + private final static String[] options = {"add","upd","del"}; - public Delg(User user) throws APIException { - super(user,"delegate", - new Param(optionsToString(options),true), - new Param("from",true), - new Param("to REQ A&U",false), - new Param("until (YYYY-MM-DD) REQ A", false) - ); - } + public Delg(User user) throws APIException { + super(user,"delegate", + new Param(optionsToString(options),true), + new Param("from",true), + new Param("to REQ A&U",false), + new Param("until (YYYY-MM-DD) REQ A", false) + ); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - DelgRequest dr = new DelgRequest(); - setStartEnd(dr); - - int option= whichOption(options, args[idx++]); - String user = fullID(args[idx++]); - dr.setUser(user); - if(option<2) { - String delegate = fullID(args[idx++]); - dr.setDelegate(delegate); - if(option<2 && args.length>idx) { - Date date; - try { - date = Chrono.dateOnlyFmt.parse(args[idx++]); - } catch (ParseException e) { - throw new CadiException(e); - } - dr.setEnd(Chrono.timeStamp(date)); - } - } - - Future fp; - RosettaDF df = getDF(DelgRequest.class); - String verb; - setQueryParamsOn(client); + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + DelgRequest dr = new DelgRequest(); + setStartEnd(dr); + + int option= whichOption(options, args[idx++]); + String user = fullID(args[idx++]); + dr.setUser(user); + if(option<2) { + String delegate = fullID(args[idx++]); + dr.setDelegate(delegate); + if(option<2 && args.length>idx) { + Date date; + try { + date = Chrono.dateOnlyFmt.parse(args[idx++]); + } catch (ParseException e) { + throw new CadiException(e); + } + dr.setEnd(Chrono.timeStamp(date)); + } + } + + Future fp; + RosettaDF df = getDF(DelgRequest.class); + String verb; + setQueryParamsOn(client); - switch(option) { - case 0: - fp = client.create(AUTHZ_DELG, df, dr); - verb = "Added"; - break; - case 1: - fp = client.update(AUTHZ_DELG, df, dr); - verb = "Updated"; - break; - case 2: - fp = client.delete(AUTHZ_DELG, df, dr); - verb = "Deleted"; - break; - default: - throw new CadiException("Bad Argument"); - }; - - if(fp.get(AAFcli.timeout())) { - pw().append("Delegate "); - pw().println(verb); - } else { - error(fp); - } - return fp.code(); - } - }); - } + switch(option) { + case 0: + fp = client.create(AUTHZ_DELG, df, dr); + verb = "Added"; + break; + case 1: + fp = client.update(AUTHZ_DELG, df, dr); + verb = "Updated"; + break; + case 2: + fp = client.delete(AUTHZ_DELG, df, dr); + verb = "Deleted"; + break; + default: + throw new CadiException("Bad Argument"); + }; + + if(fp.get(AAFcli.timeout())) { + pw().append("Delegate "); + pw().println(verb); + } else { + error(fp); + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,"Add, Update or Delete Delegate"); - indent+=2; - detailLine(sb,indent,"A Delegate is a person who will temporarily cover the Approval and"); - detailLine(sb,indent,"Ownership questions on behalf of the person Responsible."); - sb.append('\n'); - detailLine(sb,indent,"fromID - the person who is the Responsible person of record"); - detailLine(sb,indent,"toID - the person who will be delegated (required for Add/Update)"); - detailLine(sb,indent,"until - the end date for this delegation"); - indent-=2; - api(sb,indent,HttpMethods.POST,AUTHZ_DELG,DelgRequest.class,true); - api(sb,indent,HttpMethods.DELETE,AUTHZ_DELG,DelgRequest.class,false); - api(sb,indent,HttpMethods.PUT,AUTHZ_DELG,DelgRequest.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,"Add, Update or Delete Delegate"); + indent+=2; + detailLine(sb,indent,"A Delegate is a person who will temporarily cover the Approval and"); + detailLine(sb,indent,"Ownership questions on behalf of the person Responsible."); + sb.append('\n'); + detailLine(sb,indent,"fromID - the person who is the Responsible person of record"); + detailLine(sb,indent,"toID - the person who will be delegated (required for Add/Update)"); + detailLine(sb,indent,"until - the end date for this delegation"); + indent-=2; + api(sb,indent,HttpMethods.POST,AUTHZ_DELG,DelgRequest.class,true); + api(sb,indent,HttpMethods.DELETE,AUTHZ_DELG,DelgRequest.class,false); + api(sb,indent,HttpMethods.PUT,AUTHZ_DELG,DelgRequest.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java index a977431c..03148ce5 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java @@ -35,87 +35,87 @@ import aaf.v2_0.Users; public class List extends BaseCmd { - public List(User parent) { - super(parent,"list"); - cmds.add(new ListForRoles(this)); - cmds.add(new ListForPermission(this)); - cmds.add(new ListForCreds(this)); - cmds.add(new ListDelegates(this)); - cmds.add(new ListApprovals(this)); - cmds.add(new ListActivity(this)); - } + public List(User parent) { + super(parent,"list"); + cmds.add(new ListForRoles(this)); + cmds.add(new ListForPermission(this)); + cmds.add(new ListForCreds(this)); + cmds.add(new ListDelegates(this)); + cmds.add(new ListApprovals(this)); + cmds.add(new ListActivity(this)); + } - - void report(Users users, boolean count, String ... str) { - reportHead(str); - int idx = 0; - java.util.List sorted = users.getUser(); - Collections.sort(sorted, new Comparator() { - @Override - public int compare(aaf.v2_0.Users.User u1, aaf.v2_0.Users.User u2) { - if(u1==null || u2 == null) { - return -1; - } - return u1.getId().compareTo(u2.getId()); - } - }); - String format = reportColHead("%-40s %-10s %-30s\n","User","Type","Expires"); - String date = "XXXX-XX-XX"; - for(aaf.v2_0.Users.User user : sorted) { - if(!aafcli.isTest()) { - date = Chrono.dateOnlyStamp(user.getExpires()); - } - pw().format(format, - count? (Integer.valueOf(++idx) + ") " + user.getId()): user.getId(), - org.onap.aaf.auth.cmd.ns.List.getType(user), - date); - } - pw().println(); - } + + void report(Users users, boolean count, String ... str) { + reportHead(str); + int idx = 0; + java.util.List sorted = users.getUser(); + Collections.sort(sorted, new Comparator() { + @Override + public int compare(aaf.v2_0.Users.User u1, aaf.v2_0.Users.User u2) { + if(u1==null || u2 == null) { + return -1; + } + return u1.getId().compareTo(u2.getId()); + } + }); + String format = reportColHead("%-40s %-10s %-30s\n","User","Type","Expires"); + String date = "XXXX-XX-XX"; + for(aaf.v2_0.Users.User user : sorted) { + if(!aafcli.isTest()) { + date = Chrono.dateOnlyStamp(user.getExpires()); + } + pw().format(format, + count? (Integer.valueOf(++idx) + ") " + user.getId()): user.getId(), + org.onap.aaf.auth.cmd.ns.List.getType(user), + date); + } + pw().println(); + } - public void report(Approvals approvals, String title, String id) { - reportHead(title,id); - String format = reportColHead(" %-20s %-20s %-11s %-6s %12s\n","User","Approver","Type","Status","Updated"); - java.util.List lapp = approvals.getApprovals(); - Collections.sort(lapp, new Comparator() { - @Override - public int compare(Approval a1, Approval a2) { - return a1.getTicket().compareTo(a2.getTicket()); - } - } ); - String ticket = null, prev = null; - for(Approval app : lapp ) { - ticket = app.getTicket(); - if(!ticket.equals(prev)) { - pw().print("Ticket: "); - pw().println(ticket); - } - prev = ticket; + public void report(Approvals approvals, String title, String id) { + reportHead(title,id); + String format = reportColHead(" %-20s %-20s %-11s %-6s %12s\n","User","Approver","Type","Status","Updated"); + java.util.List lapp = approvals.getApprovals(); + Collections.sort(lapp, new Comparator() { + @Override + public int compare(Approval a1, Approval a2) { + return a1.getTicket().compareTo(a2.getTicket()); + } + } ); + String ticket = null, prev = null; + for(Approval app : lapp ) { + ticket = app.getTicket(); + if(!ticket.equals(prev)) { + pw().print("Ticket: "); + pw().println(ticket); + } + prev = ticket; - pw().format(format, - app.getUser(), - app.getApprover(), - app.getType(), - app.getStatus(), - Chrono.niceDateStamp(app.getUpdated()) - ); - } - } + pw().format(format, + app.getUser(), + app.getApprover(), + app.getType(), + app.getStatus(), + Chrono.niceDateStamp(app.getUpdated()) + ); + } + } - public void report(Delgs delgs, String title, String id) { - reportHead(title,id); - String format = reportColHead(" %-25s %-25s %-10s\n","User","Delegate","Expires"); - String date = "XXXX-XX-XX"; - for(Delg delg : delgs.getDelgs()) { - if(!this.aafcli.isTest()) - date = Chrono.dateOnlyStamp(delg.getExpires()); - pw().printf(format, - delg.getUser(), - delg.getDelegate(), - date - ); - } - } + public void report(Delgs delgs, String title, String id) { + reportHead(title,id); + String format = reportColHead(" %-25s %-25s %-10s\n","User","Delegate","Expires"); + String date = "XXXX-XX-XX"; + for(Delg delg : delgs.getDelgs()) { + if(!this.aafcli.isTest()) + date = Chrono.dateOnlyStamp(delg.getExpires()); + pw().printf(format, + delg.getUser(), + delg.getDelegate(), + date + ); + } + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java index 8ffcb0b6..4bb87374 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java @@ -39,40 +39,40 @@ import aaf.v2_0.History; * */ public class ListActivity extends Cmd { - private static final String HEADER = "List Activity of User"; + private static final String HEADER = "List Activity of User"; - public ListActivity(List parent) { - super(parent,"activity", - new Param("user",true)); - } + public ListActivity(List parent) { + super(parent,"activity", + new Param("user",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String user = fullID(args[idx++]); - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - - Future fp = client.read( - "/authz/hist/user/"+user, - getDF(History.class) - ); - if(fp.get(AAFcli.timeout())) { - activity(fp.value,HEADER + " [ " + user + " ]"); - } else { - error(fp); - } - return fp.code(); - } - }); - } - + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String user = fullID(args[idx++]); + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + + Future fp = client.read( + "/authz/hist/user/"+user, + getDF(History.class) + ); + if(fp.get(AAFcli.timeout())) { + activity(fp.value,HEADER + " [ " + user + " ]"); + } else { + error(fp); + } + return fp.code(); + } + }); + } + - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb,indent,HEADER); - api(sb,indent,HttpMethods.GET,"authz/hist/user/",History.class,true); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb,indent,HEADER); + api(sb,indent,HttpMethods.GET,"authz/hist/user/",History.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java index 0a461c49..d9379174 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java @@ -40,63 +40,63 @@ import aaf.v2_0.Approvals; * */ public class ListApprovals extends Cmd { - private static final String HEADER = "List Approvals"; - private final static String[] options = {"user","approver","ticket"}; - public ListApprovals(List parent) { - super(parent,"approvals", - new Param(optionsToString(options),true), - new Param("value",true)); - } + private static final String HEADER = "List Approvals"; + private final static String[] options = {"user","approver","ticket"}; + public ListApprovals(List parent) { + super(parent,"approvals", + new Param(optionsToString(options),true), + new Param("value",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String type = args[idx++]; - int option = whichOption(options,type); - String value = args[idx++]; - final String fullValue; - if (option != 2) { - fullValue = fullID(value); - } else { - fullValue = value; - } - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/approval/"+type+'/'+fullValue, - getDF(Approvals.class) - ); - if(fp.get(AAFcli.timeout())) { - ((List)parent).report(fp.value,HEADER + " by " + type,fullValue); - if(fp.code()==404) { - return 200; - } - } else { - error(fp); - } - return fp.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String type = args[idx++]; + int option = whichOption(options,type); + String value = args[idx++]; + final String fullValue; + if (option != 2) { + fullValue = fullID(value); + } else { + fullValue = value; + } + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authz/approval/"+type+'/'+fullValue, + getDF(Approvals.class) + ); + if(fp.get(AAFcli.timeout())) { + ((List)parent).report(fp.value,HEADER + " by " + type,fullValue); + if(fp.code()==404) { + return 200; + } + } else { + error(fp); + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=2; - detailLine(sb,indent,"Approvals are used when the Requestor does not have the rights"); - detailLine(sb,indent,"to perform the action required. Approvers are those listed as"); - detailLine(sb,indent,"responsible for Namespace associated with the request, and those"); - detailLine(sb,indent,"required by the Company by Policy. This may be, for instance"); - detailLine(sb,indent,"the supervisor of the requestor"); - sb.append('\n'); - detailLine(sb,indent,"Delegates can be listed by User, Approver or Ticket."); - indent-=2; - api(sb,indent,HttpMethods.GET,"authz/approval/user/",Approvals.class,true); - api(sb,indent,HttpMethods.GET,"authz/approval/approver/",Approvals.class,false); - api(sb,indent,HttpMethods.GET,"authz/approval/ticket/",Approvals.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=2; + detailLine(sb,indent,"Approvals are used when the Requestor does not have the rights"); + detailLine(sb,indent,"to perform the action required. Approvers are those listed as"); + detailLine(sb,indent,"responsible for Namespace associated with the request, and those"); + detailLine(sb,indent,"required by the Company by Policy. This may be, for instance"); + detailLine(sb,indent,"the supervisor of the requestor"); + sb.append('\n'); + detailLine(sb,indent,"Delegates can be listed by User, Approver or Ticket."); + indent-=2; + api(sb,indent,HttpMethods.GET,"authz/approval/user/",Approvals.class,true); + api(sb,indent,HttpMethods.GET,"authz/approval/approver/",Approvals.class,false); + api(sb,indent,HttpMethods.GET,"authz/approval/ticket/",Approvals.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java index 4397b426..5cc7a52b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java @@ -39,54 +39,54 @@ import aaf.v2_0.Delgs; * */ public class ListDelegates extends Cmd { - private static final String HEADER = "List Delegates"; - private static final String[] options = {"user","delegate"}; - public ListDelegates(List parent) { - super(parent,"delegates", - new Param(optionsToString(options),true), - new Param("id",true)); - } + private static final String HEADER = "List Delegates"; + private static final String[] options = {"user","delegate"}; + public ListDelegates(List parent) { + super(parent,"delegates", + new Param(optionsToString(options),true), + new Param("id",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String key = args[idx++]; - //int option = whichOption(options,key); - final String id = fullID(args[idx++]); - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - - Future fp = client.read( - "/authz/delegates/" + key + '/' + id, - getDF(Delgs.class) - ); - if(fp.get(AAFcli.timeout())) { - ((List)parent).report(fp.value,HEADER + " by " + key, id); - if(fp.code()==404)return 200; - } else { - error(fp); - } - return fp.code(); - } - }); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String key = args[idx++]; + //int option = whichOption(options,key); + final String id = fullID(args[idx++]); + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + + Future fp = client.read( + "/authz/delegates/" + key + '/' + id, + getDF(Delgs.class) + ); + if(fp.get(AAFcli.timeout())) { + ((List)parent).report(fp.value,HEADER + " by " + key, id); + if(fp.code()==404)return 200; + } else { + error(fp); + } + return fp.code(); + } + }); + } - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=2; - detailLine(sb,indent,"Delegates are those people temporarily assigned to cover the"); - detailLine(sb,indent,"responsibility of Approving, etc, while the actual Responsible"); - detailLine(sb,indent,"Party is absent. Typically, this is for Vacation, or Business"); - detailLine(sb,indent,"Travel."); - sb.append('\n'); - detailLine(sb,indent,"Delegates can be listed by the User or by the Delegate"); - indent-=2; - api(sb,indent,HttpMethods.GET,"authz/delegates/user/",Delgs.class,true); - api(sb,indent,HttpMethods.GET,"authz/delegates/delegate/",Delgs.class,false); - } + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=2; + detailLine(sb,indent,"Delegates are those people temporarily assigned to cover the"); + detailLine(sb,indent,"responsibility of Approving, etc, while the actual Responsible"); + detailLine(sb,indent,"Party is absent. Typically, this is for Vacation, or Business"); + detailLine(sb,indent,"Travel."); + sb.append('\n'); + detailLine(sb,indent,"Delegates can be listed by the User or by the Delegate"); + indent-=2; + api(sb,indent,HttpMethods.GET,"authz/delegates/user/",Delgs.class,true); + api(sb,indent,HttpMethods.GET,"authz/delegates/delegate/",Delgs.class,false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java index 4aa42f9f..a71090ea 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java @@ -44,57 +44,57 @@ import aaf.v2_0.Users.User; * */ public class ListForCreds extends Cmd { - private final static String[] options = {"ns","id"}; + private final static String[] options = {"ns","id"}; - private static final String HEADER = "List creds by Namespace or ID "; - public ListForCreds(List parent) { - super(parent,"cred", - new Param(optionsToString(options),true), - new Param("value",true)); - } + private static final String HEADER = "List creds by Namespace or ID "; + public ListForCreds(List parent) { + super(parent,"cred", + new Param(optionsToString(options),true), + new Param("value",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final int option = whichOption(options, args[idx++]); - final String which = options[option]; - final String value = args[idx++]; - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authn/creds/"+which+'/'+value, - getDF(Users.class) - ); - if(fp.get(AAFcli.timeout())) { - if (aafcli.isTest()) - Collections.sort(fp.value.getUser(), new Comparator() { - @Override - public int compare(User u1, User u2) { - return u1.getId().compareTo(u2.getId()); - } - }); - ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,option==1,HEADER+which,value); - if(fp.code()==404)return 200; - } else { - error(fp); - } - return fp.code(); - } - }); - } - - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=2; - detailLine(sb,indent,"This report lists the users associated to either Namespaces or IDs."); - detailLine(sb,indent,"ns (literal) - which Namespace"); - detailLine(sb,indent,"id (literal) - identity"); - indent-=2; - api(sb,indent,HttpMethods.GET,"authn/creds/ns/",Users.class,true); - api(sb,indent,HttpMethods.GET,"authn/creds/id/",Users.class,true); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final int option = whichOption(options, args[idx++]); + final String which = options[option]; + final String value = args[idx++]; + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authn/creds/"+which+'/'+value, + getDF(Users.class) + ); + if(fp.get(AAFcli.timeout())) { + if (aafcli.isTest()) + Collections.sort(fp.value.getUser(), new Comparator() { + @Override + public int compare(User u1, User u2) { + return u1.getId().compareTo(u2.getId()); + } + }); + ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,option==1,HEADER+which,value); + if(fp.code()==404)return 200; + } else { + error(fp); + } + return fp.code(); + } + }); + } + + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=2; + detailLine(sb,indent,"This report lists the users associated to either Namespaces or IDs."); + detailLine(sb,indent,"ns (literal) - which Namespace"); + detailLine(sb,indent,"id (literal) - identity"); + indent-=2; + api(sb,indent,HttpMethods.GET,"authn/creds/ns/",Users.class,true); + api(sb,indent,HttpMethods.GET,"authn/creds/id/",Users.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java index 32938101..439c8af6 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java @@ -44,60 +44,60 @@ import aaf.v2_0.Users.User; * */ public class ListForPermission extends Cmd { - private static final String HEADER = "List Users for Permission"; - public ListForPermission(List parent) { - super(parent,"perm", - new Param("type",true), - new Param("instance",true), - new Param("action",true)); - } + private static final String HEADER = "List Users for Permission"; + public ListForPermission(List parent) { + super(parent,"perm", + new Param("type",true), + new Param("instance",true), + new Param("action",true)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String type = args[idx++]; - String instance = args[idx++]; - if("\\*".equals(instance))instance="*"; - String action = args[idx++]; - if("\\*".equals(action))action="*"; - Future fp = client.read( - "/authz/users/perm/"+type+'/'+instance+'/'+action, - getDF(Users.class) - ); - if(fp.get(AAFcli.timeout())) { - if (aafcli.isTest()) - Collections.sort(fp.value.getUser(), new Comparator() { - @Override - public int compare(User u1, User u2) { - return u1.getId().compareTo(u2.getId()); - } - }); - ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false,HEADER,type+"|"+instance+"|"+action); - if(fp.code()==404)return 200; - } else { - error(fp); - } - return fp.code(); - } - }); - } - - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=2; - detailLine(sb,indent,"This report lists the users associated to Permissions. Since Users"); - detailLine(sb,indent,"are associated to Roles, and Roles have Permissions, this report"); - detailLine(sb,indent,"accomodates all these linkages."); - sb.append('\n'); - detailLine(sb,indent,"The URL must contain the Permission's type,instance and action, and "); - detailLine(sb,indent,"may include \"*\"s (type in as \\\\*)."); - detailLine(sb,indent,"See Perm Create Documentation for definitions."); - indent-=2; - api(sb,indent,HttpMethods.GET,"authz/users/perm///",Users.class,true); - } + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String type = args[idx++]; + String instance = args[idx++]; + if("\\*".equals(instance))instance="*"; + String action = args[idx++]; + if("\\*".equals(action))action="*"; + Future fp = client.read( + "/authz/users/perm/"+type+'/'+instance+'/'+action, + getDF(Users.class) + ); + if(fp.get(AAFcli.timeout())) { + if (aafcli.isTest()) + Collections.sort(fp.value.getUser(), new Comparator() { + @Override + public int compare(User u1, User u2) { + return u1.getId().compareTo(u2.getId()); + } + }); + ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false,HEADER,type+"|"+instance+"|"+action); + if(fp.code()==404)return 200; + } else { + error(fp); + } + return fp.code(); + } + }); + } + + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=2; + detailLine(sb,indent,"This report lists the users associated to Permissions. Since Users"); + detailLine(sb,indent,"are associated to Roles, and Roles have Permissions, this report"); + detailLine(sb,indent,"accomodates all these linkages."); + sb.append('\n'); + detailLine(sb,indent,"The URL must contain the Permission's type,instance and action, and "); + detailLine(sb,indent,"may include \"*\"s (type in as \\\\*)."); + detailLine(sb,indent,"See Perm Create Documentation for definitions."); + indent-=2; + api(sb,indent,HttpMethods.GET,"authz/users/perm///",Users.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java index 28d7f57a..1d1b328a 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java @@ -44,49 +44,49 @@ import aaf.v2_0.Users.User; * */ public class ListForRoles extends Cmd { - private static final String HEADER = "List Users for Role"; - public ListForRoles(List parent) { - super(parent,"role", new Param("role",true)); - } + private static final String HEADER = "List Users for Role"; + public ListForRoles(List parent) { + super(parent,"role", new Param("role",true)); + } - @Override - public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { - int idx = _idx; - final String role = args[idx++]; - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - Future fp = client.read( - "/authz/users/role/"+role, - getDF(Users.class) - ); - if(fp.get(AAFcli.timeout())) { - if (aafcli.isTest()) - Collections.sort(fp.value.getUser(), new Comparator() { - @Override - public int compare(User u1, User u2) { - return u1.getId().compareTo(u2.getId()); - } - }); - ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false, HEADER,role); - if(fp.code()==404)return 200; - } else { - error(fp); - } - return fp.code(); - } - }); - } - - @Override - public void detailedHelp(int _indent, StringBuilder sb) { - int indent = _indent; - detailLine(sb,indent,HEADER); - indent+=2; - detailLine(sb,indent,"This report lists the users associated to Roles."); - detailLine(sb,indent,"role - the Role name"); - indent-=2; - api(sb,indent,HttpMethods.GET,"authz/users/role/",Users.class,true); - } + @Override + public int _exec(int _idx, final String ... args) throws CadiException, APIException, LocatorException { + int idx = _idx; + final String role = args[idx++]; + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + Future fp = client.read( + "/authz/users/role/"+role, + getDF(Users.class) + ); + if(fp.get(AAFcli.timeout())) { + if (aafcli.isTest()) + Collections.sort(fp.value.getUser(), new Comparator() { + @Override + public int compare(User u1, User u2) { + return u1.getId().compareTo(u2.getId()); + } + }); + ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false, HEADER,role); + if(fp.code()==404)return 200; + } else { + error(fp); + } + return fp.code(); + } + }); + } + + @Override + public void detailedHelp(int _indent, StringBuilder sb) { + int indent = _indent; + detailLine(sb,indent,HEADER); + indent+=2; + detailLine(sb,indent,"This report lists the users associated to Roles."); + detailLine(sb,indent,"role - the Role name"); + indent-=2; + api(sb,indent,HttpMethods.GET,"authz/users/role/",Users.class,true); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java index 70bc16a3..04b444a1 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java @@ -41,115 +41,115 @@ import aaf.v2_0.UserRoleRequest; * */ public class Role extends Cmd { - private static final String[] options = {"add", "del", "setTo","extend"}; - public Role(User parent) { - super(parent, "role", new Param(optionsToString(options), true), new Param("user", true), new Param( - "role[,role]* (!REQ S)", false)); - } + private static final String[] options = {"add", "del", "setTo","extend"}; + public Role(User parent) { + super(parent, "role", new Param(optionsToString(options), true), new Param("user", true), new Param( + "role[,role]* (!REQ S)", false)); + } - @Override - public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { - return same(new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, APIException { - int idx = index; - String key = args[idx++]; - int option = whichOption(options, key); - final String user = fullID(args[idx++]); + @Override + public int _exec(final int index, final String ... args) throws CadiException, APIException, LocatorException { + return same(new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, APIException { + int idx = index; + String key = args[idx++]; + int option = whichOption(options, key); + final String user = fullID(args[idx++]); - UserRoleRequest urr = new UserRoleRequest(); - urr.setUser(user); - // Set Start/End commands - setStartEnd(urr); + UserRoleRequest urr = new UserRoleRequest(); + urr.setUser(user); + // Set Start/End commands + setStartEnd(urr); - Future fp = null; + Future fp = null; - if (option != 2) { - if (args.length < 5) { - throw new CadiException(build(new StringBuilder("Too few args: "), null).toString()); - } - String[] roles = args[idx++].split(","); - for (String role : roles) { - String verb = null,participle=null; - urr.setRole(role); - // You can request to be added or removed from role. - setQueryParamsOn(client); - switch(option) { - case 0: - fp = client.create("/authz/userRole", getDF(UserRoleRequest.class), urr); - verb = "Added"; - participle = "] to User [" ; - break; - case 1: - fp = client.delete("/authz/userRole/" + urr.getUser() + '/' + urr.getRole(), Void.class); - verb = "Removed"; - participle = "] from User [" ; - break; - case 3: - fp = client.update("/authz/userRole/extend/" + urr.getUser() + '/' + urr.getRole()); - verb = "Extended"; - participle = "] to User [" ; - break; - default: - throw new CadiException("Invalid action [" + key + ']'); - } - if (fp.get(AAFcli.timeout())) { - pw().print(verb); - pw().print(" Role ["); - pw().print(urr.getRole()); - pw().print(participle); - pw().print(urr.getUser()); - pw().println(']'); - } else { - switch(fp.code()) { - case 202: - pw().print("UserRole "); - pw().print(option == 0 ? "Creation" : option==1?"Deletion":"Extension"); - pw().println(" Accepted, but requires Approvals before actualizing"); - break; - case 404: - if(option==3) { - pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); - break; - } - default: - error(fp); - } - } - } - } else { - // option 2 is setTo command (an update call) - String allRoles = ""; - if (idx < args.length) - allRoles = args[idx++]; + if (option != 2) { + if (args.length < 5) { + throw new CadiException(build(new StringBuilder("Too few args: "), null).toString()); + } + String[] roles = args[idx++].split(","); + for (String role : roles) { + String verb = null,participle=null; + urr.setRole(role); + // You can request to be added or removed from role. + setQueryParamsOn(client); + switch(option) { + case 0: + fp = client.create("/authz/userRole", getDF(UserRoleRequest.class), urr); + verb = "Added"; + participle = "] to User [" ; + break; + case 1: + fp = client.delete("/authz/userRole/" + urr.getUser() + '/' + urr.getRole(), Void.class); + verb = "Removed"; + participle = "] from User [" ; + break; + case 3: + fp = client.update("/authz/userRole/extend/" + urr.getUser() + '/' + urr.getRole()); + verb = "Extended"; + participle = "] to User [" ; + break; + default: + throw new CadiException("Invalid action [" + key + ']'); + } + if (fp.get(AAFcli.timeout())) { + pw().print(verb); + pw().print(" Role ["); + pw().print(urr.getRole()); + pw().print(participle); + pw().print(urr.getUser()); + pw().println(']'); + } else { + switch(fp.code()) { + case 202: + pw().print("UserRole "); + pw().print(option == 0 ? "Creation" : option==1?"Deletion":"Extension"); + pw().println(" Accepted, but requires Approvals before actualizing"); + break; + case 404: + if(option==3) { + pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); + break; + } + default: + error(fp); + } + } + } + } else { + // option 2 is setTo command (an update call) + String allRoles = ""; + if (idx < args.length) + allRoles = args[idx++]; - urr.setRole(allRoles); - fp = client.update("/authz/userRole/user", getDF(UserRoleRequest.class), urr); - if (fp.get(AAFcli.timeout())) { - pw().println("Set User's Roles to [" + allRoles + "]"); - } else { - error(fp); - } - } - return fp == null ? 0 : fp.code(); - } - }); - } + urr.setRole(allRoles); + fp = client.update("/authz/userRole/user", getDF(UserRoleRequest.class), urr); + if (fp.get(AAFcli.timeout())) { + pw().println("Set User's Roles to [" + allRoles + "]"); + } else { + error(fp); + } + } + return fp == null ? 0 : fp.code(); + } + }); + } - @Override - public void detailedHelp(int indent, StringBuilder sb) { - detailLine(sb, indent, "Add OR Delete a User to/from a Role OR"); - detailLine(sb, indent, "Set a User's Roles to the roles supplied"); - detailLine(sb, indent + 2, "user - ID of User"); - detailLine(sb, indent + 2, "role(s) - Role or Roles to which to add the User"); - sb.append('\n'); - detailLine(sb, indent + 2, "Note: this is the same as \"role user add...\" except allows"); - detailLine(sb, indent + 2, "assignment of user to multiple roles"); - detailLine(sb, indent + 2, "WARNING: Roles supplied with setTo will be the ONLY roles attached to this user"); - detailLine(sb, indent + 2, "If no roles are supplied, user's roles are reset."); - api(sb, indent, HttpMethods.POST, "authz/userRole", UserRoleRequest.class, true); - api(sb, indent, HttpMethods.DELETE, "authz/userRole//", Void.class, false); - api(sb, indent, HttpMethods.PUT, "authz/userRole/", UserRoleRequest.class, false); - } + @Override + public void detailedHelp(int indent, StringBuilder sb) { + detailLine(sb, indent, "Add OR Delete a User to/from a Role OR"); + detailLine(sb, indent, "Set a User's Roles to the roles supplied"); + detailLine(sb, indent + 2, "user - ID of User"); + detailLine(sb, indent + 2, "role(s) - Role or Roles to which to add the User"); + sb.append('\n'); + detailLine(sb, indent + 2, "Note: this is the same as \"role user add...\" except allows"); + detailLine(sb, indent + 2, "assignment of user to multiple roles"); + detailLine(sb, indent + 2, "WARNING: Roles supplied with setTo will be the ONLY roles attached to this user"); + detailLine(sb, indent + 2, "If no roles are supplied, user's roles are reset."); + api(sb, indent, HttpMethods.POST, "authz/userRole", UserRoleRequest.class, true); + api(sb, indent, HttpMethods.DELETE, "authz/userRole//", Void.class, false); + api(sb, indent, HttpMethods.PUT, "authz/userRole/", UserRoleRequest.class, false); + } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/User.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/User.java index 458fc33a..26e35bec 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/User.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/User.java @@ -26,11 +26,11 @@ import org.onap.aaf.auth.cmd.BaseCmd; import org.onap.aaf.misc.env.APIException; public class User extends BaseCmd { - public User(AAFcli aafcli) throws APIException { - super(aafcli,"user"); - cmds.add(new Role(this)); - cmds.add(new Cred(this)); - cmds.add(new Delg(this)); - cmds.add(new List(this)); - } + public User(AAFcli aafcli) throws APIException { + super(aafcli,"user"); + cmds.add(new Role(this)); + cmds.add(new Cred(this)); + cmds.add(new Delg(this)); + cmds.add(new List(this)); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/HMangrStub.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/HMangrStub.java index c1b87540..ddb39ea7 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/HMangrStub.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/HMangrStub.java @@ -33,26 +33,26 @@ import org.onap.aaf.cadi.client.Retryable; import org.onap.aaf.cadi.http.HMangr; public class HMangrStub extends HMangr { - - private Rcli clientMock; + + private Rcli clientMock; - public HMangrStub(Access access, Locator loc, Rcli clientMock) throws LocatorException { - super(access, loc); - this.clientMock = clientMock; - } + public HMangrStub(Access access, Locator loc, Rcli clientMock) throws LocatorException { + super(access, loc); + this.clientMock = clientMock; + } - @Override public RET same(SecuritySetter ss, Retryable retryable) { - try { - return retryable.code(clientMock); - } catch (Exception e) { - } - return null; - } - @Override public RET oneOf(SecuritySetter ss, Retryable retryable, boolean notify, String host) { - try { - return retryable.code(clientMock); - } catch (Exception e) { - } - return null; - } + @Override public RET same(SecuritySetter ss, Retryable retryable) { + try { + return retryable.code(clientMock); + } catch (Exception e) { + } + return null; + } + @Override public RET oneOf(SecuritySetter ss, Retryable retryable, boolean notify, String host) { + try { + return retryable.code(clientMock); + } catch (Exception e) { + } + return null; + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_AAFCli.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_AAFCli.java index d9da835d..9f439053 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_AAFCli.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_AAFCli.java @@ -52,209 +52,209 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_AAFCli { - private static AAFcli cli; - private static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); + private static AAFcli cli; + private static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); - @BeforeClass - public static void setUp() throws Exception, Exception { - cli = getAAfCli(); - } + @BeforeClass + public static void setUp() throws Exception, Exception { + cli = getAAfCli(); + } - @Test - public void eval() throws Exception { - assertTrue(cli.eval("#startswith")); - } + @Test + public void eval() throws Exception { + assertTrue(cli.eval("#startswith")); + } - @Test - public void eval_empty() throws Exception { - assertTrue(cli.eval("")); - } + @Test + public void eval_empty() throws Exception { + assertTrue(cli.eval("")); + } - @Test - public void eval1() throws Exception { - assertTrue(cli.eval("@[123")); - } + @Test + public void eval1() throws Exception { + assertTrue(cli.eval("@[123")); + } -// @Test -// public void eval2() throws Exception { -// assertFalse(cli.eval("as @[ 123")); -// } +// @Test +// public void eval2() throws Exception { +// assertFalse(cli.eval("as @[ 123")); +// } - @Test - public void eval3() throws Exception { - try { - cli.eval("expect @[ 123"); - } catch (Exception e) { - // TODO Auto-generated catch block - assertTrue(e instanceof CadiException); - } - } + @Test + public void eval3() throws Exception { + try { + cli.eval("expect @[ 123"); + } catch (Exception e) { + // TODO Auto-generated catch block + assertTrue(e instanceof CadiException); + } + } - public void eval31() throws Exception { - try { - cli.eval("expect 1 @[ 123"); - } catch (Exception e) { - // TODO Auto-generated catch block - assertTrue(e instanceof CadiException); - } - } + public void eval31() throws Exception { + try { + cli.eval("expect 1 @[ 123"); + } catch (Exception e) { + // TODO Auto-generated catch block + assertTrue(e instanceof CadiException); + } + } - @Test - public void eval4() throws Exception { - try { - cli.eval("sleep @[ 123"); - } catch (Exception e) { - assertTrue(e instanceof NumberFormatException); - } - } + @Test + public void eval4() throws Exception { + try { + cli.eval("sleep @[ 123"); + } catch (Exception e) { + assertTrue(e instanceof NumberFormatException); + } + } - @Test - public void eval41() throws Exception { - assertTrue(cli.eval("sleep 1 @[ 123")); - } + @Test + public void eval41() throws Exception { + assertTrue(cli.eval("sleep 1 @[ 123")); + } - @Test - public void eval5() throws Exception { - try { - cli.eval("delay @[ 123"); - } catch (Exception e) { - assertTrue(e instanceof NumberFormatException); - } - } + @Test + public void eval5() throws Exception { + try { + cli.eval("delay @[ 123"); + } catch (Exception e) { + assertTrue(e instanceof NumberFormatException); + } + } - @Test - public void eval51() throws Exception { - assertTrue(cli.eval("delay 1 @[ 123")); - } + @Test + public void eval51() throws Exception { + assertTrue(cli.eval("delay 1 @[ 123")); + } - @Test - public void eval7() throws Exception { - assertFalse(cli.eval("exit @[ 123")); - } + @Test + public void eval7() throws Exception { + assertFalse(cli.eval("exit @[ 123")); + } - @Test - public void eval8() throws Exception { - assertTrue(cli.eval("REQUEST @[ 123")); - } + @Test + public void eval8() throws Exception { + assertTrue(cli.eval("REQUEST @[ 123")); + } - @Test - public void eval9() throws Exception { - assertTrue(cli.eval("FORCE @[ 123")); - } + @Test + public void eval9() throws Exception { + assertTrue(cli.eval("FORCE @[ 123")); + } - @Test - public void eval10() throws Exception { - assertTrue(cli.eval("set @[ 123")); - } - - @Test - public void eval11() throws Exception { - assertTrue(cli.eval("DETAILS @[ 123")); - } - - @Test - public void eval12() throws Exception { - assertTrue(cli.eval(". |/, .\"0 \" ")); - } + @Test + public void eval10() throws Exception { + assertTrue(cli.eval("set @[ 123")); + } + + @Test + public void eval11() throws Exception { + assertTrue(cli.eval("DETAILS @[ 123")); + } + + @Test + public void eval12() throws Exception { + assertTrue(cli.eval(". |/, .\"0 \" ")); + } - @Test - public void keyboardHelp() throws Exception { - boolean noError=true; - try { - cli.keyboardHelp(); - } catch (Exception e) { - noError=false; - } - assertTrue(noError); - } + @Test + public void keyboardHelp() throws Exception { + boolean noError=true; + try { + cli.keyboardHelp(); + } catch (Exception e) { + noError=false; + } + assertTrue(noError); + } - @Test - public void setProp() throws Exception { - boolean noError=true; - try { - cli.keyboardHelp(); - } catch (Exception e) { - noError=false; - } - assertTrue(noError); - } - - @Test - public void eval_randomString() throws Exception { - assertTrue(cli.eval("Some random string @#&*& to check complete 100 coverage")); - } + @Test + public void setProp() throws Exception { + boolean noError=true; + try { + cli.keyboardHelp(); + } catch (Exception e) { + noError=false; + } + assertTrue(noError); + } + + @Test + public void eval_randomString() throws Exception { + assertTrue(cli.eval("Some random string @#&*& to check complete 100 coverage")); + } - public static AAFcli getAAfCli() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { - final AuthzEnv env = new AuthzEnv(System.getProperties()); - String aafUrl = "https://DME2RESOLVE"; - SecurityInfoC si = mock(SecurityInfoC.class); - env.loadToSystemPropsStartsWith("AAF", "DME2"); - Locator loc; - loc = new PropertyLocator(aafUrl); - TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); - HMangr hman = new HMangr(env, loc).readTimeout(TIMEOUT).apiVersion("2.0"); + public static AAFcli getAAfCli() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { + final AuthzEnv env = new AuthzEnv(System.getProperties()); + String aafUrl = "https://DME2RESOLVE"; + SecurityInfoC si = mock(SecurityInfoC.class); + env.loadToSystemPropsStartsWith("AAF", "DME2"); + Locator loc; + loc = new PropertyLocator(aafUrl); + TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); + HMangr hman = new HMangr(env, loc).readTimeout(TIMEOUT).apiVersion("2.0"); - // TODO: Consider requiring a default in properties - env.setProperty(Config.AAF_DEFAULT_REALM, - System.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm())); - - HBasicAuthSS ss = mock(HBasicAuthSS.class); - env.setProperty(Config.AAF_APPPASS, "test"); - return new AAFcli(env, new OutputStreamWriter(System.out), hman, si, ss); - } - - @Test - public void testVerbose() { - cli.verbose(true); - cli.verbose(false); - } - - @Test - public void testClose() { - cli.close(); - } - - @Test - public void testTimeout() { - Assert.assertNotNull(cli.timeout()); - } - - @Test - public void testTest() { - Assert.assertNotNull(cli.isTest()); - } - - @Test - public void testIsDetailed() { - Assert.assertNotNull(cli.isDetailed()); - } - - @Test - public void testAddRequest() { - Assert.assertNotNull(cli.addRequest()); - } - - @Test - public void testForceString() { - cli.clearSingleLineProperties(); - Assert.assertNull(cli.forceString()); - } - - @Test - public void testClearSingleLineProperties() { - cli.clearSingleLineProperties(); - } - - @Test - public void testGui() { - cli.gui(true); - cli.gui(false); - } - - @Test - public void testMain() { - String[] strArr = {"\\*","test1"}; - //cli.main(strArr); - } - + // TODO: Consider requiring a default in properties + env.setProperty(Config.AAF_DEFAULT_REALM, + System.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm())); + + HBasicAuthSS ss = mock(HBasicAuthSS.class); + env.setProperty(Config.AAF_APPPASS, "test"); + return new AAFcli(env, new OutputStreamWriter(System.out), hman, si, ss); + } + + @Test + public void testVerbose() { + cli.verbose(true); + cli.verbose(false); + } + + @Test + public void testClose() { + cli.close(); + } + + @Test + public void testTimeout() { + Assert.assertNotNull(cli.timeout()); + } + + @Test + public void testTest() { + Assert.assertNotNull(cli.isTest()); + } + + @Test + public void testIsDetailed() { + Assert.assertNotNull(cli.isDetailed()); + } + + @Test + public void testAddRequest() { + Assert.assertNotNull(cli.addRequest()); + } + + @Test + public void testForceString() { + cli.clearSingleLineProperties(); + Assert.assertNull(cli.forceString()); + } + + @Test + public void testClearSingleLineProperties() { + cli.clearSingleLineProperties(); + } + + @Test + public void testGui() { + cli.gui(true); + cli.gui(false); + } + + @Test + public void testMain() { + String[] strArr = {"\\*","test1"}; + //cli.main(strArr); + } + } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BaseCmd.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BaseCmd.java index 79a3dd53..211ec7d0 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BaseCmd.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BaseCmd.java @@ -50,71 +50,71 @@ import aaf.v2_0.History; @RunWith(MockitoJUnitRunner.class) public class JU_BaseCmd { - private static AAFcli cli; - private static BaseCmd bCmd; - - @BeforeClass - public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { - cli = JU_AAFCli.getAAfCli(); - bCmd = new BaseCmd<>(cli, "testString"); - } - - @Test - public void exec() throws CadiException, APIException, LocatorException { - assertEquals(bCmd._exec(4, "add", "del", "reset", "extend"), 0); - - } - - @Test - public void exec1() throws CadiException, APIException, LocatorException { - assertEquals(bCmd._exec(0, "add", "del", "reset", "extend"), 0); - - } - - @Test - public void activity() throws DatatypeConfigurationException { - boolean noError = true; - History history = new History(); - History.Item item = new History.Item(); - item.setTarget("target"); - item.setUser("user"); - item.setMemo("memo"); - - GregorianCalendar c = new GregorianCalendar(); - c.setTime(new Date()); - XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); - item.setTimestamp(date); - history.getItem().add(item); - try { - bCmd.activity(history, "history"); - } catch (Exception e) { - noError = false; - } - assertEquals(noError, true); - - } - - @Test - public void activity1() throws DatatypeConfigurationException { - boolean noError = true; - History history = new History(); - History.Item item = new History.Item(); - item.setTarget("target"); - item.setUser("user"); - item.setMemo("memo"); - - GregorianCalendar c = new GregorianCalendar(); - c.setTime(new Date()); - XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); - item.setTimestamp(date); - history.getItem().add(item); - try { - bCmd.activity(history, "1[]"); - } catch (Exception e) { - noError = false; - } - assertEquals(noError, true); - - } + private static AAFcli cli; + private static BaseCmd bCmd; + + @BeforeClass + public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { + cli = JU_AAFCli.getAAfCli(); + bCmd = new BaseCmd<>(cli, "testString"); + } + + @Test + public void exec() throws CadiException, APIException, LocatorException { + assertEquals(bCmd._exec(4, "add", "del", "reset", "extend"), 0); + + } + + @Test + public void exec1() throws CadiException, APIException, LocatorException { + assertEquals(bCmd._exec(0, "add", "del", "reset", "extend"), 0); + + } + + @Test + public void activity() throws DatatypeConfigurationException { + boolean noError = true; + History history = new History(); + History.Item item = new History.Item(); + item.setTarget("target"); + item.setUser("user"); + item.setMemo("memo"); + + GregorianCalendar c = new GregorianCalendar(); + c.setTime(new Date()); + XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); + item.setTimestamp(date); + history.getItem().add(item); + try { + bCmd.activity(history, "history"); + } catch (Exception e) { + noError = false; + } + assertEquals(noError, true); + + } + + @Test + public void activity1() throws DatatypeConfigurationException { + boolean noError = true; + History history = new History(); + History.Item item = new History.Item(); + item.setTarget("target"); + item.setUser("user"); + item.setMemo("memo"); + + GregorianCalendar c = new GregorianCalendar(); + c.setTime(new Date()); + XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); + item.setTimestamp(date); + history.getItem().add(item); + try { + bCmd.activity(history, "1[]"); + } catch (Exception e) { + noError = false; + } + assertEquals(noError, true); + + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BasicAuth.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BasicAuth.java index 7cc5cede..d035ac59 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BasicAuth.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_BasicAuth.java @@ -35,22 +35,22 @@ import junit.framework.Assert; //TODO: Gabe [JUnit] Import missing @RunWith(MockitoJUnitRunner.class) public class JU_BasicAuth { - -// @Test -// public void getID () { -// try { -// BasicAuth bAuth = new BasicAuth("testUser", "nopass"); -// assertEquals(bAuth.getID(), "testUser"); -// System.out.println(bAuth.getID()); -// } catch (IOException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// -// } - - @Test - public void netYetTested() { - Assert.assertTrue(true); - } + +// @Test +// public void getID () { +// try { +// BasicAuth bAuth = new BasicAuth("testUser", "nopass"); +// assertEquals(bAuth.getID(), "testUser"); +// System.out.println(bAuth.getID()); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// +// } + + @Test + public void netYetTested() { + Assert.assertTrue(true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Cmd.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Cmd.java index 3566555d..8adeeee3 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Cmd.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Cmd.java @@ -62,130 +62,130 @@ import org.junit.Test; public class JU_Cmd { - CmdStub cmd; - CmdStub cmd1; - CmdStub cmd2; - AAFcli cli; - - private class CmdStub extends Cmd { + CmdStub cmd; + CmdStub cmd1; + CmdStub cmd2; + AAFcli cli; + + private class CmdStub extends Cmd { - public CmdStub(AAFcli aafcli, String name, Param[] params) { - super(aafcli, name, params); - // TODO Auto-generated constructor stub - } - - public CmdStub(Cmd parent, String name, Param[] params) { - super(parent, name, params); - // TODO Auto-generated constructor stub - } + public CmdStub(AAFcli aafcli, String name, Param[] params) { + super(aafcli, name, params); + // TODO Auto-generated constructor stub + } + + public CmdStub(Cmd parent, String name, Param[] params) { + super(parent, name, params); + // TODO Auto-generated constructor stub + } - @Override - protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void error(Future future) { - super.error(future); - } + @Override + protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void error(Future future) { + super.error(future); + } - } - - @Before - public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { - cli = JU_AAFCli.getAAfCli(); - Param[] param = new Param[] {new Param("name",true)}; - - cmd = new CmdStub(cli,"test", param); - cmd1 = new CmdStub(cmd,"test", param); - cmd2 = new CmdStub(cmd,"test", param); - } - - @Test - public void testReportColHead() { - String[] args = new String[] {new String("test")}; - cmd.reportColHead("format", args); - } - - @Test - public void testBuilder() { - StringBuilder detail = new StringBuilder(); - StringBuilder sb = new StringBuilder("test 123"); - - cmd.build(sb, detail); - detail.append("test"); - cmd.build(sb, detail); - } - - @Test - public void testApi() throws APIException, CadiException { - StringBuilder sb = new StringBuilder("test 123"); - Define def = new Define(); - PropAccess prop = new PropAccess(); - def.set(prop); - Mgmt mgmt = new Mgmt(cli); - Cache cache = new Cache(mgmt); - Clear clr = new Clear(cache); - clr.detailedHelp(0, sb); - } - - @Test - public void testToString() { - cmd.toString(); - } - - @Test - public void testFullID() { - cmd.fullID("test"); - cmd.fullID("t@st"); - cmd.fullID(null); - } - - @Test - public void testError() { - Future future = mock(Future.class); - cmd.error(future); - when(future.code()).thenReturn(401); - cmd.error(future); - when(future.code()).thenReturn(403); - cmd.error(future); - when(future.code()).thenReturn(404); - cmd.error(future); - when(future.body()).thenReturn("NotNull"); - cmd.error(future); - when(future.body()).thenReturn("{NotNull"); - cmd.error(future); - when(future.body()).thenReturn("NotNull"); - cmd.error(future); - } - - @Test - public void testActivity() { - History hist = new History(); - cmd.activity(hist, "test"); - cmd.activity(hist, "te[st"); - } - - @Test - public void testWhichOption() throws CadiException { - String[] strArr = {"a", "b", "c"}; - cmd.whichOption(strArr, "b"); - } - - @Test - public void testOneOf() throws APIException, CadiException, LocatorException { - Retryable retryable = mock(Retryable.class); - //cmd.oneOf(retryable, "host"); //TODO: AAF-111 need input for hMan - } - - @Test - public void testExec() throws CadiException, APIException, LocatorException { - String[] strArr = {"a", "b", "c"}; - cmd.exec(1, strArr); - } - - + } + + @Before + public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { + cli = JU_AAFCli.getAAfCli(); + Param[] param = new Param[] {new Param("name",true)}; + + cmd = new CmdStub(cli,"test", param); + cmd1 = new CmdStub(cmd,"test", param); + cmd2 = new CmdStub(cmd,"test", param); + } + + @Test + public void testReportColHead() { + String[] args = new String[] {new String("test")}; + cmd.reportColHead("format", args); + } + + @Test + public void testBuilder() { + StringBuilder detail = new StringBuilder(); + StringBuilder sb = new StringBuilder("test 123"); + + cmd.build(sb, detail); + detail.append("test"); + cmd.build(sb, detail); + } + + @Test + public void testApi() throws APIException, CadiException { + StringBuilder sb = new StringBuilder("test 123"); + Define def = new Define(); + PropAccess prop = new PropAccess(); + def.set(prop); + Mgmt mgmt = new Mgmt(cli); + Cache cache = new Cache(mgmt); + Clear clr = new Clear(cache); + clr.detailedHelp(0, sb); + } + + @Test + public void testToString() { + cmd.toString(); + } + + @Test + public void testFullID() { + cmd.fullID("test"); + cmd.fullID("t@st"); + cmd.fullID(null); + } + + @Test + public void testError() { + Future future = mock(Future.class); + cmd.error(future); + when(future.code()).thenReturn(401); + cmd.error(future); + when(future.code()).thenReturn(403); + cmd.error(future); + when(future.code()).thenReturn(404); + cmd.error(future); + when(future.body()).thenReturn("NotNull"); + cmd.error(future); + when(future.body()).thenReturn("{NotNull"); + cmd.error(future); + when(future.body()).thenReturn("NotNull"); + cmd.error(future); + } + + @Test + public void testActivity() { + History hist = new History(); + cmd.activity(hist, "test"); + cmd.activity(hist, "te[st"); + } + + @Test + public void testWhichOption() throws CadiException { + String[] strArr = {"a", "b", "c"}; + cmd.whichOption(strArr, "b"); + } + + @Test + public void testOneOf() throws APIException, CadiException, LocatorException { + Retryable retryable = mock(Retryable.class); + //cmd.oneOf(retryable, "host"); //TODO: AAF-111 need input for hMan + } + + @Test + public void testExec() throws CadiException, APIException, LocatorException { + String[] strArr = {"a", "b", "c"}; + cmd.exec(1, strArr); + } + + } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_DeprecatedCMD.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_DeprecatedCMD.java index 02a9e26f..32697473 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_DeprecatedCMD.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_DeprecatedCMD.java @@ -47,32 +47,32 @@ import org.junit.Test; public class JU_DeprecatedCMD { - CmdStub cmd; - AAFcli cli; - - private class CmdStub extends Cmd { + CmdStub cmd; + AAFcli cli; + + private class CmdStub extends Cmd { - public CmdStub(AAFcli aafcli, String name, Param[] params) { - super(aafcli, name, params); - // TODO Auto-generated constructor stub - } + public CmdStub(AAFcli aafcli, String name, Param[] params) { + super(aafcli, name, params); + // TODO Auto-generated constructor stub + } - @Override - protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { - // TODO Auto-generated method stub - return 0; - } - - } - - @Test - public void testExec() throws CadiException, APIException, LocatorException, GeneralSecurityException, IOException { - cli = JU_AAFCli.getAAfCli(); - Param[] param = new Param[] {new Param("name",true)}; - - cmd = new CmdStub(cli,"test", param); - DeprecatedCMD deprecatedcmd = new DeprecatedCMD(cmd,"test", "test"); - deprecatedcmd._exec(0, "test"); - } + @Override + protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { + // TODO Auto-generated method stub + return 0; + } + + } + + @Test + public void testExec() throws CadiException, APIException, LocatorException, GeneralSecurityException, IOException { + cli = JU_AAFCli.getAAfCli(); + Param[] param = new Param[] {new Param("name",true)}; + + cmd = new CmdStub(cli,"test", param); + DeprecatedCMD deprecatedcmd = new DeprecatedCMD(cmd,"test", "test"); + deprecatedcmd._exec(0, "test"); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Help.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Help.java index 50da3e37..9599e803 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Help.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Help.java @@ -50,79 +50,79 @@ import junit.framework.Assert; @RunWith(MockitoJUnitRunner.class) public class JU_Help { - - private static AAFcli cli; - private static Help help; - String[] strArr = {"null","null","b","c"}; - private class CmdStub extends Cmd { + + private static AAFcli cli; + private static Help help; + String[] strArr = {"null","null","b","c"}; + private class CmdStub extends Cmd { - public CmdStub(AAFcli aafcli, String name, Param[] params) { - super(aafcli, name, params); - // TODO Auto-generated constructor stub - } - - public CmdStub(Cmd parent, String name, Param[] params) { - super(parent, name, params); - // TODO Auto-generated constructor stub - } + public CmdStub(AAFcli aafcli, String name, Param[] params) { + super(aafcli, name, params); + // TODO Auto-generated constructor stub + } + + public CmdStub(Cmd parent, String name, Param[] params) { + super(parent, name, params); + // TODO Auto-generated constructor stub + } - @Override - protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void error(Future future) { - super.error(future); - } - - } - - @Mock - private static List cmds; - - @Before - public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { - cli = JU_AAFCli.getAAfCli(); - cmds = new ArrayList<>(); - Param[] param = new Param[] {new Param("name",true)}; - CmdStub cmd = new CmdStub(cli, "null", param); - cmds.add(cmd); - help = new Help(cli, cmds); - } - - @Test - public void exec_HTTP_200() { - try { - assertEquals(help._exec(1, "helps"), HttpStatus.OK_200); - assertEquals(help._exec(1, strArr), HttpStatus.OK_200); - } catch (CadiException | APIException | LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void exec_HTTP_200_1() { - try { - assertEquals(help._exec(1, "helps","help"), HttpStatus.OK_200); - } catch (CadiException | APIException | LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void detailhelp() { - boolean hasError=false; - try { - help.detailedHelp(2, new StringBuilder("detail help test")); - } catch (Exception e) { - hasError=true; - } - assertEquals(hasError,false); - } + @Override + protected int _exec(int idx, String... args) throws CadiException, APIException, LocatorException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void error(Future future) { + super.error(future); + } + + } + + @Mock + private static List cmds; + + @Before + public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { + cli = JU_AAFCli.getAAfCli(); + cmds = new ArrayList<>(); + Param[] param = new Param[] {new Param("name",true)}; + CmdStub cmd = new CmdStub(cli, "null", param); + cmds.add(cmd); + help = new Help(cli, cmds); + } + + @Test + public void exec_HTTP_200() { + try { + assertEquals(help._exec(1, "helps"), HttpStatus.OK_200); + assertEquals(help._exec(1, strArr), HttpStatus.OK_200); + } catch (CadiException | APIException | LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void exec_HTTP_200_1() { + try { + assertEquals(help._exec(1, "helps","help"), HttpStatus.OK_200); + } catch (CadiException | APIException | LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void detailhelp() { + boolean hasError=false; + try { + help.detailedHelp(2, new StringBuilder("detail help test")); + } catch (Exception e) { + hasError=true; + } + assertEquals(hasError,false); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Version.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Version.java index c0ac0f21..112fc92c 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Version.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/JU_Version.java @@ -45,24 +45,24 @@ import junit.framework.Assert; //TODO: Gabe [JUnit] Import missing @RunWith(MockitoJUnitRunner.class) public class JU_Version { - - private static AAFcli cli; - private static Version version; - - @BeforeClass - public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { - cli = JU_AAFCli.getAAfCli(); - version = new Version(cli); - } - -// @Test -// public void exec_HTTP_200() throws CadiException, APIException, LocatorException { -// assertEquals(version._exec(0, "Version"), HttpStatus.OK_200); + + private static AAFcli cli; + private static Version version; + + @BeforeClass + public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { + cli = JU_AAFCli.getAAfCli(); + version = new Version(cli); + } + +// @Test +// public void exec_HTTP_200() throws CadiException, APIException, LocatorException { +// assertEquals(version._exec(0, "Version"), HttpStatus.OK_200); // -// } - - @Test //TODO: Temporary fix AAF-111 - public void netYetTested() { - Assert.assertTrue(true); - } +// } + + @Test //TODO: Temporary fix AAF-111 + public void netYetTested() { + Assert.assertTrue(true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Clear.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Clear.java index 43d228d6..102e8fcd 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Clear.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Clear.java @@ -58,51 +58,51 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Clear { - - private static Clear clr; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - Cache cache; - Mgmt mgmt; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); -// hman = new HMangr(aEnv, loc); -// aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); -// mgmt = new Mgmt(aafcli); -// cache = new Cache(mgmt); -// clr = new Clear(cache); - - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - when(loc.first()).thenReturn(value); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, value, secSet); -// String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"}; - //clr._exec(0, strArr); + + private static Clear clr; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + Cache cache; + Mgmt mgmt; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); +// hman = new HMangr(aEnv, loc); +// aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); +// mgmt = new Mgmt(aafcli); +// cache = new Cache(mgmt); +// clr = new Clear(cache); + + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + when(loc.first()).thenReturn(value); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, value, secSet); +// String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"}; + //clr._exec(0, strArr); - } - - @Test - public void testDetailedHelp() throws CadiException { - Define define = new Define(); - define.set(prop); - StringBuilder sb = new StringBuilder(); -// clr.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() throws CadiException { + Define define = new Define(); + define.set(prop); + StringBuilder sb = new StringBuilder(); +// clr.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Deny.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Deny.java index 7e888a7c..5b372881 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Deny.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Deny.java @@ -59,50 +59,50 @@ import java.net.URISyntaxException; import org.junit.Test; public class JU_Deny { - - Deny deny; - DenySomething denyS; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; + + Deny deny; + DenySomething denyS; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; - @Before - public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); -// hman = new HMangr(aEnv, loc); -// aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); -// Mgmt mgmt = new Mgmt(aafcli); -// deny = new Deny(mgmt); - //denyS = deny.new DenySomething(deny,"ip","ipv4or6[,ipv4or6]*"); + @Before + public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); +// hman = new HMangr(aEnv, loc); +// aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); +// Mgmt mgmt = new Mgmt(aafcli); +// deny = new Deny(mgmt); + //denyS = deny.new DenySomething(deny,"ip","ipv4or6[,ipv4or6]*"); - } - - + } + + - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add","del", "add","del"}; -// deny._exec(0, strArr); -// -// String[] strArr1 = {"del", "add","del"}; -// deny._exec(0, strArr1); - - } +// String[] strArr = {"add","del", "add","del"}; +// deny._exec(0, strArr); +// +// String[] strArr1 = {"del", "add","del"}; +// deny._exec(0, strArr1); + + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Log.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Log.java index 6e6f06ed..6b227f38 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Log.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_Log.java @@ -55,53 +55,53 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Log { - - private static Log log; - private static Log log1; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp() throws APIException, LocatorException, CadiException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Mgmt mgmt = new Mgmt(aafcli); - log1 = new Log(mgmt); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// when(loc.first()).thenReturn(value); -// String[] strArr = {"add","upd","del","add","upd","del"}; -// log1._exec(0, strArr); + + private static Log log; + private static Log log1; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp() throws APIException, LocatorException, CadiException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Mgmt mgmt = new Mgmt(aafcli); + log1 = new Log(mgmt); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// when(loc.first()).thenReturn(value); +// String[] strArr = {"add","upd","del","add","upd","del"}; +// log1._exec(0, strArr); // -// String[] strArr1 = {"del","add","upd","del"}; -// log1._exec(0, strArr1); +// String[] strArr1 = {"del","add","upd","del"}; +// log1._exec(0, strArr1); - } - - @Test - public void testDetailedHelp() throws CadiException { - Define define = new Define(); - define.set(prop); - StringBuilder sb = new StringBuilder(); - log1.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() throws CadiException { + Define define = new Define(); + define.set(prop); + StringBuilder sb = new StringBuilder(); + log1.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_SessClear.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_SessClear.java index f55bf2f9..f1f4d9a9 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_SessClear.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/mgmt/JU_SessClear.java @@ -56,50 +56,50 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_SessClear { - - private static SessClear sessclr; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp() throws LocatorException, APIException, CadiException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); -// hman = new HMangr(aEnv, loc); -// aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); -// Mgmt mgmt = new Mgmt(aafcli); -// Session sess = new Session(mgmt); -// sessclr = new SessClear(sess); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// when(loc.first()).thenReturn(value); -// String[] strArr = {"add","upd","del","add","upd","del"}; - //sessclr._exec(0, strArr); + + private static SessClear sessclr; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp() throws LocatorException, APIException, CadiException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); +// hman = new HMangr(aEnv, loc); +// aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); +// Mgmt mgmt = new Mgmt(aafcli); +// Session sess = new Session(mgmt); +// sessclr = new SessClear(sess); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// when(loc.first()).thenReturn(value); +// String[] strArr = {"add","upd","del","add","upd","del"}; + //sessclr._exec(0, strArr); - } - - @Test - public void testDetailedHelp() throws CadiException { - Define define = new Define(); - define.set(prop); - StringBuilder sb = new StringBuilder(); -// sessclr.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() throws CadiException { + Define define = new Define(); + define.set(prop); + StringBuilder sb = new StringBuilder(); +// sessclr.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Admin.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Admin.java index 35dead11..ef4383fe 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Admin.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Admin.java @@ -56,57 +56,57 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Admin { - private static Admin admin; - - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - + private static Admin admin; + + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + - @Before - public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - admin = new Admin(ns); - - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add", "del","add","add"}; -// admin._exec(0, strArr); -// -// String[] strArr1 = {"del","add","add"}; -// admin._exec(0, strArr1); - - } + @Before + public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + admin = new Admin(ns); + + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add", "del","add","add"}; +// admin._exec(0, strArr); +// +// String[] strArr1 = {"del","add","add"}; +// admin._exec(0, strArr1); + + } - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - admin.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + admin.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Attrib.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Attrib.java index 181b4526..0f14d8ea 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Attrib.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Attrib.java @@ -61,57 +61,57 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Attrib { - private static Attrib attrib; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; + private static Attrib attrib; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; - @Before - public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - attrib = new Attrib(ns); - } + @Before + public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + attrib = new Attrib(ns); + } - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add","upd","del","add","upd","del"}; -// attrib._exec(0, strArr); -// -// String[] strArr1 = {"upd","del","add","upd","del","add"}; -// attrib._exec(0, strArr1); -// -// String[] strArr2 = {"del","add","upd","del","add","upd"}; -// attrib._exec(0, strArr2); - - } + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add","upd","del","add","upd","del"}; +// attrib._exec(0, strArr); +// +// String[] strArr1 = {"upd","del","add","upd","del","add"}; +// attrib._exec(0, strArr1); +// +// String[] strArr2 = {"del","add","upd","del","add","upd"}; +// attrib._exec(0, strArr2); + + } - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - attrib.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + attrib.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Create.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Create.java index bc590695..83417138 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Create.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Create.java @@ -51,52 +51,52 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Create { - private static Create create;//might need to replace import with org.onap.aaf.auth.cmd.perm - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - create = new Create(ns); - } - - + private static Create create;//might need to replace import with org.onap.aaf.auth.cmd.perm + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + create = new Create(ns); + } + + - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del","add","upd","del"}; - create._exec(0, strArr); - - } + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del","add","upd","del"}; + create._exec(0, strArr); + + } - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - create.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + create.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Delete.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Delete.java index ee877a4b..8d4c739d 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Delete.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Delete.java @@ -49,52 +49,52 @@ import org.onap.aaf.misc.env.APIException; public class JU_Delete { - private static Delete delete;//import may be org.onap.aaf.auth.cmd.perm - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - delete = new Delete(ns); + private static Delete delete;//import may be org.onap.aaf.auth.cmd.perm + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + delete = new Delete(ns); - } + } - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add","upd","del","add","upd","del"}; -// delete._exec(0, strArr); - - } + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add","upd","del","add","upd","del"}; +// delete._exec(0, strArr); + + } - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - delete.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + delete.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Describe.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Describe.java index c0efec00..862c1158 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Describe.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Describe.java @@ -48,47 +48,47 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Describe { - - private static Describe desc; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - desc = new Describe(ns); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add","upd","del","add","upd","del"}; -// desc._exec(0, strArr); - - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - desc.detailedHelp(0, sb ); - } + + private static Describe desc; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + desc = new Describe(ns); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add","upd","del","add","upd","del"}; +// desc._exec(0, strArr); + + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + desc.detailedHelp(0, sb ); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_List.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_List.java index a6d2130f..78add994 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_List.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_List.java @@ -53,91 +53,91 @@ import static org.mockito.Mockito.*; import org.junit.Test; public class JU_List { - - List list; - AAFcli aafcli; - User user; - - private class NssStub extends Nss { - public void addNs(Nss.Ns ns) { - if (this.ns == null) { - this.ns = new ArrayList<>(); - } - this.ns.add(ns); - } - - private class NsStub extends Ns{ - public void addAttrib(Nss.Ns.Attrib attrib) { - if ( this.attrib == null) { - this.attrib = new ArrayList<>(); - } - this.attrib.add(attrib); - } - - public void addResponsible(String str) { - if (this.responsible == null) { - this.responsible = new ArrayList<>(); - } - this.responsible.add(str); - } - - public void addAdmin(String str) { - if (this.admin == null) { - this.admin = new ArrayList<>(); - } - this.admin.add(str); - } - } - - - - - } - + + List list; + AAFcli aafcli; + User user; + + private class NssStub extends Nss { + public void addNs(Nss.Ns ns) { + if (this.ns == null) { + this.ns = new ArrayList<>(); + } + this.ns.add(ns); + } + + private class NsStub extends Ns{ + public void addAttrib(Nss.Ns.Attrib attrib) { + if ( this.attrib == null) { + this.attrib = new ArrayList<>(); + } + this.attrib.add(attrib); + } + + public void addResponsible(String str) { + if (this.responsible == null) { + this.responsible = new ArrayList<>(); + } + this.responsible.add(str); + } + + public void addAdmin(String str) { + if (this.admin == null) { + this.admin = new ArrayList<>(); + } + this.admin.add(str); + } + } + + + + + } + - @Before - public void setUp() throws APIException, LocatorException, CadiException { - PropAccess prop = new PropAccess(); - AuthzEnv aEnv = new AuthzEnv(); - Writer wtr = mock(Writer.class); - Locator loc = mock(Locator.class); - HMangr hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, null); - user = new User(); - NS ns = new NS(aafcli); - - list = new List(ns); - } - - @Test - public void testReport() throws Exception { - Future fu = mock(Future.class); - NssStub nssStub = new NssStub(); - NssStub.NsStub nsStub = nssStub.new NsStub(); - Nss.Ns.Attrib attrib = mock(Nss.Ns.Attrib.class); - when(attrib.getKey()).thenReturn("key"); - when(attrib.getValue()).thenReturn("value"); - nsStub.addAttrib(attrib); - nsStub.addResponsible("test"); - nsStub.addAdmin("admin"); - nssStub.addNs(nsStub); - fu.value = nssStub; - aafcli.eval("DETAILS @[ 123"); - - list.report(fu, "test"); - } - - @Test - public void testGetType() { - Assert.assertEquals("n/a", list.getType(user)); - user.setType(1); - Assert.assertEquals("U/P", list.getType(user)); - user.setType(2); - Assert.assertEquals("U/P2", list.getType(user)); - user.setType(10); - Assert.assertEquals("Cert", list.getType(user)); - user.setType(200); - Assert.assertEquals("x509", list.getType(user)); - } - + @Before + public void setUp() throws APIException, LocatorException, CadiException { + PropAccess prop = new PropAccess(); + AuthzEnv aEnv = new AuthzEnv(); + Writer wtr = mock(Writer.class); + Locator loc = mock(Locator.class); + HMangr hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, null); + user = new User(); + NS ns = new NS(aafcli); + + list = new List(ns); + } + + @Test + public void testReport() throws Exception { + Future fu = mock(Future.class); + NssStub nssStub = new NssStub(); + NssStub.NsStub nsStub = nssStub.new NsStub(); + Nss.Ns.Attrib attrib = mock(Nss.Ns.Attrib.class); + when(attrib.getKey()).thenReturn("key"); + when(attrib.getValue()).thenReturn("value"); + nsStub.addAttrib(attrib); + nsStub.addResponsible("test"); + nsStub.addAdmin("admin"); + nssStub.addNs(nsStub); + fu.value = nssStub; + aafcli.eval("DETAILS @[ 123"); + + list.report(fu, "test"); + } + + @Test + public void testGetType() { + Assert.assertEquals("n/a", list.getType(user)); + user.setType(1); + Assert.assertEquals("U/P", list.getType(user)); + user.setType(2); + Assert.assertEquals("U/P2", list.getType(user)); + user.setType(10); + Assert.assertEquals("Cert", list.getType(user)); + user.setType(200); + Assert.assertEquals("x509", list.getType(user)); + } + } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListActivity.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListActivity.java index bdebe0f9..298d4732 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListActivity.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListActivity.java @@ -57,49 +57,49 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListActivity { - - private static ListActivity lsActivity; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - List ls = new List(ns); - lsActivity = new ListActivity(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del","add","upd","del"}; - //lsActivity._exec(0, strArr); - - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsActivity.detailedHelp(0, sb ); - } + + private static ListActivity lsActivity; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + List ls = new List(ns); + lsActivity = new ListActivity(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del","add","upd","del"}; + //lsActivity._exec(0, strArr); + + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsActivity.detailedHelp(0, sb ); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListAdminResponsible.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListAdminResponsible.java index 0e146edb..7d7422fd 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListAdminResponsible.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListAdminResponsible.java @@ -56,48 +56,48 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListAdminResponsible { - - private static ListAdminResponsible lsAdminRes; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - List ls = new List(ns); - lsAdminRes = new ListAdminResponsible(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del","add","upd","del"}; - //lsAdminRes._exec(0, strArr); - - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsAdminRes.detailedHelp(0, sb ); - } + + private static ListAdminResponsible lsAdminRes; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + List ls = new List(ns); + lsAdminRes = new ListAdminResponsible(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del","add","upd","del"}; + //lsAdminRes._exec(0, strArr); + + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsAdminRes.detailedHelp(0, sb ); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListByName.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListByName.java index 48711dc9..c37237dc 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListByName.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListByName.java @@ -56,48 +56,48 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByName { - - private static ListByName lsByName; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - NS ns = new NS(aafcli); - List ls = new List(ns); - lsByName = new ListByName(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del","add","upd","del"}; - //lsByName._exec(0, strArr); - - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsByName.detailedHelp(0, sb ); - } + + private static ListByName lsByName; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + NS ns = new NS(aafcli); + List ls = new List(ns); + lsByName = new ListByName(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del","add","upd","del"}; + //lsByName._exec(0, strArr); + + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsByName.detailedHelp(0, sb ); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListChildren.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListChildren.java index 5723f19f..5b697de0 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListChildren.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListChildren.java @@ -41,37 +41,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListChildren { - - private static ListChildren lsChildren; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - NS ns = new NS(cli); - List ls = new List(ns); - lsChildren = new ListChildren(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsChildren._exec(0, "add","del","reset","extend"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsChildren.detailedHelp(0, sb ); - } + + private static ListChildren lsChildren; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + NS ns = new NS(cli); + List ls = new List(ns); + lsChildren = new ListChildren(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsChildren._exec(0, "add","del","reset","extend"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsChildren.detailedHelp(0, sb ); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListNsKeysByAttrib.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListNsKeysByAttrib.java index a1b0da19..6c8e61a5 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListNsKeysByAttrib.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListNsKeysByAttrib.java @@ -40,37 +40,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListNsKeysByAttrib { - - private static ListNsKeysByAttrib lsNsKeys; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - NS ns = new NS(cli); - List ls = new List(ns); - lsNsKeys = new ListNsKeysByAttrib(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsNsKeys._exec(0, "add","del","reset","extend"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsNsKeys.detailedHelp(0, sb ); - } + + private static ListNsKeysByAttrib lsNsKeys; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + NS ns = new NS(cli); + List ls = new List(ns); + lsNsKeys = new ListNsKeysByAttrib(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsNsKeys._exec(0, "add","del","reset","extend"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsNsKeys.detailedHelp(0, sb ); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsers.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsers.java index 909e852e..f400e16d 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsers.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsers.java @@ -52,29 +52,29 @@ import org.junit.Test; public class JU_ListUsers { - AAFcli cli; - NS ns; - List list; - ListUsers lUsers; - - @Before - public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { - cli = JU_AAFCli.getAAfCli(); - ns = new NS(cli); - list = new List(ns); - lUsers = new ListUsers(list); - } - - @Test - public void testReports() throws DatatypeConfigurationException { - Users.User user = new Users.User(); - GregorianCalendar gcal = new GregorianCalendar(); - XMLGregorianCalendar xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal); - user.setExpires(xgcal); - - lUsers.report("header", "ns"); - lUsers.report("subHead"); - lUsers.report("prefix", user); - } + AAFcli cli; + NS ns; + List list; + ListUsers lUsers; + + @Before + public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException { + cli = JU_AAFCli.getAAfCli(); + ns = new NS(cli); + list = new List(ns); + lUsers = new ListUsers(list); + } + + @Test + public void testReports() throws DatatypeConfigurationException { + Users.User user = new Users.User(); + GregorianCalendar gcal = new GregorianCalendar(); + XMLGregorianCalendar xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal); + user.setExpires(xgcal); + + lUsers.report("header", "ns"); + lUsers.report("subHead"); + lUsers.report("prefix", user); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersContact.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersContact.java index 536d70fa..e0029791 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersContact.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersContact.java @@ -55,51 +55,51 @@ import org.junit.Test; public class JU_ListUsersContact { - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - NS ns; - List list; - ListUsers lUsers; - ListUsersContact lUContact; - - @Before - public void setUp() throws LocatorException, APIException, CadiException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - ns = new NS(aafcli); - list = new List(ns); - lUsers = new ListUsers(list); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - lUContact = new ListUsersContact(lUsers); - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - //lUContact._exec(0, "test"); - - } - - @Test - public void testDetailedHelp() { - lUContact = new ListUsersContact(lUsers); - StringBuilder sb = new StringBuilder(); - lUContact.detailedHelp(0, sb); - } + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + NS ns; + List list; + ListUsers lUsers; + ListUsersContact lUContact; + + @Before + public void setUp() throws LocatorException, APIException, CadiException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + ns = new NS(aafcli); + list = new List(ns); + lUsers = new ListUsers(list); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + lUContact = new ListUsersContact(lUsers); + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + //lUContact._exec(0, "test"); + + } + + @Test + public void testDetailedHelp() { + lUContact = new ListUsersContact(lUsers); + StringBuilder sb = new StringBuilder(); + lUContact.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersInRole.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersInRole.java index 9f61b009..8d4cf593 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersInRole.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersInRole.java @@ -39,35 +39,35 @@ import org.onap.aaf.auth.cmd.test.JU_AAFCli; @RunWith(MockitoJUnitRunner.class) public class JU_ListUsersInRole { - private static ListUsersInRole lsUserinRole; + private static ListUsersInRole lsUserinRole; - @BeforeClass - public static void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - NS ns = new NS(cli); - List ls = new List(ns);//possible wrong import, remove import org.onap.aaf.auth.cmd.ns to see other options - ListUsers lsU = new ListUsers(ls); - lsUserinRole = new ListUsersInRole(lsU); - } + @BeforeClass + public static void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + NS ns = new NS(cli); + List ls = new List(ns);//possible wrong import, remove import org.onap.aaf.auth.cmd.ns to see other options + ListUsers lsU = new ListUsers(ls); + lsUserinRole = new ListUsersInRole(lsU); + } -// @Test -// public void exec() { -// try { -// assertEquals(lsUserinRole._exec(0, "add", "del", "reset", "extend"), 500); -// } catch (Exception e) { -// assertEquals(e.getMessage(), "java.net.UnknownHostException: DME2RESOLVE"); -// } -// } +// @Test +// public void exec() { +// try { +// assertEquals(lsUserinRole._exec(0, "add", "del", "reset", "extend"), 500); +// } catch (Exception e) { +// assertEquals(e.getMessage(), "java.net.UnknownHostException: DME2RESOLVE"); +// } +// } - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsUserinRole.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsUserinRole.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersWithPerm.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersWithPerm.java index 62984d63..dd750c66 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersWithPerm.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_ListUsersWithPerm.java @@ -39,40 +39,40 @@ import org.onap.aaf.auth.cmd.test.JU_AAFCli; @RunWith(MockitoJUnitRunner.class) public class JU_ListUsersWithPerm { - private static ListUsersWithPerm lsUserWithPerm; + private static ListUsersWithPerm lsUserWithPerm; - @BeforeClass - public static void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - NS ns = new NS(cli); - List ls = new List(ns);//possible wrong import, remove import org.onap.aaf.auth.cmd.ns to see other option - ListUsers lsU = new ListUsers(ls); - lsUserWithPerm = new ListUsersWithPerm(lsU); - } + @BeforeClass + public static void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + NS ns = new NS(cli); + List ls = new List(ns);//possible wrong import, remove import org.onap.aaf.auth.cmd.ns to see other option + ListUsers lsU = new ListUsers(ls); + lsUserWithPerm = new ListUsersWithPerm(lsU); + } -// @Test -// public void exec() { -// try { -// assertEquals(lsUserWithPerm._exec(0, "add", "del", "reset", "extend"), 500); -// } catch (Exception e) { -// assertEquals(e.getMessage(), "No Services Found for https://DME2RESOLVE [ ]"); +// @Test +// public void exec() { +// try { +// assertEquals(lsUserWithPerm._exec(0, "add", "del", "reset", "extend"), 500); +// } catch (Exception e) { +// assertEquals(e.getMessage(), "No Services Found for https://DME2RESOLVE [ ]"); // -// } -// } +// } +// } - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsUserWithPerm.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } - - @Test //TODO: Temporary fix AAF-111 - public void netYetTested() { - Assert.assertTrue(true); - } + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsUserWithPerm.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } + + @Test //TODO: Temporary fix AAF-111 + public void netYetTested() { + Assert.assertTrue(true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Owner.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Owner.java index a03cb3ad..2b552b91 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Owner.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Owner.java @@ -52,31 +52,31 @@ import org.junit.Test; public class JU_Owner { - private static Owner owner; + private static Owner owner; - @BeforeClass - public static void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - NS ns = new NS(cli); - owner = new Owner(ns); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - String[] strArr = {"add","del","add","del"}; - //owner._exec(0, strArr); + @BeforeClass + public static void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + NS ns = new NS(cli); + owner = new Owner(ns); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + String[] strArr = {"add","del","add","del"}; + //owner._exec(0, strArr); - } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - owner.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + owner.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Responsible.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Responsible.java index 4c1cdc6f..9229ba2c 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Responsible.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/ns/JU_Responsible.java @@ -37,39 +37,39 @@ import org.onap.aaf.misc.env.APIException; public class JU_Responsible { -// private static Responsible responsible;//TODO: Gabe[JUnit] check with Jonathan +// private static Responsible responsible;//TODO: Gabe[JUnit] check with Jonathan // -// @BeforeClass -// public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException { -// AAFcli cli = JU_AAFCli.getAAfCli(); -// NS ns = new NS(cli); -// responsible = new Responsible(ns); +// @BeforeClass +// public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException { +// AAFcli cli = JU_AAFCli.getAAfCli(); +// NS ns = new NS(cli); +// responsible = new Responsible(ns); // -// } +// } // -// @Test -// public void exec1() { -// try { -// responsible._exec(0, "del", "del", "del"); -// } catch (Exception e) { -// assertEquals(e.getMessage(), "java.net.UnknownHostException: DME2RESOLVE"); -// } -// } +// @Test +// public void exec1() { +// try { +// responsible._exec(0, "del", "del", "del"); +// } catch (Exception e) { +// assertEquals(e.getMessage(), "java.net.UnknownHostException: DME2RESOLVE"); +// } +// } // -// @Test -// public void detailedHelp() { -// boolean hasNoError = true; -// try { -// responsible.detailedHelp(1, new StringBuilder("test")); -// } catch (Exception e) { -// hasNoError = false; -// } -// assertEquals(hasNoError, true); -// } - - @Test - public void netYetTested() { - Assert.assertTrue(true); - } +// @Test +// public void detailedHelp() { +// boolean hasNoError = true; +// try { +// responsible.detailedHelp(1, new StringBuilder("test")); +// } catch (Exception e) { +// hasNoError = false; +// } +// assertEquals(hasNoError, true); +// } + + @Test + public void netYetTested() { + Assert.assertTrue(true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Create.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Create.java index 41295c79..bfd0ad6d 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Create.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Create.java @@ -56,60 +56,60 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Create { - @Mock private SecuritySetter ssMock; - @Mock private Locator locMock; - @Mock private Writer wrtMock; - @Mock private Rcli clientMock; - @Mock private Future futureMock; - - private static Create create; + @Mock private SecuritySetter ssMock; + @Mock private Locator locMock; + @Mock private Writer wrtMock; + @Mock private Rcli clientMock; + @Mock private Future futureMock; + + private static Create create; - private NS ns; - private PropAccess access; - private HMangrStub hman; - private AuthzEnv aEnv; - private AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - MockitoAnnotations.initMocks(this); - - when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); + private NS ns; + private PropAccess access; + private HMangrStub hman; + private AuthzEnv aEnv; + private AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + MockitoAnnotations.initMocks(this); + + when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); - hman = new HMangrStub(access, locMock, clientMock); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - aEnv = new AuthzEnv(); - aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); - - ns = new NS(aafcli); + hman = new HMangrStub(access, locMock, clientMock); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + aEnv = new AuthzEnv(); + aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); + + ns = new NS(aafcli); - create = new Create(ns); - } - - @Test - public void testError() throws APIException, LocatorException, CadiException, URISyntaxException { - create._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - create._exec(4, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.code()).thenReturn(202); - create._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } + create = new Create(ns); + } + + @Test + public void testError() throws APIException, LocatorException, CadiException, URISyntaxException { + create._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + create._exec(4, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.code()).thenReturn(202); + create._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } - @Test - public void testSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.get(any(Integer.class))).thenReturn(true); - create._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - create.detailedHelp(0, sb); - } - + @Test + public void testSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.get(any(Integer.class))).thenReturn(true); + create._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + create.detailedHelp(0, sb); + } + } \ No newline at end of file diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Delete.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Delete.java index 19cacedb..e504b765 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Delete.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Delete.java @@ -57,60 +57,60 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Delete { - - @Mock private SecuritySetter ssMock; - @Mock private Locator locMock; - @Mock private Writer wrtMock; - @Mock private Rcli clientMock; - @Mock private Future futureMock; + + @Mock private SecuritySetter ssMock; + @Mock private Locator locMock; + @Mock private Writer wrtMock; + @Mock private Rcli clientMock; + @Mock private Future futureMock; - private static Delete del; - - private PropAccess access; - private HMangrStub hman; - private AuthzEnv aEnv; - private AAFcli aafcli; - - @Before - public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - MockitoAnnotations.initMocks(this); + private static Delete del; + + private PropAccess access; + private HMangrStub hman; + private AuthzEnv aEnv; + private AAFcli aafcli; + + @Before + public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + MockitoAnnotations.initMocks(this); - when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); - hman = new HMangrStub(access, locMock, clientMock); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - aEnv = new AuthzEnv(); - aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); + hman = new HMangrStub(access, locMock, clientMock); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + aEnv = new AuthzEnv(); + aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); - Role role = new Role(aafcli); - Perm perm = new Perm(role); + Role role = new Role(aafcli); + Perm perm = new Perm(role); - del = new Delete(perm); - } - - @Test - public void testExecError() throws APIException, LocatorException, CadiException, URISyntaxException { - del._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } + del = new Delete(perm); + } + + @Test + public void testExecError() throws APIException, LocatorException, CadiException, URISyntaxException { + del._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } - @Test - public void testExecSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.code()).thenReturn(202); - del._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.get(any(Integer.class))).thenReturn(true); - del._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - del.detailedHelp(0, sb); - } - + @Test + public void testExecSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.code()).thenReturn(202); + del._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.get(any(Integer.class))).thenReturn(true); + del._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + del.detailedHelp(0, sb); + } + } \ No newline at end of file diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Describe.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Describe.java index 9a5fc734..4d3b36d0 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Describe.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Describe.java @@ -57,58 +57,58 @@ import org.onap.aaf.auth.cmd.test.HMangrStub; @RunWith(MockitoJUnitRunner.class) public class JU_Describe { - @Mock private SecuritySetter ssMock; - @Mock private Locator locMock; - @Mock private Writer wrtMock; - @Mock private Rcli clientMock; - @Mock private Future futureMock; + @Mock private SecuritySetter ssMock; + @Mock private Locator locMock; + @Mock private Writer wrtMock; + @Mock private Rcli clientMock; + @Mock private Future futureMock; - private PropAccess access; - private HMangrStub hman; - private AuthzEnv aEnv; - private AAFcli aafcli; - - private Describe desc; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - MockitoAnnotations.initMocks(this); + private PropAccess access; + private HMangrStub hman; + private AuthzEnv aEnv; + private AAFcli aafcli; + + private Describe desc; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + MockitoAnnotations.initMocks(this); - when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); - hman = new HMangrStub(access, locMock, clientMock); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - aEnv = new AuthzEnv(); - aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); + hman = new HMangrStub(access, locMock, clientMock); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + aEnv = new AuthzEnv(); + aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); - Role role = new Role(aafcli); - Perm perm = new Perm(role); + Role role = new Role(aafcli); + Perm perm = new Perm(role); - desc = new Describe(perm); - } - - @Test - public void testExecError() throws APIException, LocatorException, CadiException, URISyntaxException { - desc._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.code()).thenReturn(202); - desc._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.get(any(Integer.class))).thenReturn(true); - desc._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - desc.detailedHelp(0, sb); - } + desc = new Describe(perm); + } + + @Test + public void testExecError() throws APIException, LocatorException, CadiException, URISyntaxException { + desc._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.code()).thenReturn(202); + desc._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.get(any(Integer.class))).thenReturn(true); + desc._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + desc.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Grant.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Grant.java index 975b83d2..a85b1aa6 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Grant.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Grant.java @@ -56,76 +56,76 @@ import org.onap.aaf.auth.cmd.test.HMangrStub; @RunWith(MockitoJUnitRunner.class) public class JU_Grant { - - private static Grant grant; + + private static Grant grant; - @Mock private SecuritySetter ssMock; - @Mock private Locator locMock; - @Mock private Writer wrtMock; - @Mock private Rcli clientMock; - @Mock private Future futureMock; + @Mock private SecuritySetter ssMock; + @Mock private Locator locMock; + @Mock private Writer wrtMock; + @Mock private Rcli clientMock; + @Mock private Future futureMock; - private PropAccess access; - private HMangrStub hman; - private AuthzEnv aEnv; - private AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - MockitoAnnotations.initMocks(this); + private PropAccess access; + private HMangrStub hman; + private AuthzEnv aEnv; + private AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + MockitoAnnotations.initMocks(this); - when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); - when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.create(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.delete(any(), any(), any(String.class))).thenReturn(futureMock); + when(clientMock.update(any(), any(), any(String.class))).thenReturn(futureMock); - hman = new HMangrStub(access, locMock, clientMock); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - aEnv = new AuthzEnv(); - aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); + hman = new HMangrStub(access, locMock, clientMock); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + aEnv = new AuthzEnv(); + aafcli = new AAFcli(access, aEnv, wrtMock, hman, null, ssMock); - Role role = new Role(aafcli); - Perm perm = new Perm(role); + Role role = new Role(aafcli); + Perm perm = new Perm(role); - grant = new Grant(perm); - } + grant = new Grant(perm); + } - @Test - public void testExecError() throws APIException, LocatorException, CadiException, URISyntaxException { - grant._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.code()).thenReturn(202); - grant._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - grant._exec(1, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.get(any(Integer.class))).thenReturn(true); - grant._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSetToError() throws APIException, LocatorException, CadiException, URISyntaxException { - grant._exec(2, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSetToSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { - when(futureMock.get(any(Integer.class))).thenReturn(true); - grant._exec(2, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); - } - - @Test - public void testExecSetToSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { - grant._exec(2, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo","another"}); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - grant.detailedHelp(0, sb); - } + @Test + public void testExecError() throws APIException, LocatorException, CadiException, URISyntaxException { + grant._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.code()).thenReturn(202); + grant._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + grant._exec(1, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.get(any(Integer.class))).thenReturn(true); + grant._exec(0, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSetToError() throws APIException, LocatorException, CadiException, URISyntaxException { + grant._exec(2, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSetToSuccess1() throws APIException, LocatorException, CadiException, URISyntaxException { + when(futureMock.get(any(Integer.class))).thenReturn(true); + grant._exec(2, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo"}); + } + + @Test + public void testExecSetToSuccess2() throws APIException, LocatorException, CadiException, URISyntaxException { + grant._exec(2, new String[] {"grant","ungrant","setTo","grant","ungrant","setTo","another"}); + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + grant.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListActivity.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListActivity.java index 16bd3f9c..1f691768 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListActivity.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListActivity.java @@ -57,48 +57,48 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListActivity { - - private static ListActivity lsActivity; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - Perm perm = new Perm(role); - List ls = new List(perm); - lsActivity = new ListActivity(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"}; - //lsActivity._exec(0, strArr); + + private static ListActivity lsActivity; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + Perm perm = new Perm(role); + List ls = new List(perm); + lsActivity = new ListActivity(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"}; + //lsActivity._exec(0, strArr); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsActivity.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsActivity.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByNS.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByNS.java index e8f34f38..ee367541 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByNS.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByNS.java @@ -41,37 +41,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByNS { - - private static ListByNS lsByNS; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - Role role = new Role(cli); - Perm perm = new Perm(role); - List ls = new List(perm); - lsByNS = new ListByNS(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsByNS._exec(0, "add","del","reset","extend"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsByNS.detailedHelp(0, sb); - } + + private static ListByNS lsByNS; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + Role role = new Role(cli); + Perm perm = new Perm(role); + List ls = new List(perm); + lsByNS = new ListByNS(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsByNS._exec(0, "add","del","reset","extend"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsByNS.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByName.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByName.java index fb845181..a6c3a895 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByName.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByName.java @@ -57,48 +57,48 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByName { - - private static ListByName lsByName; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - Perm perm = new Perm(role); - List ls = new List(perm); - lsByName = new ListByName(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"List Child Permissions"}; - //lsByName._exec(0, strArr); + + private static ListByName lsByName; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + Perm perm = new Perm(role); + List ls = new List(perm); + lsByName = new ListByName(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"List Child Permissions"}; + //lsByName._exec(0, strArr); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsByName.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsByName.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByRole.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByRole.java index c9302aa2..ae61d267 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByRole.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByRole.java @@ -41,37 +41,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByRole { - - private static ListByRole lsByRole; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - Role role = new Role(cli); - Perm perm = new Perm(role); - List ls = new List(perm); - lsByRole = new ListByRole(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsByRole._exec(0, "add","del","reset","extend"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsByRole.detailedHelp(0, sb); - } + + private static ListByRole lsByRole; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + Role role = new Role(cli); + Perm perm = new Perm(role); + List ls = new List(perm); + lsByRole = new ListByRole(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsByRole._exec(0, "add","del","reset","extend"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsByRole.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByUser.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByUser.java index d220d397..5eafbf05 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByUser.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_ListByUser.java @@ -41,37 +41,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByUser { - - private static ListByUser lsByName; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - Role role = new Role(cli); - Perm perm = new Perm(role); - List ls = new List(perm); - lsByName = new ListByUser(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsByName._exec(0, "add","del","reset","extend"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsByName.detailedHelp(0, sb); - } + + private static ListByUser lsByName; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + Role role = new Role(cli); + Perm perm = new Perm(role); + List ls = new List(perm); + lsByName = new ListByUser(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsByName._exec(0, "add","del","reset","extend"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsByName.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Rename.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Rename.java index b4d86edd..5503750e 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Rename.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/perm/JU_Rename.java @@ -56,47 +56,47 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Rename { - - private static Rename rename; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - Perm perm = new Perm(role); - rename = new Rename(perm); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"}; -// rename._exec(0, strArr); - - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - rename.detailedHelp(0, sb); - } + + private static Rename rename; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + Perm perm = new Perm(role); + rename = new Rename(perm); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"}; +// rename._exec(0, strArr); + + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + rename.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_CreateDelete.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_CreateDelete.java index bf2741e5..e2cd56d4 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_CreateDelete.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_CreateDelete.java @@ -55,54 +55,54 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_CreateDelete { - - private static CreateDelete createDel; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - createDel = new CreateDelete(role); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"create","delete","create","delete"}; -// createDel._exec(0, strArr); -// -// String[] strArr1 = {"delete","create","delete"}; -// createDel._exec(0, strArr1); - - } - - @Test - public void testDetailedHelp() { - boolean hasNoError = true; - try { - createDel.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + + private static CreateDelete createDel; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + createDel = new CreateDelete(role); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"create","delete","create","delete"}; +// createDel._exec(0, strArr); +// +// String[] strArr1 = {"delete","create","delete"}; +// createDel._exec(0, strArr1); + + } + + @Test + public void testDetailedHelp() { + boolean hasNoError = true; + try { + createDel.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_Describe.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_Describe.java index 61236eee..8733ceac 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_Describe.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_Describe.java @@ -49,51 +49,51 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Describe { - - private static Describe desc; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - desc = new Describe(role); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add","upd","del","add","upd","del"}; -// desc._exec(0, strArr); - - } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - desc.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + + private static Describe desc; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + desc = new Describe(role); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add","upd","del","add","upd","del"}; +// desc._exec(0, strArr); + + } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + desc.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_List.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_List.java index 84b3caa9..ce5d74d0 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_List.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_List.java @@ -65,97 +65,97 @@ import java.util.ArrayList; import org.junit.Test; public class JU_List { - - AAFcli cli; - Role role; - List list; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; + + AAFcli cli; + Role role; + List list; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; - private class ListRolesStub extends List { + private class ListRolesStub extends List { - public ListRolesStub(Role parent) { - super(parent); - // TODO Auto-generated constructor stub - } - } - - private class RolesStub extends Roles { - public void addRole(aaf.v2_0.Role role) { - if (this.role == null) { - this.role = new ArrayList<>(); - } - this.role.add(role); - } - } - - private class RoleStub extends aaf.v2_0.Role { - - public void addPerms(Pkey perms) { - if (this.perms == null) { - this.perms = new ArrayList<>(); - } - this.perms.add(perms); - } - } - - @Before - public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException{ - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - role = new Role(aafcli); - list = new List(role); - } - - @Test - public void testRoles() throws APIException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Role role = new Role(aafcli); - ListRolesStub listStub = new ListRolesStub(role); - Future future = mock(Future.class); - Rcli rcli = mock(Rcli.class); - - Class c = listStub.getClass(); - Class[] cArg = new Class[3]; - cArg[0] = Future.class; - cArg[1] = Rcli.class; - cArg[2] = String.class;//Steps to test a protected method - //Method listMethod = c.getDeclaredMethod("list", cArg); - //listMethod.setAccessible(true); - //listMethod.invoke(listStub, future, rcli, "test"); - - } - - @Test - public void testReport() throws Exception { - UserRoles urs = new UserRoles(); - Perms perms = new Perms(); - RolesStub roles = new RolesStub(); - list.report(roles, perms , urs , "test"); - AAFcli cli = JU_AAFCli.getAAfCli(); - RoleStub role = new RoleStub(); - roles.addRole(role); - Pkey pkey = new Pkey(); - pkey.setInstance("test"); - pkey.setAction("test"); - pkey.setInstance("test"); - pkey.setType("test"); - role.addPerms(pkey); - list.report(roles, perms , null , "test"); - list.report(roles, perms , urs , "test"); - - aafcli.eval("DETAILS @[ 123"); - role.setName("test"); + public ListRolesStub(Role parent) { + super(parent); + // TODO Auto-generated constructor stub + } + } + + private class RolesStub extends Roles { + public void addRole(aaf.v2_0.Role role) { + if (this.role == null) { + this.role = new ArrayList<>(); + } + this.role.add(role); + } + } + + private class RoleStub extends aaf.v2_0.Role { + + public void addPerms(Pkey perms) { + if (this.perms == null) { + this.perms = new ArrayList<>(); + } + this.perms.add(perms); + } + } + + @Before + public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException, CadiException{ + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + role = new Role(aafcli); + list = new List(role); + } + + @Test + public void testRoles() throws APIException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Role role = new Role(aafcli); + ListRolesStub listStub = new ListRolesStub(role); + Future future = mock(Future.class); + Rcli rcli = mock(Rcli.class); + + Class c = listStub.getClass(); + Class[] cArg = new Class[3]; + cArg[0] = Future.class; + cArg[1] = Rcli.class; + cArg[2] = String.class;//Steps to test a protected method + //Method listMethod = c.getDeclaredMethod("list", cArg); + //listMethod.setAccessible(true); + //listMethod.invoke(listStub, future, rcli, "test"); + + } + + @Test + public void testReport() throws Exception { + UserRoles urs = new UserRoles(); + Perms perms = new Perms(); + RolesStub roles = new RolesStub(); + list.report(roles, perms , urs , "test"); + AAFcli cli = JU_AAFCli.getAAfCli(); + RoleStub role = new RoleStub(); + roles.addRole(role); + Pkey pkey = new Pkey(); + pkey.setInstance("test"); + pkey.setAction("test"); + pkey.setInstance("test"); + pkey.setType("test"); + role.addPerms(pkey); + list.report(roles, perms , null , "test"); + list.report(roles, perms , urs , "test"); + + aafcli.eval("DETAILS @[ 123"); + role.setName("test"); - list.report(roles, perms , urs , "test"); - } + list.report(roles, perms , urs , "test"); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListActivity.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListActivity.java index 4976f753..5c1a839e 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListActivity.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListActivity.java @@ -56,52 +56,52 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListActivity { - - private static ListActivity lsActivity; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - List ls = new List(role); - lsActivity = new ListActivity(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del","add","upd","del"}; - //lsActivity._exec(0, strArr); - - } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsActivity.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + + private static ListActivity lsActivity; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + List ls = new List(role); + lsActivity = new ListActivity(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del","add","upd","del"}; + //lsActivity._exec(0, strArr); + + } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsActivity.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNS.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNS.java index 6017905c..c8443912 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNS.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNS.java @@ -40,41 +40,41 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByNS { - - private static ListByNS lsByNS; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - Role role = new Role(cli); - List ls = new List(role); - lsByNS = new ListByNS(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsByNS._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsByNS.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + + private static ListByNS lsByNS; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + Role role = new Role(cli); + List ls = new List(role); + lsByNS = new ListByNS(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsByNS._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsByNS.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNameOnly.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNameOnly.java index 49a53d82..1bac5004 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNameOnly.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByNameOnly.java @@ -56,52 +56,52 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByNameOnly { - - private static ListByNameOnly lsByName; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - List ls = new List(role); - lsByName = new ListByNameOnly(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del","add","upd","del"}; - //lsByName._exec(0, strArr); - - } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsByName.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + + private static ListByNameOnly lsByName; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + List ls = new List(role); + lsByName = new ListByNameOnly(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del","add","upd","del"}; + //lsByName._exec(0, strArr); + + } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsByName.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByPerm.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByPerm.java index 65f2c6f0..cc1a4b75 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByPerm.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByPerm.java @@ -40,41 +40,41 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByPerm { - - private static ListByPerm lsByPerm; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - Role role = new Role(cli); - List ls = new List(role); - lsByPerm = new ListByPerm(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsByPerm._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsByPerm.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + + private static ListByPerm lsByPerm; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + Role role = new Role(cli); + List ls = new List(role); + lsByPerm = new ListByPerm(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsByPerm._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsByPerm.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByRole.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByRole.java index 37accbbc..064346ab 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByRole.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByRole.java @@ -40,42 +40,42 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByRole { - - private static ListByRole lsByRole; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - Role role = new Role(cli); - List ls = new List(role); - lsByRole = new ListByRole(ls); - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsByRole._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); -// } catch (CadiException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (APIException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (LocatorException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsByRole.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } - + + private static ListByRole lsByRole; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + Role role = new Role(cli); + List ls = new List(role); + lsByRole = new ListByRole(ls); + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsByRole._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); +// } catch (CadiException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (APIException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (LocatorException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsByRole.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } + } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByUser.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByUser.java index 86ce24cc..a6f297ec 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByUser.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_ListByUser.java @@ -56,53 +56,53 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListByUser { - - private static ListByUser lsByUser; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - List ls = new List(role); - lsByUser = new ListByUser(ls); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del","add","upd","del"}; - //lsByUser._exec(0, strArr); - - } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - lsByUser.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } - + + private static ListByUser lsByUser; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + List ls = new List(role); + lsByUser = new ListByUser(ls); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del","add","upd","del"}; + //lsByUser._exec(0, strArr); + + } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + lsByUser.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } + } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_User.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_User.java index ead62eb6..530362a8 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_User.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/role/JU_User.java @@ -56,60 +56,60 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_User { - - private static User user; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - Role role = new Role(aafcli); - user = new User(role); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add","del","setTo","extend","add","del","setTo","extend"}; -// user._exec(0, strArr); -// -// String[] strArr1 = {"del","setTo","extend","add","del","setTo","extend"}; -// user._exec(0, strArr1); -// -// String[] strArr2 = {"setTo","extend","add","del","setTo","extend"}; -// user._exec(0, strArr2); -// -// String[] strArr3 = {"extend","add","del","setTo","extend"}; -// user._exec(0, strArr3); - - } - - @Test - public void detailedHelp() { - boolean hasNoError = true; - try { - user.detailedHelp(1, new StringBuilder("test")); - } catch (Exception e) { - hasNoError = false; - } - assertEquals(hasNoError, true); - } + + private static User user; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + Role role = new Role(aafcli); + user = new User(role); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add","del","setTo","extend","add","del","setTo","extend"}; +// user._exec(0, strArr); +// +// String[] strArr1 = {"del","setTo","extend","add","del","setTo","extend"}; +// user._exec(0, strArr1); +// +// String[] strArr2 = {"setTo","extend","add","del","setTo","extend"}; +// user._exec(0, strArr2); +// +// String[] strArr3 = {"extend","add","del","setTo","extend"}; +// user._exec(0, strArr3); + + } + + @Test + public void detailedHelp() { + boolean hasNoError = true; + try { + user.detailedHelp(1, new StringBuilder("test")); + } catch (Exception e) { + hasNoError = false; + } + assertEquals(hasNoError, true); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Cred.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Cred.java index 033aff3f..cca28fd4 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Cred.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Cred.java @@ -59,56 +59,56 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Cred { - User user; - Cred cred; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; + User user; + Cred cred; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; - @Before - public void setUp() throws FileNotFoundException, APIException, LocatorException, CadiException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - user = new User(aafcli); - cred = new Cred(user); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add","del","reset","extend"}; -// cred._exec(0, strArr); -// -// String[] strArr1 = {"del","reset","extend","add"}; -// cred._exec(0, strArr1); -// -// String[] strArr2 = {"reset","extend", "add","del"}; -// cred._exec(0, strArr2); -// -// String[] strArr3 = {"extend","add","del","reset"}; -// cred._exec(0, strArr3); + @Before + public void setUp() throws FileNotFoundException, APIException, LocatorException, CadiException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + user = new User(aafcli); + cred = new Cred(user); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add","del","reset","extend"}; +// cred._exec(0, strArr); +// +// String[] strArr1 = {"del","reset","extend","add"}; +// cred._exec(0, strArr1); +// +// String[] strArr2 = {"reset","extend", "add","del"}; +// cred._exec(0, strArr2); +// +// String[] strArr3 = {"extend","add","del","reset"}; +// cred._exec(0, strArr3); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - cred.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + cred.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Delg.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Delg.java index eec11880..03a7cc3e 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Delg.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Delg.java @@ -56,55 +56,55 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Delg { - - private static User testUser; - private static Delg delg; - User user; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; + + private static User testUser; + private static Delg delg; + User user; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; - @Before - public void setUp() throws FileNotFoundException, APIException, LocatorException, CadiException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = mock(HMangr.class); //new HMangr(aEnv, loc); - aafcli = mock(AAFcli.class);//new AAFcli(prop, aEnv, wtr, hman, null, secSet); -// user = mock(User.class); //new User(aafcli); -// delg = new Delg(user); - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"add","upd","del"}; -// delg._exec(0, strArr); - - String[] strArr1 = {"upd","del","add"}; -// delg._exec(0, strArr1); - - String[] strArr2 = {"del","add"}; -// delg._exec(0, strArr2); + @Before + public void setUp() throws FileNotFoundException, APIException, LocatorException, CadiException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = mock(HMangr.class); //new HMangr(aEnv, loc); + aafcli = mock(AAFcli.class);//new AAFcli(prop, aEnv, wtr, hman, null, secSet); +// user = mock(User.class); //new User(aafcli); +// delg = new Delg(user); + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"add","upd","del"}; +// delg._exec(0, strArr); + + String[] strArr1 = {"upd","del","add"}; +// delg._exec(0, strArr1); + + String[] strArr2 = {"del","add"}; +// delg._exec(0, strArr2); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); -// delg.detailedHelp(0, sb); - } - + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); +// delg.detailedHelp(0, sb); + } + } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListActivity.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListActivity.java index 11517248..fc1c9aac 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListActivity.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListActivity.java @@ -40,37 +40,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListActivity { - - private static ListActivity lsActivity; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - User usr = new User(cli); - List parent = new List(usr); - lsActivity = new ListActivity(parent); - - } -// -// @Test -// public void exec() { -// try { -// assertEquals(lsActivity._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); -// } catch (CadiException e) { -// -// e.printStackTrace(); -// } catch (APIException e) { -// -// e.printStackTrace(); -// } catch (LocatorException e) { -// -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsActivity.detailedHelp(0, sb); - } + + private static ListActivity lsActivity; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + User usr = new User(cli); + List parent = new List(usr); + lsActivity = new ListActivity(parent); + + } +// +// @Test +// public void exec() { +// try { +// assertEquals(lsActivity._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); +// } catch (CadiException e) { +// +// e.printStackTrace(); +// } catch (APIException e) { +// +// e.printStackTrace(); +// } catch (LocatorException e) { +// +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsActivity.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListApprovals.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListApprovals.java index 4a9e3aba..457f277c 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListApprovals.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListApprovals.java @@ -58,49 +58,49 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListApprovals { - - private static ListApprovals lsApprovals; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - User usr = new User(aafcli); - List parent = new List(usr); - lsApprovals = new ListApprovals(parent); - } - - + + private static ListApprovals lsApprovals; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + User usr = new User(aafcli); + List parent = new List(usr); + lsApprovals = new ListApprovals(parent); + } + + - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"user","approver","ticket"}; - //lsApprovals._exec(0, strArr); - - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsApprovals.detailedHelp(0, sb); - } + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"user","approver","ticket"}; + //lsApprovals._exec(0, strArr); + + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsApprovals.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListDelegates.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListDelegates.java index a1a21ed4..4ddbd337 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListDelegates.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListDelegates.java @@ -40,37 +40,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListDelegates { - - private static ListDelegates lsDelegates; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - User usr = new User(cli); - List parent = new List(usr); - lsDelegates = new ListDelegates(parent); - - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsDelegates._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); -// } catch (CadiException e) { -// -// e.printStackTrace(); -// } catch (APIException e) { -// -// e.printStackTrace(); -// } catch (LocatorException e) { -// -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsDelegates.detailedHelp(0, sb); - } + + private static ListDelegates lsDelegates; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + User usr = new User(cli); + List parent = new List(usr); + lsDelegates = new ListDelegates(parent); + + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsDelegates._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); +// } catch (CadiException e) { +// +// e.printStackTrace(); +// } catch (APIException e) { +// +// e.printStackTrace(); +// } catch (LocatorException e) { +// +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsDelegates.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForCreds.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForCreds.java index 89364b2b..08d5f5c4 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForCreds.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForCreds.java @@ -56,49 +56,49 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListForCreds { - - private static ListForCreds lsForCreds; - User user; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - User usr = new User(aafcli); - List parent = new List(usr); - lsForCreds = new ListForCreds(parent); - - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); - HRcli hcli = new HRcli(hman, uri, item, secSet); - String[] strArr = {"ns","id","ns","id"}; - //lsForCreds._exec(0, strArr); + + private static ListForCreds lsForCreds; + User user; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + User usr = new User(aafcli); + List parent = new List(usr); + lsForCreds = new ListForCreds(parent); + + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); + HRcli hcli = new HRcli(hman, uri, item, secSet); + String[] strArr = {"ns","id","ns","id"}; + //lsForCreds._exec(0, strArr); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsForCreds.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsForCreds.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForPermission.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForPermission.java index bebd7eca..0cc20550 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForPermission.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForPermission.java @@ -40,37 +40,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListForPermission { - - private static ListForPermission lsForPermission; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - User usr = new User(cli); - List parent = new List(usr); - lsForPermission = new ListForPermission(parent); - - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsForPermission._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); -// } catch (CadiException e) { -// -// e.printStackTrace(); -// } catch (APIException e) { -// -// e.printStackTrace(); -// } catch (LocatorException e) { -// -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsForPermission.detailedHelp(0, sb); - } + + private static ListForPermission lsForPermission; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + User usr = new User(cli); + List parent = new List(usr); + lsForPermission = new ListForPermission(parent); + + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsForPermission._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); +// } catch (CadiException e) { +// +// e.printStackTrace(); +// } catch (APIException e) { +// +// e.printStackTrace(); +// } catch (LocatorException e) { +// +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsForPermission.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForRoles.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForRoles.java index 457c1987..62b05150 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForRoles.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_ListForRoles.java @@ -40,37 +40,37 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_ListForRoles { - - private static ListForRoles lsForRoles; - - @BeforeClass - public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - AAFcli cli = JU_AAFCli.getAAfCli(); - User usr = new User(cli); - List parent = new List(usr); - lsForRoles = new ListForRoles(parent); - - } - -// @Test -// public void exec() { -// try { -// assertEquals(lsForRoles._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); -// } catch (CadiException e) { -// -// e.printStackTrace(); -// } catch (APIException e) { -// -// e.printStackTrace(); -// } catch (LocatorException e) { -// -// e.printStackTrace(); -// } -// } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - lsForRoles.detailedHelp(0, sb); - } + + private static ListForRoles lsForRoles; + + @BeforeClass + public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + AAFcli cli = JU_AAFCli.getAAfCli(); + User usr = new User(cli); + List parent = new List(usr); + lsForRoles = new ListForRoles(parent); + + } + +// @Test +// public void exec() { +// try { +// assertEquals(lsForRoles._exec(0, "add","del","reset","extend","clear", "rename", "create"),500); +// } catch (CadiException e) { +// +// e.printStackTrace(); +// } catch (APIException e) { +// +// e.printStackTrace(); +// } catch (LocatorException e) { +// +// e.printStackTrace(); +// } +// } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + lsForRoles.detailedHelp(0, sb); + } } diff --git a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Role.java b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Role.java index 2799f93d..ce490819 100644 --- a/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Role.java +++ b/auth/auth-cmd/src/test/java/org/onap/aaf/auth/cmd/test/user/JU_Role.java @@ -55,57 +55,57 @@ import org.onap.aaf.misc.env.APIException; @RunWith(MockitoJUnitRunner.class) public class JU_Role { - - private static Role role; - User user; - PropAccess prop; - AuthzEnv aEnv; - Writer wtr; - Locator loc; - HMangr hman; - AAFcli aafcli; - - @Before - public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { - prop = new PropAccess(); - aEnv = new AuthzEnv(); - wtr = mock(Writer.class); - loc = mock(Locator.class); - SecuritySetter secSet = mock(SecuritySetter.class); - hman = new HMangr(aEnv, loc); - aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); - User usr = new User(aafcli); - role = new Role(usr); - - } - - @Test - public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { - Item value = mock(Item.class); - Locator.Item item = new Locator.Item() { - }; - when(loc.best()).thenReturn(value); - URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); - when(loc.get(value)).thenReturn(uri); - SecuritySetter secSet = mock(SecuritySetter.class); -// HRcli hcli = new HRcli(hman, uri, item, secSet); -// String[] strArr = {"add", "del", "setTo","extend", "del", "setTo","extend"}; -// Assert.assertEquals(200, role._exec(0, strArr)); -// -// String[] strArr1 = { "del", "setTo","extend","add", "del", "setTo","extend"}; -// Assert.assertEquals(501, role._exec(0, strArr1)); -// -// String[] strArr2 = {"setTo","extend","add", "del", "del", "setTo","extend" }; -// Assert.assertEquals(501, role._exec(0, strArr2)); -// -// String[] strArr3 = {"extend","add", "del","setTo", "del", "setTo","extend" }; -// Assert.assertEquals(501, role._exec(0, strArr3)); + + private static Role role; + User user; + PropAccess prop; + AuthzEnv aEnv; + Writer wtr; + Locator loc; + HMangr hman; + AAFcli aafcli; + + @Before + public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException { + prop = new PropAccess(); + aEnv = new AuthzEnv(); + wtr = mock(Writer.class); + loc = mock(Locator.class); + SecuritySetter secSet = mock(SecuritySetter.class); + hman = new HMangr(aEnv, loc); + aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet); + User usr = new User(aafcli); + role = new Role(usr); + + } + + @Test + public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException { + Item value = mock(Item.class); + Locator.Item item = new Locator.Item() { + }; + when(loc.best()).thenReturn(value); + URI uri = new URI("http://www.oracle.com/technetwork/java/index.html"); + when(loc.get(value)).thenReturn(uri); + SecuritySetter secSet = mock(SecuritySetter.class); +// HRcli hcli = new HRcli(hman, uri, item, secSet); +// String[] strArr = {"add", "del", "setTo","extend", "del", "setTo","extend"}; +// Assert.assertEquals(200, role._exec(0, strArr)); +// +// String[] strArr1 = { "del", "setTo","extend","add", "del", "setTo","extend"}; +// Assert.assertEquals(501, role._exec(0, strArr1)); +// +// String[] strArr2 = {"setTo","extend","add", "del", "del", "setTo","extend" }; +// Assert.assertEquals(501, role._exec(0, strArr2)); +// +// String[] strArr3 = {"extend","add", "del","setTo", "del", "setTo","extend" }; +// Assert.assertEquals(501, role._exec(0, strArr3)); - } - - @Test - public void testDetailedHelp() { - StringBuilder sb = new StringBuilder(); - role.detailedHelp(0, sb); - } + } + + @Test + public void testDetailedHelp() { + StringBuilder sb = new StringBuilder(); + role.detailedHelp(0, sb); + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java index 9d48ecbe..13aa04fd 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java @@ -45,156 +45,156 @@ import org.onap.aaf.misc.env.Trans; * @param */ public class Cache { - private static Clean clean; - private static Timer cleanseTimer; - - public static final String CACHE_HIGH_COUNT = "CACHE_HIGH_COUNT"; - public static final String CACHE_CLEAN_INTERVAL = "CACHE_CLEAN_INTERVAL"; - - private static final Map> cacheMap; - - static { - cacheMap = new HashMap<>(); - } - - /** - * Dated Class - store any Data with timestamp - * - * @author Jonathan - * - */ - public static final class Dated { - public Date timestamp; - public List data; - private long expireIn; - - public Dated(List data, long expireIn) { - timestamp = new Date(System.currentTimeMillis()+expireIn); - this.data = data; - this.expireIn = expireIn; - } - - public Dated(T t, long expireIn) { - timestamp = new Date(System.currentTimeMillis()+expireIn); - ArrayList al = new ArrayList<>(1); - al.add(t); - data = al; - this.expireIn = expireIn; - } - - public void touch() { - timestamp = new Date(System.currentTimeMillis()+expireIn); - } - } - - public static Map obtain(String key) { - Map m = cacheMap.get(key); - if(m==null) { - m = new ConcurrentHashMap<>(); - synchronized(cacheMap) { - cacheMap.put(key, m); - } - } - return m; - } - - /** - * Clean will examine resources, and remove those that have expired. - * - * If "highs" have been exceeded, then we'll expire 10% more the next time. This will adjust after each run - * without checking contents more than once, making a good average "high" in the minimum speed. - * - * @author Jonathan - * - */ - private static final class Clean extends TimerTask { - private final Env env; - private Set set; - - // The idea here is to not be too restrictive on a high, but to Expire more items by - // shortening the time to expire. This is done by judiciously incrementing "advance" - // when the "highs" are exceeded. This effectively reduces numbers of cached items quickly. - private final int high; - private long advance; - private final long timeInterval; - - public Clean(Env env, long cleanInterval, int highCount) { - this.env = env; - high = highCount; - timeInterval = cleanInterval; - advance = 0; - set = new HashSet<>(); - } - - public synchronized void add(String key) { - set.add(key); - } - - public void run() { - int count = 0; - int total = 0; - // look at now. If we need to expire more by increasing "now" by "advance" - Date now = new Date(System.currentTimeMillis() + advance); - - - for(String name : set) { - Map map = cacheMap.get(name); - if(map==null) { - continue; - } - - for(Map.Entry me : map.entrySet()) { - ++total; - if (me.getValue().timestamp.before(now)) { - map.remove(me.getKey()); - ++count; - } - } - } - - if(count>0) { - env.info().log(Level.INFO, "Cache removed",count,"expired Cached Elements out of", total); - } - - // If High (total) is reached during this period, increase the number of expired services removed for next time. - // There's no point doing it again here, as there should have been cleaned items. - if(total>high) { - // advance cleanup by 10%, without getting greater than timeInterval. - advance = Math.min(timeInterval, advance+(timeInterval/10)); - } else { - // reduce advance by 10%, without getting lower than 0. - advance = Math.max(0, advance-(timeInterval/10)); - } - } - } - - public static synchronized void startCleansing(Env env, String ... keys) { - if(cleanseTimer==null) { - cleanseTimer = new Timer("Cache Cleanup Timer"); - int cleanInterval = Integer.parseInt(env.getProperty(CACHE_CLEAN_INTERVAL,"60000")); // 1 minute clean cycles - int highCount = Integer.parseInt(env.getProperty(CACHE_HIGH_COUNT,"5000")); - cleanseTimer.schedule(clean = new Clean(env, cleanInterval, highCount), cleanInterval, cleanInterval); - } - - for(String key : keys) { - clean.add(key); - } - } - - public static void stopTimer() { - if(cleanseTimer!=null) { - cleanseTimer.cancel(); - cleanseTimer = null; - } - } - - public static void addShutdownHook() { - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - Cache.stopTimer(); - } - }); - } + private static Clean clean; + private static Timer cleanseTimer; + + public static final String CACHE_HIGH_COUNT = "CACHE_HIGH_COUNT"; + public static final String CACHE_CLEAN_INTERVAL = "CACHE_CLEAN_INTERVAL"; + + private static final Map> cacheMap; + + static { + cacheMap = new HashMap<>(); + } + + /** + * Dated Class - store any Data with timestamp + * + * @author Jonathan + * + */ + public static final class Dated { + public Date timestamp; + public List data; + private long expireIn; + + public Dated(List data, long expireIn) { + timestamp = new Date(System.currentTimeMillis()+expireIn); + this.data = data; + this.expireIn = expireIn; + } + + public Dated(T t, long expireIn) { + timestamp = new Date(System.currentTimeMillis()+expireIn); + ArrayList al = new ArrayList<>(1); + al.add(t); + data = al; + this.expireIn = expireIn; + } + + public void touch() { + timestamp = new Date(System.currentTimeMillis()+expireIn); + } + } + + public static Map obtain(String key) { + Map m = cacheMap.get(key); + if(m==null) { + m = new ConcurrentHashMap<>(); + synchronized(cacheMap) { + cacheMap.put(key, m); + } + } + return m; + } + + /** + * Clean will examine resources, and remove those that have expired. + * + * If "highs" have been exceeded, then we'll expire 10% more the next time. This will adjust after each run + * without checking contents more than once, making a good average "high" in the minimum speed. + * + * @author Jonathan + * + */ + private static final class Clean extends TimerTask { + private final Env env; + private Set set; + + // The idea here is to not be too restrictive on a high, but to Expire more items by + // shortening the time to expire. This is done by judiciously incrementing "advance" + // when the "highs" are exceeded. This effectively reduces numbers of cached items quickly. + private final int high; + private long advance; + private final long timeInterval; + + public Clean(Env env, long cleanInterval, int highCount) { + this.env = env; + high = highCount; + timeInterval = cleanInterval; + advance = 0; + set = new HashSet<>(); + } + + public synchronized void add(String key) { + set.add(key); + } + + public void run() { + int count = 0; + int total = 0; + // look at now. If we need to expire more by increasing "now" by "advance" + Date now = new Date(System.currentTimeMillis() + advance); + + + for(String name : set) { + Map map = cacheMap.get(name); + if(map==null) { + continue; + } + + for(Map.Entry me : map.entrySet()) { + ++total; + if (me.getValue().timestamp.before(now)) { + map.remove(me.getKey()); + ++count; + } + } + } + + if(count>0) { + env.info().log(Level.INFO, "Cache removed",count,"expired Cached Elements out of", total); + } + + // If High (total) is reached during this period, increase the number of expired services removed for next time. + // There's no point doing it again here, as there should have been cleaned items. + if(total>high) { + // advance cleanup by 10%, without getting greater than timeInterval. + advance = Math.min(timeInterval, advance+(timeInterval/10)); + } else { + // reduce advance by 10%, without getting lower than 0. + advance = Math.max(0, advance-(timeInterval/10)); + } + } + } + + public static synchronized void startCleansing(Env env, String ... keys) { + if(cleanseTimer==null) { + cleanseTimer = new Timer("Cache Cleanup Timer"); + int cleanInterval = Integer.parseInt(env.getProperty(CACHE_CLEAN_INTERVAL,"60000")); // 1 minute clean cycles + int highCount = Integer.parseInt(env.getProperty(CACHE_HIGH_COUNT,"5000")); + cleanseTimer.schedule(clean = new Clean(env, cleanInterval, highCount), cleanInterval, cleanInterval); + } + + for(String key : keys) { + clean.add(key); + } + } + + public static void stopTimer() { + if(cleanseTimer!=null) { + cleanseTimer.cancel(); + cleanseTimer = null; + } + } + + public static void addShutdownHook() { + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + Cache.stopTimer(); + } + }); + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java index ce0033cc..606e7735 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java @@ -29,60 +29,60 @@ import org.onap.aaf.cadi.Access.Level; import org.onap.aaf.cadi.config.Config; public class Define { - private static String ROOT_NS = null; - private static String ROOT_COMPANY = null; - private static boolean initialized = false; + private static String ROOT_NS = null; + private static String ROOT_COMPANY = null; + private static boolean initialized = false; - private final static String MSG = ".set(Access access) must be called before use"; - public static final CharSequence ROOT_NS_TAG = "AAF_NS"; // use for certain Replacements in Location - private static final String ROOT_NS_TAG_DOT = ROOT_NS_TAG +"."; + private final static String MSG = ".set(Access access) must be called before use"; + public static final CharSequence ROOT_NS_TAG = "AAF_NS"; // use for certain Replacements in Location + private static final String ROOT_NS_TAG_DOT = ROOT_NS_TAG +"."; - public static String ROOT_NS() { - if(ROOT_NS==null) { - throw new RuntimeException(Define.class.getName() + MSG); - } - return ROOT_NS; - } - - public static String ROOT_COMPANY() { - if(ROOT_NS==null) { - throw new RuntimeException(Define.class.getName() + MSG); - } - return ROOT_COMPANY; - } - - public static void set(Access access) throws CadiException { - ROOT_NS = access.getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); - ROOT_COMPANY = access.getProperty(Config.AAF_ROOT_COMPANY,null); - if(ROOT_COMPANY==null) { - int last = ROOT_NS.lastIndexOf('.'); - if(last>=0) { - ROOT_COMPANY = ROOT_NS.substring(0, last); - } else { - throw new CadiException(Config.AAF_ROOT_COMPANY + " or " + Config.AAF_ROOT_NS + " property with 3 positions is required."); - } - } - - for( Entry es : access.getProperties().entrySet()) { - if(es.getKey().toString().startsWith(ROOT_NS_TAG_DOT)) { - access.getProperties().setProperty(es.getKey().toString(),varReplace(es.getValue().toString())); - } - } + public static String ROOT_NS() { + if(ROOT_NS==null) { + throw new RuntimeException(Define.class.getName() + MSG); + } + return ROOT_NS; + } + + public static String ROOT_COMPANY() { + if(ROOT_NS==null) { + throw new RuntimeException(Define.class.getName() + MSG); + } + return ROOT_COMPANY; + } + + public static void set(Access access) throws CadiException { + ROOT_NS = access.getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); + ROOT_COMPANY = access.getProperty(Config.AAF_ROOT_COMPANY,null); + if(ROOT_COMPANY==null) { + int last = ROOT_NS.lastIndexOf('.'); + if(last>=0) { + ROOT_COMPANY = ROOT_NS.substring(0, last); + } else { + throw new CadiException(Config.AAF_ROOT_COMPANY + " or " + Config.AAF_ROOT_NS + " property with 3 positions is required."); + } + } + + for( Entry es : access.getProperties().entrySet()) { + if(es.getKey().toString().startsWith(ROOT_NS_TAG_DOT)) { + access.getProperties().setProperty(es.getKey().toString(),varReplace(es.getValue().toString())); + } + } - initialized = true; - access.printf(Level.INIT,"AAF Root NS is %s, and AAF Company Root is %s",ROOT_NS,ROOT_COMPANY); - } + initialized = true; + access.printf(Level.INIT,"AAF Root NS is %s, and AAF Company Root is %s",ROOT_NS,ROOT_COMPANY); + } - public static String varReplace(final String potential) { - if(potential.startsWith(ROOT_NS_TAG_DOT)) { - return ROOT_NS + potential.substring(6); - } else { - return potential; - } - } + public static String varReplace(final String potential) { + if(potential.startsWith(ROOT_NS_TAG_DOT)) { + return ROOT_NS + potential.substring(6); + } else { + return potential; + } + } - public static boolean isInitialized() { - return initialized; - } - + public static boolean isInitialized() { + return initialized; + } + } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java index a396cd98..70cee5c3 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java @@ -47,245 +47,245 @@ import org.onap.aaf.misc.rosetta.env.RosettaEnv; * */ public class AuthzEnv extends RosettaEnv implements Access { - private long[] times = new long[20]; - private int idx = 0; - private PropAccess access; + private long[] times = new long[20]; + private int idx = 0; + private PropAccess access; - public AuthzEnv() { - super(); - _init(new PropAccess()); - } + public AuthzEnv() { + super(); + _init(new PropAccess()); + } - public AuthzEnv(String ... args) { - super(); - _init(new PropAccess(args)); - } + public AuthzEnv(String ... args) { + super(); + _init(new PropAccess(args)); + } - public AuthzEnv(Properties props) { - super(); - _init(new PropAccess(props)); - } - + public AuthzEnv(Properties props) { + super(); + _init(new PropAccess(props)); + } + - public AuthzEnv(PropAccess pa) { - super(); - _init(pa); - } - - private final void _init(PropAccess pa) { - access = pa; - times = new long[20]; - idx = 0; - fatal = new AccessLogTarget(access, Level.ERROR); - error = fatal; - audit = new AccessLogTarget(access, Level.AUDIT); - init = new AccessLogTarget(access, Level.INIT); - warn = new AccessLogTarget(access, Level.WARN); - info = new AccessLogTarget(access, Level.INFO); - debug = new AccessLogTarget(access, Level.DEBUG); - trace = new AccessLogTarget(access, Level.TRACE); - } - - private class AccessLogTarget implements LogTarget { - private final Level level; - private final Access access; - - public AccessLogTarget(final Access access, final Level level) { - this.level = level; - this.access = access; - } - - @Override - public void log(Object... msgs) { - access.log(level, msgs); - } + public AuthzEnv(PropAccess pa) { + super(); + _init(pa); + } + + private final void _init(PropAccess pa) { + access = pa; + times = new long[20]; + idx = 0; + fatal = new AccessLogTarget(access, Level.ERROR); + error = fatal; + audit = new AccessLogTarget(access, Level.AUDIT); + init = new AccessLogTarget(access, Level.INIT); + warn = new AccessLogTarget(access, Level.WARN); + info = new AccessLogTarget(access, Level.INFO); + debug = new AccessLogTarget(access, Level.DEBUG); + trace = new AccessLogTarget(access, Level.TRACE); + } + + private class AccessLogTarget implements LogTarget { + private final Level level; + private final Access access; + + public AccessLogTarget(final Access access, final Level level) { + this.level = level; + this.access = access; + } + + @Override + public void log(Object... msgs) { + access.log(level, msgs); + } - @Override - public void log(Throwable e, Object... msgs) { - access.log(Level.ERROR, msgs); - } + @Override + public void log(Throwable e, Object... msgs) { + access.log(Level.ERROR, msgs); + } - @Override - public boolean isLoggable() { - return access.willLog(level); - } + @Override + public boolean isLoggable() { + return access.willLog(level); + } - @Override - public void printf(String fmt, Object... vars) { - access.printf(level, fmt, vars); - } - - } - @Override - public AuthzTransImpl newTrans() { - synchronized(this) { - times[idx]=System.currentTimeMillis(); - if(++idx>=times.length)idx=0; - } - return new AuthzTransImpl(this); - } + @Override + public void printf(String fmt, Object... vars) { + access.printf(level, fmt, vars); + } + + } + @Override + public AuthzTransImpl newTrans() { + synchronized(this) { + times[idx]=System.currentTimeMillis(); + if(++idx>=times.length)idx=0; + } + return new AuthzTransImpl(this); + } - /** - * Create a Trans, but do not include in Weighted Average - * @return - */ - public AuthzTrans newTransNoAvg() { - return new AuthzTransImpl(this); - } + /** + * Create a Trans, but do not include in Weighted Average + * @return + */ + public AuthzTrans newTransNoAvg() { + return new AuthzTransImpl(this); + } - public long transRate() { - int count = 0; - long pot = 0; - long prev = 0; - for(int i=idx;i0) { - if(prev>0) { - ++count; - pot += times[i]-prev; - } - prev = times[i]; - } - } - for(int i=0;i0) { - if(prev>0) { - ++count; - pot += times[i]-prev; - } - prev = times[i]; - } - } + public long transRate() { + int count = 0; + long pot = 0; + long prev = 0; + for(int i=idx;i0) { + if(prev>0) { + ++count; + pot += times[i]-prev; + } + prev = times[i]; + } + } + for(int i=0;i0) { + if(prev>0) { + ++count; + pot += times[i]-prev; + } + prev = times[i]; + } + } - return count==0?300000L:pot/count; // Return Weighted Avg, or 5 mins, if none avail. - } - - @Override - public ClassLoader classLoader() { - return getClass().getClassLoader(); - } + return count==0?300000L:pot/count; // Return Weighted Avg, or 5 mins, if none avail. + } + + @Override + public ClassLoader classLoader() { + return getClass().getClassLoader(); + } - @Override - public void load(InputStream is) throws IOException { - access.load(is); - } + @Override + public void load(InputStream is) throws IOException { + access.load(is); + } - @Override - public void log(Level lvl, Object... msgs) { - access.log(lvl, msgs); - } + @Override + public void log(Level lvl, Object... msgs) { + access.log(lvl, msgs); + } - @Override - public void log(Exception e, Object... msgs) { - access.log(e,msgs); - } + @Override + public void log(Exception e, Object... msgs) { + access.log(e,msgs); + } - @Override - public void printf(Level level, String fmt, Object... elements) { - access.printf(level, fmt, elements); - } + @Override + public void printf(Level level, String fmt, Object... elements) { + access.printf(level, fmt, elements); + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Access#willLog(org.onap.aaf.cadi.Access.Level) - */ - @Override - public boolean willLog(Level level) { - return access.willLog(level); - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Access#willLog(org.onap.aaf.cadi.Access.Level) + */ + @Override + public boolean willLog(Level level) { + return access.willLog(level); + } - @Override - public void setLogLevel(Level level) { - access.setLogLevel(level); - } - - private static final byte[] ENC="enc:".getBytes(); - public String decrypt(String encrypted, final boolean anytext) throws IOException { - if(encrypted==null) { - throw new IOException("Password to be decrypted is null"); - } - if(anytext || encrypted.startsWith("enc:")) { - if(decryptor.equals(Decryptor.NULL) && getProperty(Config.CADI_KEYFILE)!=null) { - final Symm s; - try { - s = Symm.obtain(this); - } catch (CadiException e1) { - throw new IOException(e1); - } - decryptor = new Decryptor() { - private Symm symm = s; - @Override - public String decrypt(String encrypted) { - try { - return (encrypted!=null && (anytext || encrypted.startsWith(Symm.ENC))) - ? symm.depass(encrypted) - : encrypted; - } catch (IOException e) { - return ""; - } - } - }; - encryptor = new Encryptor() { - @Override - public String encrypt(String data) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - baos.write(ENC); - return "enc:"+s.enpass(data); - } catch (IOException e) { - return ""; - } - } - - }; - } - return decryptor.decrypt(encrypted); - } else { - return encrypted; - } - } + @Override + public void setLogLevel(Level level) { + access.setLogLevel(level); + } + + private static final byte[] ENC="enc:".getBytes(); + public String decrypt(String encrypted, final boolean anytext) throws IOException { + if(encrypted==null) { + throw new IOException("Password to be decrypted is null"); + } + if(anytext || encrypted.startsWith("enc:")) { + if(decryptor.equals(Decryptor.NULL) && getProperty(Config.CADI_KEYFILE)!=null) { + final Symm s; + try { + s = Symm.obtain(this); + } catch (CadiException e1) { + throw new IOException(e1); + } + decryptor = new Decryptor() { + private Symm symm = s; + @Override + public String decrypt(String encrypted) { + try { + return (encrypted!=null && (anytext || encrypted.startsWith(Symm.ENC))) + ? symm.depass(encrypted) + : encrypted; + } catch (IOException e) { + return ""; + } + } + }; + encryptor = new Encryptor() { + @Override + public String encrypt(String data) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + baos.write(ENC); + return "enc:"+s.enpass(data); + } catch (IOException e) { + return ""; + } + } + + }; + } + return decryptor.decrypt(encrypted); + } else { + return encrypted; + } + } - /* (non-Javadoc) - * @see org.onap.aaf.misc.env.impl.BasicEnv#getProperty(java.lang.String) - */ - @Override - public String getProperty(String key) { - return access.getProperty(key); - } + /* (non-Javadoc) + * @see org.onap.aaf.misc.env.impl.BasicEnv#getProperty(java.lang.String) + */ + @Override + public String getProperty(String key) { + return access.getProperty(key); + } - /* (non-Javadoc) - * @see org.onap.aaf.misc.env.impl.BasicEnv#getProperties(java.lang.String[]) - */ - @Override - public Properties getProperties(String... filter) { - return access.getProperties(); - } + /* (non-Javadoc) + * @see org.onap.aaf.misc.env.impl.BasicEnv#getProperties(java.lang.String[]) + */ + @Override + public Properties getProperties(String... filter) { + return access.getProperties(); + } - /* (non-Javadoc) - * @see org.onap.aaf.misc.env.impl.BasicEnv#getProperty(java.lang.String, java.lang.String) - */ - @Override - public String getProperty(String key, String defaultValue) { - return access.getProperty(key, defaultValue); - } + /* (non-Javadoc) + * @see org.onap.aaf.misc.env.impl.BasicEnv#getProperty(java.lang.String, java.lang.String) + */ + @Override + public String getProperty(String key, String defaultValue) { + return access.getProperty(key, defaultValue); + } - /* (non-Javadoc) - * @see org.onap.aaf.misc.env.impl.BasicEnv#setProperty(java.lang.String, java.lang.String) - */ - @Override - public String setProperty(String key, String value) { - access.setProperty(key, value); - return value; - } + /* (non-Javadoc) + * @see org.onap.aaf.misc.env.impl.BasicEnv#setProperty(java.lang.String, java.lang.String) + */ + @Override + public String setProperty(String key, String value) { + access.setProperty(key, value); + return value; + } - public PropAccess access() { - return access; - } + public PropAccess access() { + return access; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Access#getProperties() - */ - @Override - public Properties getProperties() { - return access.getProperties(); - }; - + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Access#getProperties() + */ + @Override + public Properties getProperties() { + return access.getProperties(); + }; + } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java index bd66ff66..5f7fa410 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java @@ -33,46 +33,46 @@ import org.onap.aaf.misc.env.LogTarget; import org.onap.aaf.misc.env.TransStore; public interface AuthzTrans extends TransStore { - public enum REQD_TYPE {future(1),force(2),move(4),ns(8); - public final int bit; + public enum REQD_TYPE {future(1),force(2),move(4),ns(8); + public final int bit; - REQD_TYPE(int bit) { - this.bit = bit; - } - }; - - public abstract AuthzTrans set(HttpServletRequest req); + REQD_TYPE(int bit) { + this.bit = bit; + } + }; + + public abstract AuthzTrans set(HttpServletRequest req); - public abstract String user(); + public abstract String user(); - public abstract void setUser(TaggedPrincipal p); - - public abstract TaggedPrincipal getUserPrincipal(); + public abstract void setUser(TaggedPrincipal p); + + public abstract TaggedPrincipal getUserPrincipal(); - public abstract String ip(); + public abstract String ip(); - public abstract int port(); + public abstract int port(); - public abstract String meth(); + public abstract String meth(); - public abstract String path(); + public abstract String path(); - public abstract String agent(); - - public abstract AuthzEnv env(); + public abstract String agent(); + + public abstract AuthzEnv env(); - public abstract void setLur(Lur lur); + public abstract void setLur(Lur lur); - public abstract boolean fish(Permission ... p); - - public abstract Organization org(); + public abstract boolean fish(Permission ... p); + + public abstract Organization org(); - public abstract boolean requested(REQD_TYPE requested); - - public void requested(REQD_TYPE requested, boolean b); - - public abstract void logAuditTrail(LogTarget lt); - - public abstract Date now(); + public abstract boolean requested(REQD_TYPE requested); + + public void requested(REQD_TYPE requested, boolean b); + + public abstract void logAuditTrail(LogTarget lt); + + public abstract Date now(); } \ No newline at end of file diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java index 531e40ab..06fd310e 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java @@ -40,144 +40,144 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.Trans.Metric; public class AuthzTransFilter extends TransFilter { - private AuthzEnv env; - public Metric serviceMetric; - public static Slot transIDslot,specialLogSlot; + private AuthzEnv env; + public Metric serviceMetric; + public static Slot transIDslot,specialLogSlot; - public static final String TRANS_ID_SLOT = "TRANS_ID_SLOT"; - public static final String SPECIAL_LOG_SLOT = "SPECIAL_LOG_SLOT"; + public static final String TRANS_ID_SLOT = "TRANS_ID_SLOT"; + public static final String SPECIAL_LOG_SLOT = "SPECIAL_LOG_SLOT"; - public static final int BUCKETSIZE = 2; - - public AuthzTransFilter(AuthzEnv env, Connector con, TrustChecker tc, Object ... additionalTafLurs) throws CadiException, LocatorException { - super(env.access(),con, tc, additionalTafLurs); - this.env = env; - serviceMetric = new Metric(); - serviceMetric.buckets = new float[BUCKETSIZE]; - if(transIDslot==null) { - transIDslot = env.slot(TRANS_ID_SLOT); - } - if(specialLogSlot==null) { - specialLogSlot = env.slot(SPECIAL_LOG_SLOT); - } - } - - @Override - protected AuthzTrans newTrans(HttpServletRequest req) { - AuthzTrans at = env.newTrans(); - at.setLur(getLur()); - at.set(req); - return at; - } + public static final int BUCKETSIZE = 2; + + public AuthzTransFilter(AuthzEnv env, Connector con, TrustChecker tc, Object ... additionalTafLurs) throws CadiException, LocatorException { + super(env.access(),con, tc, additionalTafLurs); + this.env = env; + serviceMetric = new Metric(); + serviceMetric.buckets = new float[BUCKETSIZE]; + if(transIDslot==null) { + transIDslot = env.slot(TRANS_ID_SLOT); + } + if(specialLogSlot==null) { + specialLogSlot = env.slot(SPECIAL_LOG_SLOT); + } + } + + @Override + protected AuthzTrans newTrans(HttpServletRequest req) { + AuthzTrans at = env.newTrans(); + at.setLur(getLur()); + at.set(req); + return at; + } - @Override - protected TimeTaken start(AuthzTrans trans, ServletRequest request) { - trans.set((HttpServletRequest)request); - return trans.start("Trans " + //(context==null?"n/a":context.toString()) + - " IP: " + trans.ip() + - " Port: " + trans.port() - , Env.SUB); - } + @Override + protected TimeTaken start(AuthzTrans trans, ServletRequest request) { + trans.set((HttpServletRequest)request); + return trans.start("Trans " + //(context==null?"n/a":context.toString()) + + " IP: " + trans.ip() + + " Port: " + trans.port() + , Env.SUB); + } - @Override - protected void authenticated(AuthzTrans trans, Principal p) { - trans.setUser((TaggedPrincipal)p); // We only work with TaggedPrincipals in Authz - } + @Override + protected void authenticated(AuthzTrans trans, Principal p) { + trans.setUser((TaggedPrincipal)p); // We only work with TaggedPrincipals in Authz + } - @Override - protected void tallyHo(AuthzTrans trans) { - Boolean b = trans.get(specialLogSlot, false); - LogTarget lt = b?trans.warn():trans.info(); - - if(lt.isLoggable()) { - // Transaction is done, now post full Audit Trail - StringBuilder sb = new StringBuilder("AuditTrail\n"); - // We'll grabAct sub-metrics for Remote Calls and JSON - // IMPORTANT!!! if you add more entries here, change "BUCKETSIZE"!!! - Metric m = trans.auditTrail(lt,1, sb, Env.REMOTE,Env.JSON); + @Override + protected void tallyHo(AuthzTrans trans) { + Boolean b = trans.get(specialLogSlot, false); + LogTarget lt = b?trans.warn():trans.info(); + + if(lt.isLoggable()) { + // Transaction is done, now post full Audit Trail + StringBuilder sb = new StringBuilder("AuditTrail\n"); + // We'll grabAct sub-metrics for Remote Calls and JSON + // IMPORTANT!!! if you add more entries here, change "BUCKETSIZE"!!! + Metric m = trans.auditTrail(lt,1, sb, Env.REMOTE,Env.JSON); - // Add current Metrics to total metrics - serviceMetric.total+= m.total; - for(int i=0;i=0) { - sb.append(content,start+6,content.length()-1); - } else { - sb.append(content); - } - sb.append('"'); - } - - trans.warn().log(sb); - } - } + if(content.length()>0) { + sb.append(",msg=\""); + int start = content.lastIndexOf(",msg=\""); + if(start>=0) { + sb.append(content,start+6,content.length()-1); + } else { + sb.append(content); + } + sb.append('"'); + } + + trans.warn().log(sb); + } + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java index ccfd715f..ee90f284 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java @@ -34,183 +34,183 @@ import org.onap.aaf.misc.env.LogTarget; import org.onap.aaf.misc.env.impl.BasicTrans; public class AuthzTransImpl extends BasicTrans implements AuthzTrans { - private TaggedPrincipal user; - private String ip,agent,meth,path; - private int port; - private Lur lur; - private Organization org; - private int mask; - private Date now; - public AuthzTransImpl(AuthzEnv env) { - super(env); - ip="n/a"; - org=null; - mask=0; - } - - /** - * @see org.onap.aaf.auth.env.test.AuthTrans#set(javax.servlet.http.HttpServletRequest) - */ - @Override - public AuthzTrans set(HttpServletRequest req) { - user = (TaggedPrincipal)req.getUserPrincipal(); - ip = req.getRemoteAddr(); - port = req.getRemotePort(); - agent = req.getHeader("User-Agent"); - meth = req.getMethod(); - path = req.getPathInfo(); - - for(REQD_TYPE rt : REQD_TYPE.values()) { - requested(rt,req); - } - // Handle alternate "request" for "future" - String request = req.getParameter("request"); - if(request!=null) { - requested(REQD_TYPE.future,(request.length()==0 || "true".equalsIgnoreCase(request))); - } - - org=null; - return this; - } - - @Override - public void setUser(TaggedPrincipal p) { - user = p; - } - - /** - * @see org.onap.aaf.auth.env.test.AuthTrans#user() - */ - @Override - public String user() { - return user==null?"n/a":user.getName(); - } - - /** - * @see org.onap.aaf.auth.env.test.AuthTrans#getUserPrincipal() - */ - @Override - public TaggedPrincipal getUserPrincipal() { - return user; - } - - /** - * @see org.onap.aaf.auth.env.test.AuthTrans#ip() - */ - @Override - public String ip() { - return ip; - } - - /** - * @see org.onap.aaf.auth.env.test.AuthTrans#port() - */ - @Override - public int port() { - return port; - } - - - /* (non-Javadoc) - * @see org.onap.aaf.auth.env.test.AuthzTrans#meth() - */ - @Override - public String meth() { - return meth; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.env.test.AuthzTrans#path() - */ - @Override - public String path() { - return path; - } - - /** - * @see org.onap.aaf.auth.env.test.AuthTrans#agent() - */ - @Override - public String agent() { - return agent; - } - - @Override - public AuthzEnv env() { - return (AuthzEnv)delegate; - } - - @Override - public boolean requested(REQD_TYPE requested) { - return (mask&requested.bit)==requested.bit; - } - - public void requested(REQD_TYPE requested, boolean b) { - if(b) { - mask|=requested.bit; - } else { - mask&=~requested.bit; - } - } - - private void requested(REQD_TYPE reqtype, HttpServletRequest req) { - String p = req.getParameter(reqtype.name()); - if(p!=null) { - requested(reqtype,p.length()==0 || "true".equalsIgnoreCase(p)); - } - } - - @Override - public void setLur(Lur lur) { - this.lur = lur; - } - - @Override - public boolean fish(Permission ... pond) { - if(lur!=null) { - return lur.fish(user, pond); - } - return false; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.env.test.AuthzTrans#org() - */ - @Override - public Organization org() { - if(org==null) { - try { - if((org = OrganizationFactory.obtain(env(), user()))==null) { - org = Organization.NULL; - } - } catch (Exception e) { - - org = Organization.NULL; - } - } - return org; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.env.test.AuthzTrans#logAuditTrailOnly(com.att.inno.env.LogTarget) - */ - @Override - public void logAuditTrail(LogTarget lt) { - if(lt.isLoggable()) { - StringBuilder sb = new StringBuilder(); - auditTrail(1, sb); - lt.log(sb); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.env.test.AuthzTrans#now() - */ - @Override - public Date now() { - if(now==null) { - now = new Date(); - } - return now; - } + private TaggedPrincipal user; + private String ip,agent,meth,path; + private int port; + private Lur lur; + private Organization org; + private int mask; + private Date now; + public AuthzTransImpl(AuthzEnv env) { + super(env); + ip="n/a"; + org=null; + mask=0; + } + + /** + * @see org.onap.aaf.auth.env.test.AuthTrans#set(javax.servlet.http.HttpServletRequest) + */ + @Override + public AuthzTrans set(HttpServletRequest req) { + user = (TaggedPrincipal)req.getUserPrincipal(); + ip = req.getRemoteAddr(); + port = req.getRemotePort(); + agent = req.getHeader("User-Agent"); + meth = req.getMethod(); + path = req.getPathInfo(); + + for(REQD_TYPE rt : REQD_TYPE.values()) { + requested(rt,req); + } + // Handle alternate "request" for "future" + String request = req.getParameter("request"); + if(request!=null) { + requested(REQD_TYPE.future,(request.length()==0 || "true".equalsIgnoreCase(request))); + } + + org=null; + return this; + } + + @Override + public void setUser(TaggedPrincipal p) { + user = p; + } + + /** + * @see org.onap.aaf.auth.env.test.AuthTrans#user() + */ + @Override + public String user() { + return user==null?"n/a":user.getName(); + } + + /** + * @see org.onap.aaf.auth.env.test.AuthTrans#getUserPrincipal() + */ + @Override + public TaggedPrincipal getUserPrincipal() { + return user; + } + + /** + * @see org.onap.aaf.auth.env.test.AuthTrans#ip() + */ + @Override + public String ip() { + return ip; + } + + /** + * @see org.onap.aaf.auth.env.test.AuthTrans#port() + */ + @Override + public int port() { + return port; + } + + + /* (non-Javadoc) + * @see org.onap.aaf.auth.env.test.AuthzTrans#meth() + */ + @Override + public String meth() { + return meth; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.env.test.AuthzTrans#path() + */ + @Override + public String path() { + return path; + } + + /** + * @see org.onap.aaf.auth.env.test.AuthTrans#agent() + */ + @Override + public String agent() { + return agent; + } + + @Override + public AuthzEnv env() { + return (AuthzEnv)delegate; + } + + @Override + public boolean requested(REQD_TYPE requested) { + return (mask&requested.bit)==requested.bit; + } + + public void requested(REQD_TYPE requested, boolean b) { + if(b) { + mask|=requested.bit; + } else { + mask&=~requested.bit; + } + } + + private void requested(REQD_TYPE reqtype, HttpServletRequest req) { + String p = req.getParameter(reqtype.name()); + if(p!=null) { + requested(reqtype,p.length()==0 || "true".equalsIgnoreCase(p)); + } + } + + @Override + public void setLur(Lur lur) { + this.lur = lur; + } + + @Override + public boolean fish(Permission ... pond) { + if(lur!=null) { + return lur.fish(user, pond); + } + return false; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.env.test.AuthzTrans#org() + */ + @Override + public Organization org() { + if(org==null) { + try { + if((org = OrganizationFactory.obtain(env(), user()))==null) { + org = Organization.NULL; + } + } catch (Exception e) { + + org = Organization.NULL; + } + } + return org; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.env.test.AuthzTrans#logAuditTrailOnly(com.att.inno.env.LogTarget) + */ + @Override + public void logAuditTrail(LogTarget lt) { + if(lt.isLoggable()) { + StringBuilder sb = new StringBuilder(); + auditTrail(1, sb); + lt.log(sb); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.env.test.AuthzTrans#now() + */ + @Override + public Date now() { + if(now==null) { + now = new Date(); + } + return now; + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java index 2488cc7e..d7b6f1da 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java @@ -31,56 +31,56 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.Trans.Metric; public class AuthzTransOnlyFilter extends TransOnlyFilter { - private AuthzEnv env; - public Metric serviceMetric; + private AuthzEnv env; + public Metric serviceMetric; - public static final int BUCKETSIZE = 2; + public static final int BUCKETSIZE = 2; - public AuthzTransOnlyFilter(AuthzEnv env) { - this.env = env; - serviceMetric = new Metric(); - serviceMetric.buckets = new float[BUCKETSIZE]; - } - - @Override - protected AuthzTrans newTrans() { - return env.newTrans(); - } + public AuthzTransOnlyFilter(AuthzEnv env) { + this.env = env; + serviceMetric = new Metric(); + serviceMetric.buckets = new float[BUCKETSIZE]; + } + + @Override + protected AuthzTrans newTrans() { + return env.newTrans(); + } - @Override - protected TimeTaken start(AuthzTrans trans, ServletRequest request) { - trans.set((HttpServletRequest)request); - return trans.start("Trans " + //(context==null?"n/a":context.toString()) + - " IP: " + trans.ip() + - " Port: " + trans.port() - , Env.SUB); - } + @Override + protected TimeTaken start(AuthzTrans trans, ServletRequest request) { + trans.set((HttpServletRequest)request); + return trans.start("Trans " + //(context==null?"n/a":context.toString()) + + " IP: " + trans.ip() + + " Port: " + trans.port() + , Env.SUB); + } - @Override - protected void authenticated(AuthzTrans trans, TaggedPrincipal p) { - trans.setUser(p); - } + @Override + protected void authenticated(AuthzTrans trans, TaggedPrincipal p) { + trans.setUser(p); + } - @Override - protected void tallyHo(AuthzTrans trans) { - // Transaction is done, now post - StringBuilder sb = new StringBuilder("AuditTrail\n"); - // We'll grab sub-metrics for Remote Calls and JSON - // IMPORTANT!!! if you add more entries here, change "BUCKETSIZE"!!! - Metric m = trans.auditTrail(1, sb, Env.REMOTE,Env.JSON); - // Add current Metrics to total metrics - serviceMetric.total+= m.total; - for(int i=0;i T get(Slot slot, T deflt) { - return null; - } - @Override - public T get(StaticSlot slot, T dflt) { - return null; - } - @Override - public Slot slot(String name) { - return null; - } - @Override - public AuthzEnv env() { - return null; - } - @Override - public String agent() { - return null; - } - - @Override - public void setLur(Lur lur) { - } - - @Override - public boolean fish(Permission ... p) { - return false; - } - - @Override - public Organization org() { - return Organization.NULL; - } - - @Override - public void logAuditTrail(LogTarget lt) { - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.env.test.AuthzTrans#requested(org.onap.aaf.auth.env.test.AuthzTrans.REQD_TYPE) - */ - @Override - public boolean requested(REQD_TYPE requested) { - return false; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.env.test.AuthzTrans#requested(org.onap.aaf.auth.env.test.AuthzTrans.REQD_TYPE, boolean) - */ - @Override - public void requested(REQD_TYPE requested, boolean b) { - } - - @Override - public Date now() { - if(now==null) { - now = new Date(); - } - return now; - } + private static final AuthzTrans singleton = new NullTrans(); + + public static final AuthzTrans singleton() { + return singleton; + } + + private Date now; + + public void checkpoint(String text) {} + public void checkpoint(String text, int additionalFlag) {} + public Metric auditTrail(int indent, StringBuilder sb, int... flag) {return null;} + + @Override + public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int... flag) { + return null; + } + + public LogTarget fatal() { + return LogTarget.NULL; + } + + public LogTarget error() { + return LogTarget.NULL; + } + + public LogTarget audit() { + return LogTarget.NULL; + } + + /* (non-Javadoc) + * @see com.att.env.Env#init() + */ + @Override + public LogTarget init() { + return LogTarget.NULL; + } + + public LogTarget warn() { + return LogTarget.NULL; + } + + public LogTarget info() { + return LogTarget.NULL; + } + + public LogTarget debug() { + return LogTarget.NULL; + } + + public LogTarget trace() { + return LogTarget.NULL; + } + + public TimeTaken start(String name, int flag) { + return new TimeTaken(name,flag) { + public void output(StringBuilder sb) { + sb.append(name); + sb.append(' '); + sb.append(millis()); + sb.append("ms"); + } + }; + } + + @Override + public String setProperty(String tag, String value) { + return value; + } + + @Override + public String getProperty(String tag) { + return tag; + } + + @Override + public String getProperty(String tag, String deflt) { + return deflt; + } + + @Override + public Decryptor decryptor() { + return null; + } + + @Override + public Encryptor encryptor() { + return null; + } + @Override + public AuthzTrans set(HttpServletRequest req) { + return null; + } + + @Override + public String user() { + return null; + } + + @Override + public TaggedPrincipal getUserPrincipal() { + return null; + } + + @Override + public void setUser(TaggedPrincipal p) { + } + + @Override + public String ip() { + return null; + } + + @Override + public int port() { + return 0; + } + @Override + public String meth() { + return null; + } + + @Override + public String path() { + return null; + } + + @Override + public void put(Slot slot, Object value) { + } + @Override + public T get(Slot slot, T deflt) { + return null; + } + @Override + public T get(StaticSlot slot, T dflt) { + return null; + } + @Override + public Slot slot(String name) { + return null; + } + @Override + public AuthzEnv env() { + return null; + } + @Override + public String agent() { + return null; + } + + @Override + public void setLur(Lur lur) { + } + + @Override + public boolean fish(Permission ... p) { + return false; + } + + @Override + public Organization org() { + return Organization.NULL; + } + + @Override + public void logAuditTrail(LogTarget lt) { + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.env.test.AuthzTrans#requested(org.onap.aaf.auth.env.test.AuthzTrans.REQD_TYPE) + */ + @Override + public boolean requested(REQD_TYPE requested) { + return false; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.env.test.AuthzTrans#requested(org.onap.aaf.auth.env.test.AuthzTrans.REQD_TYPE, boolean) + */ + @Override + public void requested(REQD_TYPE requested, boolean b) { + } + + @Override + public Date now() { + if(now==null) { + now = new Date(); + } + return now; + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/FacadeImpl.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/FacadeImpl.java index 81fc1e26..c81504b6 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/FacadeImpl.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/FacadeImpl.java @@ -29,14 +29,14 @@ import org.onap.aaf.misc.env.Data.TYPE; public abstract class FacadeImpl { - protected static final String IN = "in"; + protected static final String IN = "in"; - protected void setContentType(HttpServletResponse response, TYPE type) { - response.setContentType(type==Data.TYPE.JSON?"application/json":"text.xml"); - } - - protected void setCacheControlOff(HttpServletResponse response) { - response.setHeader("Cache-Control", "no-store"); - response.setHeader("Pragma", "no-cache"); - } + protected void setContentType(HttpServletResponse response, TYPE type) { + response.setContentType(type==Data.TYPE.JSON?"application/json":"text.xml"); + } + + protected void setCacheControlOff(HttpServletResponse response) { + response.setHeader("Cache-Control", "no-store"); + response.setHeader("Pragma", "no-cache"); + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java index e61cf2e8..92a8269a 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java @@ -36,37 +36,37 @@ public class Result { private static final String SUCCESS = "Success"; public static final String[] EMPTY_VARS = new String[0]; - public final static int OK=0, - ERR_Security = 1, - ERR_Denied = 2, - ERR_Policy = 3, - ERR_BadData = 4, - ERR_NotImplemented = 5, - ERR_NotFound = 6, - ERR_ConflictAlreadyExists = 7, - ERR_ActionNotCompleted = 8, - ERR_Backend = 9, - ERR_General = 20; - - public final RV value; - public final int status; - public final String details; - public final String[] variables; - - protected Result(RV value, int status, String details, String[] variables) { - this.value = value; - if(value==null) { - specialCondition|=EMPTY_LIST; - } - this.status = status; - this.details = details; - if(variables==null) { - this.variables = EMPTY_VARS; - } else { - this.variables=variables; - } - } - + public final static int OK=0, + ERR_Security = 1, + ERR_Denied = 2, + ERR_Policy = 3, + ERR_BadData = 4, + ERR_NotImplemented = 5, + ERR_NotFound = 6, + ERR_ConflictAlreadyExists = 7, + ERR_ActionNotCompleted = 8, + ERR_Backend = 9, + ERR_General = 20; + + public final RV value; + public final int status; + public final String details; + public final String[] variables; + + protected Result(RV value, int status, String details, String[] variables) { + this.value = value; + if(value==null) { + specialCondition|=EMPTY_LIST; + } + this.status = status; + this.details = details; + if(variables==null) { + this.variables = EMPTY_VARS; + } else { + this.variables=variables; + } + } + /** * Create a Result class with "OK" status and "Success" for details * @@ -77,7 +77,7 @@ public class Result { * @return */ public static Result ok(R value) { - return new Result(value,OK,SUCCESS,null); + return new Result(value,OK,SUCCESS,null); } /** @@ -86,7 +86,7 @@ public class Result { * @return */ public static Result ok(R value[]) { - return new Result(value,OK,SUCCESS,null).emptyList(value.length==0); + return new Result(value,OK,SUCCESS,null).emptyList(value.length==0); } /** @@ -95,7 +95,7 @@ public class Result { * @return */ public static Result> ok(Set value) { - return new Result>(value,OK,SUCCESS,null).emptyList(value.size()==0); + return new Result>(value,OK,SUCCESS,null).emptyList(value.size()==0); } /** @@ -104,7 +104,7 @@ public class Result { * @return */ public static Result> ok(List value) { - return new Result>(value,OK,SUCCESS,null).emptyList(value.size()==0); + return new Result>(value,OK,SUCCESS,null).emptyList(value.size()==0); } /** @@ -113,7 +113,7 @@ public class Result { * @return */ public static Result> ok(Collection value) { - return new Result>(value,OK,SUCCESS,null).emptyList(value.size()==0); + return new Result>(value,OK,SUCCESS,null).emptyList(value.size()==0); } @@ -122,7 +122,7 @@ public class Result { * @return */ public static Result ok() { - return new Result(null,OK,SUCCESS,null); + return new Result(null,OK,SUCCESS,null); } /** @@ -133,7 +133,7 @@ public class Result { * @return */ // public static Result err(int status, String details) { -// return new Result(null,status,details,null); +// return new Result(null,status,details,null); // } /** @@ -144,7 +144,7 @@ public class Result { * @return */ public static Result err(int status, String details, String ... variables) { - return new Result(null,status,details,variables); + return new Result(null,status,details,variables); } /** @@ -153,19 +153,19 @@ public class Result { * @return */ public static Result err(Result pdr) { - return new Result(null,pdr.status,pdr.details,pdr.variables); - } + return new Result(null,pdr.status,pdr.details,pdr.variables); + } /** * Create General Error from Exception * @param e * @return */ - public static Result err(Exception e) { - return new Result(null,ERR_General,e.getMessage(),EMPTY_VARS); - } + public static Result err(Exception e) { + return new Result(null,ERR_General,e.getMessage(),EMPTY_VARS); + } - /** + /** * Create a Status (usually non OK, with a details statement * @param value * @param status @@ -173,7 +173,7 @@ public class Result { * @return */ public static Result create(R value, int status, String details, String ... vars) { - return new Result(value,status,details,vars); + return new Result(value,status,details,vars); } /** @@ -184,18 +184,18 @@ public class Result { * @return */ public static Result create(R value, Result result) { - return new Result(value,result.status,result.details,result.variables); + return new Result(value,result.status,result.details,result.variables); } private static final int PARTIAL_CONTENT = 0x001; private static final int EMPTY_LIST = 0x002; /** - * AAF Specific problems, etc - * - * @author Jonathan - * - */ + * AAF Specific problems, etc + * + * @author Jonathan + * + */ /** * specialCondition is a bit field to enable multiple conditions, e.g. PARTIAL_CONTENT @@ -218,10 +218,10 @@ public class Result { */ public Result partialContent(boolean hasPartialContent) { if (hasPartialContent) { - specialCondition |= PARTIAL_CONTENT; - } else { - specialCondition &= (~PARTIAL_CONTENT); - } + specialCondition |= PARTIAL_CONTENT; + } else { + specialCondition &= (~PARTIAL_CONTENT); + } return this; } @@ -231,7 +231,7 @@ public class Result { * @return */ public boolean isEmpty() { - return (specialCondition & EMPTY_LIST) == EMPTY_LIST; + return (specialCondition & EMPTY_LIST) == EMPTY_LIST; } /** @@ -242,11 +242,11 @@ public class Result { * @return */ public Result emptyList(boolean emptyList) { - if (emptyList) { - specialCondition |= EMPTY_LIST; - } else { - specialCondition &= (~EMPTY_LIST); - } + if (emptyList) { + specialCondition |= EMPTY_LIST; + } else { + specialCondition &= (~EMPTY_LIST); + } return this; } @@ -257,7 +257,7 @@ public class Result { * @return */ public boolean isOK() { - return status == OK; + return status == OK; } /** @@ -266,7 +266,7 @@ public class Result { * @return */ public boolean notOK() { - return status != OK; + return status != OK; } /** @@ -275,7 +275,7 @@ public class Result { * @return */ public boolean isOKhasData() { - return status == OK && (specialCondition & EMPTY_LIST) != EMPTY_LIST; + return status == OK && (specialCondition & EMPTY_LIST) != EMPTY_LIST; } @@ -285,44 +285,44 @@ public class Result { * @return */ public boolean notOKorIsEmpty() { - return status != OK || (specialCondition & EMPTY_LIST) == EMPTY_LIST; + return status != OK || (specialCondition & EMPTY_LIST) == EMPTY_LIST; } @Override public String toString() { - if(status==0) { - return details; - } else { - StringBuilder sb = new StringBuilder(); - sb.append(status); - sb.append(':'); - sb.append(String.format(details,((Object[])variables))); - if(isEmpty()) { - sb.append("{empty}"); - } - if(value!=null) { - sb.append('-'); - sb.append(value.toString()); - } - return sb.toString(); - } + if(status==0) { + return details; + } else { + StringBuilder sb = new StringBuilder(); + sb.append(status); + sb.append(':'); + sb.append(String.format(details,((Object[])variables))); + if(isEmpty()) { + sb.append("{empty}"); + } + if(value!=null) { + sb.append('-'); + sb.append(value.toString()); + } + return sb.toString(); + } } public String errorString() { - StringBuilder sb = new StringBuilder(); - switch(status) { - case 1: sb.append("Security"); break; - case 2: sb.append("Denied"); break; - case 3: sb.append("Policy"); break; - case 4: sb.append("BadData"); break; - case 5: sb.append("NotImplemented"); break; - case 6: sb.append("NotFound"); break; - case 7: sb.append("AlreadyExists"); break; - case 8: sb.append("ActionNotComplete"); break; - default: sb.append("Error"); - } - sb.append(" - "); - sb.append(String.format(details, (Object[])variables)); - return sb.toString(); + StringBuilder sb = new StringBuilder(); + switch(status) { + case 1: sb.append("Security"); break; + case 2: sb.append("Denied"); break; + case 3: sb.append("Policy"); break; + case 4: sb.append("BadData"); break; + case 5: sb.append("NotImplemented"); break; + case 6: sb.append("NotFound"); break; + case 7: sb.append("AlreadyExists"); break; + case 8: sb.append("ActionNotComplete"); break; + default: sb.append("Error"); + } + sb.append(" - "); + sb.append(String.format(details, (Object[])variables)); + return sb.toString(); } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java index 17edae42..90857b42 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java @@ -35,172 +35,172 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.TimeTaken; public abstract class AbsData implements Iterable { - protected DataFile data; - protected TextIndex ti; - private File dataf,idxf,lockf; - private String name; - private char delim; - private int maxLineSize; - private int fieldOffset; - private int skipLines; - - public AbsData(File dataf,char sepChar, int maxLineSize, int fieldOffset) { - File dir = dataf.getParentFile(); - int dot = dataf.getName().lastIndexOf('.'); - name = dataf.getName().substring(0,dot); - - this.dataf=dataf; - this.delim = sepChar; - this.maxLineSize = maxLineSize; - this.fieldOffset = fieldOffset; - idxf = new File(dir,name.concat(".idx")); - lockf = new File(dir,name.concat(".lock")); - - - data = new DataFile(dataf,"r"); - ti = new TextIndex(idxf); - skipLines=0; - } - - public void skipLines(int lines) { - skipLines=lines; - } - - public String name() { - return name; - } - - public void open(AuthzTrans trans, long timeout) throws IOException { - TimeTaken tt = trans.start("Open Data File", Env.SUB); - boolean first = true; - try { - if(!dataf.exists()) { - throw new FileNotFoundException("Data File Missing:" + dataf.getCanonicalPath()); - } - long begin = System.currentTimeMillis(); - long end = begin+timeout; - boolean exists; - while((exists=lockf.exists()) && beginidxf.lastModified()) { - trans.warn().log(idxf.getAbsolutePath(),"is missing, empty or out of date, creating"); - RandomAccessFile raf = new RandomAccessFile(lockf, "rw"); - try { - ti.create(trans, data, maxLineSize, delim, fieldOffset, skipLines); - if(!idxf.exists() || (idxf.length()==0 && dataf.length()!=0)) { - throw new IOException("Data Index File did not create correctly"); - } - } finally { - raf.close(); - lockf.delete(); - } - } - } - - public void close(AuthzTrans trans) throws IOException { - ti.close(); - data.close(); - } - - public class Reuse { - public Token tokenData; - private Field fieldData; - - private Reuse(int size,char delim) { - tokenData = data.new Token(size); - fieldData = tokenData.new Field(delim); - } - - public void reset() { - getFieldData().reset(); - } - - public void pos(int rec) { - getFieldData().reset(); - tokenData.pos(rec); - } - - public String next() { - return getFieldData().next(); - } - - public String at(int field) { - return getFieldData().at(field); - } - - public String atToEnd(int field) { - return getFieldData().atToEnd(field); - } - - public Field getFieldData() { - return fieldData; - } - } - - public Reuse reuse() { - return new Reuse(maxLineSize,delim); - } - - public Iter iterator() { - return new Iter(); - } - - public class Iter implements Iterator { - private Reuse reuse; - private org.onap.aaf.auth.local.TextIndex.Iter tii; - - public Iter() { - reuse = reuse(); - tii = ti.new Iter(); - } - - @Override - public boolean hasNext() { - return tii.hasNext(); - } - - @Override - public String next() { - if(!hasNext()) { - throw new NoSuchElementException(); - } - reuse.reset(); - int rec = tii.next(); - reuse.pos(rec); - return reuse.at(0); - } - - @Override - public void remove() { - // read only - } - } + protected DataFile data; + protected TextIndex ti; + private File dataf,idxf,lockf; + private String name; + private char delim; + private int maxLineSize; + private int fieldOffset; + private int skipLines; + + public AbsData(File dataf,char sepChar, int maxLineSize, int fieldOffset) { + File dir = dataf.getParentFile(); + int dot = dataf.getName().lastIndexOf('.'); + name = dataf.getName().substring(0,dot); + + this.dataf=dataf; + this.delim = sepChar; + this.maxLineSize = maxLineSize; + this.fieldOffset = fieldOffset; + idxf = new File(dir,name.concat(".idx")); + lockf = new File(dir,name.concat(".lock")); + + + data = new DataFile(dataf,"r"); + ti = new TextIndex(idxf); + skipLines=0; + } + + public void skipLines(int lines) { + skipLines=lines; + } + + public String name() { + return name; + } + + public void open(AuthzTrans trans, long timeout) throws IOException { + TimeTaken tt = trans.start("Open Data File", Env.SUB); + boolean first = true; + try { + if(!dataf.exists()) { + throw new FileNotFoundException("Data File Missing:" + dataf.getCanonicalPath()); + } + long begin = System.currentTimeMillis(); + long end = begin+timeout; + boolean exists; + while((exists=lockf.exists()) && beginidxf.lastModified()) { + trans.warn().log(idxf.getAbsolutePath(),"is missing, empty or out of date, creating"); + RandomAccessFile raf = new RandomAccessFile(lockf, "rw"); + try { + ti.create(trans, data, maxLineSize, delim, fieldOffset, skipLines); + if(!idxf.exists() || (idxf.length()==0 && dataf.length()!=0)) { + throw new IOException("Data Index File did not create correctly"); + } + } finally { + raf.close(); + lockf.delete(); + } + } + } + + public void close(AuthzTrans trans) throws IOException { + ti.close(); + data.close(); + } + + public class Reuse { + public Token tokenData; + private Field fieldData; + + private Reuse(int size,char delim) { + tokenData = data.new Token(size); + fieldData = tokenData.new Field(delim); + } + + public void reset() { + getFieldData().reset(); + } + + public void pos(int rec) { + getFieldData().reset(); + tokenData.pos(rec); + } + + public String next() { + return getFieldData().next(); + } + + public String at(int field) { + return getFieldData().at(field); + } + + public String atToEnd(int field) { + return getFieldData().atToEnd(field); + } + + public Field getFieldData() { + return fieldData; + } + } + + public Reuse reuse() { + return new Reuse(maxLineSize,delim); + } + + public Iter iterator() { + return new Iter(); + } + + public class Iter implements Iterator { + private Reuse reuse; + private org.onap.aaf.auth.local.TextIndex.Iter tii; + + public Iter() { + reuse = reuse(); + tii = ti.new Iter(); + } + + @Override + public boolean hasNext() { + return tii.hasNext(); + } + + @Override + public String next() { + if(!hasNext()) { + throw new NoSuchElementException(); + } + reuse.reset(); + int rec = tii.next(); + reuse.pos(rec); + return reuse.at(0); + } + + @Override + public void remove() { + // read only + } + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java index bb9fb1fd..7e420df4 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java @@ -32,159 +32,159 @@ import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; public class DataFile { - private RandomAccessFile rafile; - private FileChannel channel; - public MappedByteBuffer mapBuff; - private final File file; - private final String access; - - public DataFile(File file, String access) { - this.file = file; - this.access = access; - } - public void open() throws IOException { - if(!file.exists()) throw new FileNotFoundException(); - rafile = new RandomAccessFile(file,access); - channel = rafile.getChannel(); - mapBuff = channel.map("r".equals(access)?MapMode.READ_ONLY:MapMode.READ_WRITE,0,channel.size()); - } - public boolean isOpened() { - return mapBuff!=null; - } - public void close() throws IOException { - if(channel!=null){ - channel.close(); - } - if(rafile!=null) { - rafile.close(); - } - mapBuff = null; - } + private RandomAccessFile rafile; + private FileChannel channel; + public MappedByteBuffer mapBuff; + private final File file; + private final String access; + + public DataFile(File file, String access) { + this.file = file; + this.access = access; + } + public void open() throws IOException { + if(!file.exists()) throw new FileNotFoundException(); + rafile = new RandomAccessFile(file,access); + channel = rafile.getChannel(); + mapBuff = channel.map("r".equals(access)?MapMode.READ_ONLY:MapMode.READ_WRITE,0,channel.size()); + } + public boolean isOpened() { + return mapBuff!=null; + } + public void close() throws IOException { + if(channel!=null){ + channel.close(); + } + if(rafile!=null) { + rafile.close(); + } + mapBuff = null; + } - public long size() throws IOException { - return channel==null?0:channel.size(); - } + public long size() throws IOException { + return channel==null?0:channel.size(); + } - private synchronized int load(Token t) { - int len = Math.min(mapBuff.limit()-t.next,t.buff.length); - if(len>0) { - mapBuff.position(t.next); - mapBuff.get(t.buff,0,len); - } - return len<0?0:len; - } - - public class Token { - private byte[] buff; - int pos, next, end; - - public Token(int size) { - buff = new byte[size]; - pos = next = end = 0; - } - - public boolean pos(int to) { - pos = next = to; - return (end=load(this))>0; - } - - public boolean nextLine() { - end = load(this); - pos = next; - for(int i=0;i0) { + mapBuff.position(t.next); + mapBuff.get(t.buff,0,len); + } + return len<0?0:len; + } + + public class Token { + private byte[] buff; + int pos, next, end; + + public Token(int size) { + buff = new byte[size]; + pos = next = end = 0; + } + + public boolean pos(int to) { + pos = next = to; + return (end=load(this))>0; + } + + public boolean nextLine() { + end = load(this); + pos = next; + for(int i=0;i=end)return null; - int start = idx; - byte c=0; - int endStr = -1; - while(idx=end)return null; + int start = idx; + byte c=0; + int endStr = -1; + while(idx=end)?1:0))); - } + public String at(int fieldOffset) { + int start; + byte c=0; + for(int count = idx = start = 0; idx=end)?1:0))); + } - } + } - public int pos() { - return pos; - } - } + public int pos() { + return pos; + } + } - public File file() { - return file; - } - + public File file() { + return file; + } + } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java index 39225f74..bb1b6117 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java @@ -39,223 +39,223 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.Trans; public class TextIndex { - private static final int REC_SIZE=8; - - private File file; - private DataFile dataFile=null; - - public TextIndex(File theFile) { - file = theFile; - } - - public void open() throws IOException { - dataFile = new DataFile(file,"r"); - dataFile.open(); - } - - public void close() throws IOException { - if(dataFile!=null) { - dataFile.close(); - dataFile=null; - } - } + private static final int REC_SIZE=8; + + private File file; + private DataFile dataFile=null; + + public TextIndex(File theFile) { + file = theFile; + } + + public void open() throws IOException { + dataFile = new DataFile(file,"r"); + dataFile.open(); + } + + public void close() throws IOException { + if(dataFile!=null) { + dataFile.close(); + dataFile=null; + } + } - public int find(Object key, AbsData.Reuse reuse, int offset) throws IOException { - return find(key,reuse.tokenData,reuse.getFieldData(),offset); - } - - public int find(Object key, DataFile.Token dtok, Field df, int offset) throws IOException { - if(dataFile==null) { - throw new IOException("File not opened"); - } - long hash = hashToLong(key.hashCode()); - int min=0, max = (int)(dataFile.size()/REC_SIZE); - Token ttok = dataFile.new Token(REC_SIZE); - IntBuffer tib = ttok.getIntBuffer(); - long lhash; - int curr; - while((max-min)>100) { - ttok.pos((curr=(min+(max-min)/2))*REC_SIZE); - tib.rewind(); - lhash = hashToLong(tib.get()); - if(lhashhash) { - max=curr-1; - } else { - min=curr-40; - max=curr+40; - break; - } - } - - List entries = new ArrayList<>(); - for(int i=min;i<=max;++i) { - ttok.pos(i*REC_SIZE); - tib.rewind(); - lhash = hashToLong(tib.get()); - if(lhash==hash) { - entries.add(tib.get()); - } else if(lhash>hash) { - break; - } - } - - for(Integer i : entries) { - dtok.pos(i); - if(df.at(offset).equals(key)) { - return i; - } - } - return -1; - } - + public int find(Object key, AbsData.Reuse reuse, int offset) throws IOException { + return find(key,reuse.tokenData,reuse.getFieldData(),offset); + } + + public int find(Object key, DataFile.Token dtok, Field df, int offset) throws IOException { + if(dataFile==null) { + throw new IOException("File not opened"); + } + long hash = hashToLong(key.hashCode()); + int min=0, max = (int)(dataFile.size()/REC_SIZE); + Token ttok = dataFile.new Token(REC_SIZE); + IntBuffer tib = ttok.getIntBuffer(); + long lhash; + int curr; + while((max-min)>100) { + ttok.pos((curr=(min+(max-min)/2))*REC_SIZE); + tib.rewind(); + lhash = hashToLong(tib.get()); + if(lhashhash) { + max=curr-1; + } else { + min=curr-40; + max=curr+40; + break; + } + } + + List entries = new ArrayList<>(); + for(int i=min;i<=max;++i) { + ttok.pos(i*REC_SIZE); + tib.rewind(); + lhash = hashToLong(tib.get()); + if(lhash==hash) { + entries.add(tib.get()); + } else if(lhash>hash) { + break; + } + } + + for(Integer i : entries) { + dtok.pos(i); + if(df.at(offset).equals(key)) { + return i; + } + } + return -1; + } + - /* - * Have to change Bytes into a Long, to avoid the inevitable signs in the Hash - */ - private static long hashToLong(int hash) { - long rv; - if(hash<0) { - rv = 0xFFFFFFFFL & hash; - } else { - rv = hash; - } - return rv; - } - - public void create(final Trans trans,final DataFile data, int maxLine, char delim, int fieldOffset, int skipLines) throws IOException { - FileChannel fos; - - List list = new LinkedList<>(); // Some hashcodes will double... DO NOT make a set - TimeTaken tt2 = trans.start("Open Files", Env.SUB); - RandomAccessFile raf=null; - try { - try { - raf = new RandomAccessFile(file,"rw"); - raf.setLength(0L); - fos = raf.getChannel(); - } finally { - tt2.done(); - } - - try { - - Token t = data.new Token(maxLine); - Field f = t.new Field(delim); - - int count = 0; - if(skipLines>0) { - trans.info().log("Skipping",skipLines,"line"+(skipLines==1?" in":"s in"),data.file().getName()); - } - for(int i=0;i list = new LinkedList<>(); // Some hashcodes will double... DO NOT make a set + TimeTaken tt2 = trans.start("Open Files", Env.SUB); + RandomAccessFile raf=null; + try { + try { + raf = new RandomAccessFile(file,"rw"); + raf.setLength(0L); + fos = raf.getChannel(); + } finally { + tt2.done(); + } + + try { + + Token t = data.new Token(maxLine); + Field f = t.new Field(delim); + + int count = 0; + if(skipLines>0) { + trans.info().log("Skipping",skipLines,"line"+(skipLines==1?" in":"s in"),data.file().getName()); + } + for(int i=0;i { - public int hash, pos; - public Idx(Object obj, int pos) { - hash = obj.hashCode(); - this.pos = pos; - } - - @Override - public int compareTo(Idx ib) { - long a = hashToLong(hash); - long b = hashToLong(ib.hash); - return a>b?1:a { + public int hash, pos; + public Idx(Object obj, int pos) { + hash = obj.hashCode(); + this.pos = pos; + } + + @Override + public int compareTo(Idx ib) { + long a = hashToLong(hash); + long b = hashToLong(ib.hash); + return a>b?1:a 1, remove User from Owner - // if # of Owners = 1, changeOwner to X Remove Owner???? - boolean hasPermission(String user, String ns, String type, String instance, String action); - boolean inRole(String name); - - public String namespace() throws Exception; - public String id(); + // remove User from user/Role + // remove user from Admins + // if # of Owners > 1, remove User from Owner + // if # of Owners = 1, changeOwner to X Remove Owner???? + boolean hasPermission(String user, String ns, String type, String instance, String action); + boolean inRole(String name); + + public String namespace() throws Exception; + public String id(); } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java index 86875a4a..ff5d24c9 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java @@ -25,14 +25,14 @@ import java.util.List; import org.onap.aaf.auth.env.AuthzTrans; public interface Mailer { - public int sendEmail( - AuthzTrans trans, - boolean testMode, - String mailFrom, - List toList, - List ccList, - String subject, - String body, - Boolean urgent) throws OrganizationException; + public int sendEmail( + AuthzTrans trans, + boolean testMode, + String mailFrom, + List toList, + List ccList, + String subject, + String body, + Boolean urgent) throws OrganizationException; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java index bbae00ca..3ade1195 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java @@ -43,258 +43,258 @@ import org.onap.aaf.auth.env.AuthzTrans; * */ public interface Organization { - public static final String N_A = "n/a"; - - public interface Identity { - public String id(); - public String fullID() throws OrganizationException; // Fully Qualified ID (includes Domain of Organization) - public String type(); // Must be one of "IdentityTypes", see below - public Identity responsibleTo() throws OrganizationException; // Chain of Command, or Application ID Sponsor - public List delegate(); // Someone who has authority to act on behalf of Identity - public String email(); - public String fullName(); - public String firstName(); - /** - * If Responsible entity, then String returned is "null" meaning "no Objection". - * If String exists, it is the Policy objection text setup by the entity. - * @return - */ - public String mayOwn(); // Is id passed belong to a person suitable to be Responsible for content Management - public boolean isFound(); // Is Identity found in Identity stores - public boolean isPerson(); // Whether a Person or a Machine (App) - public Organization org(); // Organization of Identity - - } - - - /** - * Name of Organization, suitable for Logging - * @return - */ - public String getName(); - - /** - * Realm, for use in distinguishing IDs from different systems/Companies - * @return - */ - public String getRealm(); - - public boolean supportsRealm(String user); - - public void addSupportedRealm(String r); - - - - String getDomain(); - - /** - * Get Identity information based on userID - * - * @param id - * @return - */ - public Identity getIdentity(AuthzTrans trans, String id) throws OrganizationException; - - - /** - * Does the ID pass Organization Standards - * - * Return a Blank (empty) String if empty, otherwise, return a "\n" separated list of - * reasons why it fails - * - * @param id - * @return - */ - public String isValidID(AuthzTrans trans, String id); - - /** - * Return a Blank (empty) String if empty, otherwise, return a "\n" separated list of - * reasons why it fails - * - * Identity is passed in to allow policies regarding passwords that are the same as user ID - * - * any entries for "prev" imply a reset - * - * @param id - * @param password - * @return - */ - public String isValidPassword(final AuthzTrans trans, final String id, final String password, final String ... prev); + public static final String N_A = "n/a"; + + public interface Identity { + public String id(); + public String fullID() throws OrganizationException; // Fully Qualified ID (includes Domain of Organization) + public String type(); // Must be one of "IdentityTypes", see below + public Identity responsibleTo() throws OrganizationException; // Chain of Command, or Application ID Sponsor + public List delegate(); // Someone who has authority to act on behalf of Identity + public String email(); + public String fullName(); + public String firstName(); + /** + * If Responsible entity, then String returned is "null" meaning "no Objection". + * If String exists, it is the Policy objection text setup by the entity. + * @return + */ + public String mayOwn(); // Is id passed belong to a person suitable to be Responsible for content Management + public boolean isFound(); // Is Identity found in Identity stores + public boolean isPerson(); // Whether a Person or a Machine (App) + public Organization org(); // Organization of Identity + + } + + + /** + * Name of Organization, suitable for Logging + * @return + */ + public String getName(); + + /** + * Realm, for use in distinguishing IDs from different systems/Companies + * @return + */ + public String getRealm(); + + public boolean supportsRealm(String user); + + public void addSupportedRealm(String r); + + + + String getDomain(); + + /** + * Get Identity information based on userID + * + * @param id + * @return + */ + public Identity getIdentity(AuthzTrans trans, String id) throws OrganizationException; + + + /** + * Does the ID pass Organization Standards + * + * Return a Blank (empty) String if empty, otherwise, return a "\n" separated list of + * reasons why it fails + * + * @param id + * @return + */ + public String isValidID(AuthzTrans trans, String id); + + /** + * Return a Blank (empty) String if empty, otherwise, return a "\n" separated list of + * reasons why it fails + * + * Identity is passed in to allow policies regarding passwords that are the same as user ID + * + * any entries for "prev" imply a reset + * + * @param id + * @param password + * @return + */ + public String isValidPassword(final AuthzTrans trans, final String id, final String password, final String ... prev); + + /** + * Return a list of Strings denoting Organization Password Rules, suitable for posting on a WebPage with

+ */ + public String[] getPasswordRules(); + + /** + * + * @param id + * @return + */ + public boolean isValidCred(final AuthzTrans trans, final String id); + + /** + * If response is Null, then it is valid. Otherwise, the Organization specific reason is returned. + * + * @param trans + * @param policy + * @param executor + * @param vars + * @return + * @throws OrganizationException + */ + public String validate(AuthzTrans trans, Policy policy, Executor executor, String ... vars) throws OrganizationException; /** - * Return a list of Strings denoting Organization Password Rules, suitable for posting on a WebPage with

- */ - public String[] getPasswordRules(); - - /** - * - * @param id - * @return - */ - public boolean isValidCred(final AuthzTrans trans, final String id); - - /** - * If response is Null, then it is valid. Otherwise, the Organization specific reason is returned. - * - * @param trans - * @param policy - * @param executor - * @param vars - * @return - * @throws OrganizationException - */ - public String validate(AuthzTrans trans, Policy policy, Executor executor, String ... vars) throws OrganizationException; - - /** - * Does your Company distinguish essential permission structures by kind of Identity? - * i.e. Employee, Contractor, Vendor - * @return - */ - public Set getIdentityTypes(); - - public enum Notify { - Approval(1), - PasswordExpiration(2), + * Does your Company distinguish essential permission structures by kind of Identity? + * i.e. Employee, Contractor, Vendor + * @return + */ + public Set getIdentityTypes(); + + public enum Notify { + Approval(1), + PasswordExpiration(2), RoleExpiration(3); - final int id; - Notify(int id) {this.id = id;} - public int getValue() {return id;} - public static Notify from(int type) { - for(Notify t : Notify.values()) { - if(t.id==type) { - return t; - } - } - return null; - } - } - - public enum Response{ - OK, - ERR_NotImplemented, - ERR_UserNotExist, - ERR_NotificationFailure, - }; - - public enum Expiration { - Password, - TempPassword, - Future, - UserInRole, - UserDelegate, - ExtendPassword - } - - public enum Policy { - CHANGE_JOB, - LEFT_COMPANY, - CREATE_MECHID, - CREATE_MECHID_BY_PERM_ONLY, - OWNS_MECHID, - AS_RESPONSIBLE, - MAY_EXTEND_CRED_EXPIRES, - MAY_APPLY_DEFAULT_REALM - } - - /** - * Notify a User of Action or Info - * - * @param type - * @param url - * @param users (separated by commas) - * @param ccs (separated by commas) - * @param summary - */ + final int id; + Notify(int id) {this.id = id;} + public int getValue() {return id;} + public static Notify from(int type) { + for(Notify t : Notify.values()) { + if(t.id==type) { + return t; + } + } + return null; + } + } + + public enum Response{ + OK, + ERR_NotImplemented, + ERR_UserNotExist, + ERR_NotificationFailure, + }; + + public enum Expiration { + Password, + TempPassword, + Future, + UserInRole, + UserDelegate, + ExtendPassword + } + + public enum Policy { + CHANGE_JOB, + LEFT_COMPANY, + CREATE_MECHID, + CREATE_MECHID_BY_PERM_ONLY, + OWNS_MECHID, + AS_RESPONSIBLE, + MAY_EXTEND_CRED_EXPIRES, + MAY_APPLY_DEFAULT_REALM + } + + /** + * Notify a User of Action or Info + * + * @param type + * @param url + * @param users (separated by commas) + * @param ccs (separated by commas) + * @param summary + */ public Response notify(AuthzTrans trans, Notify type, String url, String ids[], String ccs[], String summary, Boolean urgent); - /** - * (more) generic way to send an email - * - * @param toList - * @param ccList - * @param subject - * @param body - * @param urgent - */ - - public int sendEmail(AuthzTrans trans, List toList, List ccList, String subject, String body, Boolean urgent) throws OrganizationException; - - /** - * whenToValidate - * - * Authz support services will ask the Organization Object at startup when it should - * kickoff Validation processes given particular types. - * - * This allows the Organization to express Policy - * - * Turn off Validation behavior by returning "null" - * - */ - public Date whenToValidate(Notify type, Date lastValidated); - - - /** - * Expiration - * - * Given a Calendar item of Start (or now), set the Expiration Date based on the Policy - * based on type. - * - * For instance, "Passwords expire in 3 months" - * - * The Extra Parameter is used by certain Orgs. - * - * For Password, the extra is UserID, so it can check the User Type - * - * @param gc - * @param exp - * @return - */ - public GregorianCalendar expiration(GregorianCalendar gc, Expiration exp, String ... extra); - - /** - * Get Email Warning timing policies - * @return - */ - public EmailWarnings emailWarningPolicy(); - - /** - * - * @param trans - * @param user - * @return - */ - public List getApprovers(AuthzTrans trans, String user) throws OrganizationException ; - - /* - * - * @param user - * @param type - * @param users - * @return - public Response notifyRequest(AuthzTrans trans, String user, Approval type, List approvers); - */ - - /** - * - * @return - */ - public String getApproverType(); - - /* - * startOfDay - define for company what hour of day business starts (specifically for password and other expiration which - * were set by Date only.) - * - * @return - */ - public int startOfDay(); + /** + * (more) generic way to send an email + * + * @param toList + * @param ccList + * @param subject + * @param body + * @param urgent + */ + + public int sendEmail(AuthzTrans trans, List toList, List ccList, String subject, String body, Boolean urgent) throws OrganizationException; + + /** + * whenToValidate + * + * Authz support services will ask the Organization Object at startup when it should + * kickoff Validation processes given particular types. + * + * This allows the Organization to express Policy + * + * Turn off Validation behavior by returning "null" + * + */ + public Date whenToValidate(Notify type, Date lastValidated); + + + /** + * Expiration + * + * Given a Calendar item of Start (or now), set the Expiration Date based on the Policy + * based on type. + * + * For instance, "Passwords expire in 3 months" + * + * The Extra Parameter is used by certain Orgs. + * + * For Password, the extra is UserID, so it can check the User Type + * + * @param gc + * @param exp + * @return + */ + public GregorianCalendar expiration(GregorianCalendar gc, Expiration exp, String ... extra); + + /** + * Get Email Warning timing policies + * @return + */ + public EmailWarnings emailWarningPolicy(); + + /** + * + * @param trans + * @param user + * @return + */ + public List getApprovers(AuthzTrans trans, String user) throws OrganizationException ; + + /* + * + * @param user + * @param type + * @param users + * @return + public Response notifyRequest(AuthzTrans trans, String user, Approval type, List approvers); + */ + + /** + * + * @return + */ + public String getApproverType(); + + /* + * startOfDay - define for company what hour of day business starts (specifically for password and other expiration which + * were set by Date only.) + * + * @return + */ + public int startOfDay(); /** * implement this method to support any IDs that can have multiple entries in the cred table * NOTE: the combination of ID/expiration date/(encryption type when implemented) must be unique. - * Since expiration date is based on startOfDay for your company, you cannot create many - * creds for the same ID in the same day. + * Since expiration date is based on startOfDay for your company, you cannot create many + * creds for the same ID in the same day. * @param id * @return */ @@ -302,228 +302,228 @@ public interface Organization { boolean isTestEnv(); - public void setTestMode(boolean dryRun); - - public static final Organization NULL = new Organization() - { - private final GregorianCalendar gc = new GregorianCalendar(1900, 1, 1); - private final List nullList = new ArrayList<>(); - private final Set nullStringSet = new HashSet<>(); - private String[] nullStringArray = new String[0]; - private final Identity nullIdentity = new Identity() { - List nullUser = new ArrayList<>(); - @Override - public String type() { - return N_A; - } - - @Override - public String mayOwn() { - return N_A; // negative case - } - - @Override - public boolean isFound() { - return false; - } - - @Override - public String id() { - return N_A; - } - - @Override - public String fullID() { - return N_A; - } - - @Override - public String email() { - return N_A; - } - - @Override - public List delegate() { - return nullUser; - } - @Override - public String fullName() { - return N_A; - } - @Override - public Organization org() { - return NULL; - } - @Override - public String firstName() { - return N_A; - } - @Override - public boolean isPerson() { - return false; - } - - @Override - public Identity responsibleTo() { - return null; - } - }; - @Override - public String getName() { - return N_A; - } - - @Override - public String getRealm() { - return N_A; - } - - @Override - public boolean supportsRealm(String r) { - return false; - } - - @Override - public void addSupportedRealm(String r) { - } - - @Override - public String getDomain() { - return N_A; - } - - @Override - public Identity getIdentity(AuthzTrans trans, String id) { - return nullIdentity; - } - - @Override - public String isValidID(final AuthzTrans trans, String id) { - return N_A; - } - - @Override - public String isValidPassword(final AuthzTrans trans, final String user, final String password, final String... prev) { - return N_A; - } - - @Override - public Set getIdentityTypes() { - return nullStringSet; - } - - @Override - public Response notify(AuthzTrans trans, Notify type, String url, - String[] users, String[] ccs, String summary, Boolean urgent) { - return Response.ERR_NotImplemented; - } - - @Override - public int sendEmail(AuthzTrans trans, List toList, List ccList, - String subject, String body, Boolean urgent) throws OrganizationException { - return 0; - } - - @Override - public Date whenToValidate(Notify type, Date lastValidated) { - return gc.getTime(); - } - - @Override - public GregorianCalendar expiration(GregorianCalendar gc, - Expiration exp, String... extra) { - return gc; - } - - @Override - public List getApprovers(AuthzTrans trans, String user) - throws OrganizationException { - return nullList; - } - - @Override - public String getApproverType() { - return ""; - } - - @Override - public int startOfDay() { - return 0; - } - - @Override - public boolean canHaveMultipleCreds(String id) { - return false; - } - - @Override - public boolean isValidCred(final AuthzTrans trans, final String id) { - return false; - } - - @Override - public String validate(AuthzTrans trans, Policy policy, Executor executor, String ... vars) - throws OrganizationException { - return "Null Organization rejects all Policies"; - } - - @Override - public boolean isTestEnv() { - return false; - } - - @Override - public void setTestMode(boolean dryRun) { - } - - @Override - public EmailWarnings emailWarningPolicy() { - return new EmailWarnings() { - - @Override - public long credEmailInterval() - { - return 604800000L; // 7 days in millis 1000 * 86400 * 7 - } - - @Override - public long roleEmailInterval() - { - return 604800000L; // 7 days in millis 1000 * 86400 * 7 - } - - @Override - public long apprEmailInterval() { - return 259200000L; // 3 days in millis 1000 * 86400 * 3 - } - - @Override - public long credExpirationWarning() - { - return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds - } - - @Override - public long roleExpirationWarning() - { - return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds - } - - @Override - public long emailUrgentWarning() - { - return( 1209600000L ); // Two weeks, in milliseconds 1000 * 86400 * 14 in milliseconds - } - - }; - } - - @Override - public String[] getPasswordRules() { - return nullStringArray; - } - - }; + public void setTestMode(boolean dryRun); + + public static final Organization NULL = new Organization() + { + private final GregorianCalendar gc = new GregorianCalendar(1900, 1, 1); + private final List nullList = new ArrayList<>(); + private final Set nullStringSet = new HashSet<>(); + private String[] nullStringArray = new String[0]; + private final Identity nullIdentity = new Identity() { + List nullUser = new ArrayList<>(); + @Override + public String type() { + return N_A; + } + + @Override + public String mayOwn() { + return N_A; // negative case + } + + @Override + public boolean isFound() { + return false; + } + + @Override + public String id() { + return N_A; + } + + @Override + public String fullID() { + return N_A; + } + + @Override + public String email() { + return N_A; + } + + @Override + public List delegate() { + return nullUser; + } + @Override + public String fullName() { + return N_A; + } + @Override + public Organization org() { + return NULL; + } + @Override + public String firstName() { + return N_A; + } + @Override + public boolean isPerson() { + return false; + } + + @Override + public Identity responsibleTo() { + return null; + } + }; + @Override + public String getName() { + return N_A; + } + + @Override + public String getRealm() { + return N_A; + } + + @Override + public boolean supportsRealm(String r) { + return false; + } + + @Override + public void addSupportedRealm(String r) { + } + + @Override + public String getDomain() { + return N_A; + } + + @Override + public Identity getIdentity(AuthzTrans trans, String id) { + return nullIdentity; + } + + @Override + public String isValidID(final AuthzTrans trans, String id) { + return N_A; + } + + @Override + public String isValidPassword(final AuthzTrans trans, final String user, final String password, final String... prev) { + return N_A; + } + + @Override + public Set getIdentityTypes() { + return nullStringSet; + } + + @Override + public Response notify(AuthzTrans trans, Notify type, String url, + String[] users, String[] ccs, String summary, Boolean urgent) { + return Response.ERR_NotImplemented; + } + + @Override + public int sendEmail(AuthzTrans trans, List toList, List ccList, + String subject, String body, Boolean urgent) throws OrganizationException { + return 0; + } + + @Override + public Date whenToValidate(Notify type, Date lastValidated) { + return gc.getTime(); + } + + @Override + public GregorianCalendar expiration(GregorianCalendar gc, + Expiration exp, String... extra) { + return gc; + } + + @Override + public List getApprovers(AuthzTrans trans, String user) + throws OrganizationException { + return nullList; + } + + @Override + public String getApproverType() { + return ""; + } + + @Override + public int startOfDay() { + return 0; + } + + @Override + public boolean canHaveMultipleCreds(String id) { + return false; + } + + @Override + public boolean isValidCred(final AuthzTrans trans, final String id) { + return false; + } + + @Override + public String validate(AuthzTrans trans, Policy policy, Executor executor, String ... vars) + throws OrganizationException { + return "Null Organization rejects all Policies"; + } + + @Override + public boolean isTestEnv() { + return false; + } + + @Override + public void setTestMode(boolean dryRun) { + } + + @Override + public EmailWarnings emailWarningPolicy() { + return new EmailWarnings() { + + @Override + public long credEmailInterval() + { + return 604800000L; // 7 days in millis 1000 * 86400 * 7 + } + + @Override + public long roleEmailInterval() + { + return 604800000L; // 7 days in millis 1000 * 86400 * 7 + } + + @Override + public long apprEmailInterval() { + return 259200000L; // 3 days in millis 1000 * 86400 * 3 + } + + @Override + public long credExpirationWarning() + { + return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds + } + + @Override + public long roleExpirationWarning() + { + return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds + } + + @Override + public long emailUrgentWarning() + { + return( 1209600000L ); // Two weeks, in milliseconds 1000 * 86400 * 14 in milliseconds + } + + }; + } + + @Override + public String[] getPasswordRules() { + return nullStringArray; + } + + }; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationException.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationException.java index ed1d398b..347e2d35 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationException.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationException.java @@ -23,30 +23,30 @@ package org.onap.aaf.auth.org; public class OrganizationException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; - - public OrganizationException() { - super(); - } - - public OrganizationException(String message) { - super(message); - } - - public OrganizationException(Throwable cause) { - super(cause); - } - - public OrganizationException(String message, Throwable cause) { - super(message, cause); - } - - public OrganizationException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + public OrganizationException() { + super(); + } + + public OrganizationException(String message) { + super(message); + } + + public OrganizationException(Throwable cause) { + super(cause); + } + + public OrganizationException(String message, Throwable cause) { + super(message, cause); + } + + public OrganizationException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java index ffc79169..3b97d6f3 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java @@ -46,96 +46,96 @@ import org.onap.aaf.misc.env.impl.BasicEnv; * */ public class OrganizationFactory { - private static final String ORGANIZATION_DOT = "Organization."; - private static Organization defaultOrg = null; - private static Map orgs = new ConcurrentHashMap<>(); - public static Organization init(BasicEnv env) throws OrganizationException { - int idx = ORGANIZATION_DOT.length(); - Organization org,firstOrg = null; - - for(Entry es : env.getProperties().entrySet()) { - String key = es.getKey().toString(); - if(key.startsWith(ORGANIZATION_DOT)) { - org = obtain(env,key.substring(idx)); - if(firstOrg==null) { - firstOrg = org; - } - } - } - if(defaultOrg == null) { - defaultOrg = firstOrg; - } - return defaultOrg; - } - public static Organization obtain(Env env,final String theNS) throws OrganizationException { - String orgNS; - if(theNS.indexOf('@')>=0) { - orgNS=FQI.reverseDomain(theNS); - } else { - orgNS=theNS; - } - Organization org = orgs.get(orgNS); - if(org == null) { - env.debug().printf("Attempting to instantiate Organization %s\n",orgNS); + private static final String ORGANIZATION_DOT = "Organization."; + private static Organization defaultOrg = null; + private static Map orgs = new ConcurrentHashMap<>(); + public static Organization init(BasicEnv env) throws OrganizationException { + int idx = ORGANIZATION_DOT.length(); + Organization org,firstOrg = null; + + for(Entry es : env.getProperties().entrySet()) { + String key = es.getKey().toString(); + if(key.startsWith(ORGANIZATION_DOT)) { + org = obtain(env,key.substring(idx)); + if(firstOrg==null) { + firstOrg = org; + } + } + } + if(defaultOrg == null) { + defaultOrg = firstOrg; + } + return defaultOrg; + } + public static Organization obtain(Env env,final String theNS) throws OrganizationException { + String orgNS; + if(theNS.indexOf('@')>=0) { + orgNS=FQI.reverseDomain(theNS); + } else { + orgNS=theNS; + } + Organization org = orgs.get(orgNS); + if(org == null) { + env.debug().printf("Attempting to instantiate Organization %s\n",orgNS); - String orgClass = env.getProperty(ORGANIZATION_DOT+orgNS); - if(orgClass == null) { - env.warn().log("There is no Organization." + orgNS + " property"); - } else { - try { - Class orgCls = Class.forName(orgClass); - for(Organization o : orgs.values()) { - if(o.getClass().isAssignableFrom(orgCls)) { - org = o; - } - } - } catch (ClassNotFoundException e1) { - env.error().log(e1, orgClass + " is not on the Classpath."); - throw new OrganizationException(e1); - } - if(org==null) { - try { - @SuppressWarnings("unchecked") - Class cls = (Class) Class.forName(orgClass); - Constructor cnst = cls.getConstructor(Env.class,String.class); - org = cnst.newInstance(env,orgNS); - String other_realms = env.getProperty(orgNS+".also_supports"); - if(other_realms!=null) { - for(String r : Split.splitTrim(',', other_realms)) { - org.addSupportedRealm(r); - } - } - } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | - InstantiationException | IllegalAccessException | IllegalArgumentException | - InvocationTargetException e) { - env.error().log(e, "Error on Organization Construction"); - throw new OrganizationException(e); - } - } - orgs.put(orgNS, org); - boolean isDefault; - if((isDefault="true".equalsIgnoreCase(env.getProperty(orgNS+".default")))) { - defaultOrg = org; - } - env.init().printf("Instantiated %s with %s%s\n",orgNS,orgClass,(isDefault?" as default":"")); - } - if(org==null) { - if(defaultOrg!=null) { - org=defaultOrg; - orgs.put(orgNS, org); - } - } - } - - return org; - } + String orgClass = env.getProperty(ORGANIZATION_DOT+orgNS); + if(orgClass == null) { + env.warn().log("There is no Organization." + orgNS + " property"); + } else { + try { + Class orgCls = Class.forName(orgClass); + for(Organization o : orgs.values()) { + if(o.getClass().isAssignableFrom(orgCls)) { + org = o; + } + } + } catch (ClassNotFoundException e1) { + env.error().log(e1, orgClass + " is not on the Classpath."); + throw new OrganizationException(e1); + } + if(org==null) { + try { + @SuppressWarnings("unchecked") + Class cls = (Class) Class.forName(orgClass); + Constructor cnst = cls.getConstructor(Env.class,String.class); + org = cnst.newInstance(env,orgNS); + String other_realms = env.getProperty(orgNS+".also_supports"); + if(other_realms!=null) { + for(String r : Split.splitTrim(',', other_realms)) { + org.addSupportedRealm(r); + } + } + } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | + InstantiationException | IllegalAccessException | IllegalArgumentException | + InvocationTargetException e) { + env.error().log(e, "Error on Organization Construction"); + throw new OrganizationException(e); + } + } + orgs.put(orgNS, org); + boolean isDefault; + if((isDefault="true".equalsIgnoreCase(env.getProperty(orgNS+".default")))) { + defaultOrg = org; + } + env.init().printf("Instantiated %s with %s%s\n",orgNS,orgClass,(isDefault?" as default":"")); + } + if(org==null) { + if(defaultOrg!=null) { + org=defaultOrg; + orgs.put(orgNS, org); + } + } + } + + return org; + } - public static Organization get(AuthzTrans trans) throws OrganizationException { - String domain = FQI.reverseDomain(trans.user()); - Organization org = orgs.get(domain); - if(org==null) { - org = defaultOrg; // can be null, btw, unless set. - } - return org; - } + public static Organization get(AuthzTrans trans) throws OrganizationException { + String domain = FQI.reverseDomain(trans.user()); + Organization org = orgs.get(domain); + if(org==null) { + org = defaultOrg; // can be null, btw, unless set. + } + return org; + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java index 82a226ec..30924dd5 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java @@ -36,134 +36,134 @@ import org.onap.aaf.misc.env.Trans; * @param */ class Acceptor { - private List, List>>>> types; - List, List>>>> acceptable; - - public Acceptor(List, List>>>> types) { - this.types = types; - acceptable = new ArrayList<>(); - } - - private boolean eval(HttpCode code, String str, List props) { -// int plus = str.indexOf('+'); -// if(plus<0) { - boolean ok = false; - boolean any = false; - for(Pair, List>>> type : types) { - ok = true; - if(type.x.equals(str)) { - for(Iterator iter = props.iterator();ok && iter.hasNext();) { - ok = props(type,iter.next(),iter.next()); - } - if(ok) { - any = true; - acceptable.add(type); - } - } - } -// } else { // Handle Accepts with "+" as in application/xaml+xml -// int prev = str.indexOf('/')+1; -// String first = str.substring(0,prev); -// String nstr; -// while(prev!=0) { -// nstr = first + (plus<0?str.substring(prev):str.substring(prev,plus)); -// -// for(Pair, List>>> type : types) { -// if(type.x.equals(nstr)) { -// acceptable.add(type); -// return type; -// } -// } -// prev = plus+1; -// plus=str.indexOf('+', prev); -// }; -// } - return any; - } + private List, List>>>> types; + List, List>>>> acceptable; + + public Acceptor(List, List>>>> types) { + this.types = types; + acceptable = new ArrayList<>(); + } + + private boolean eval(HttpCode code, String str, List props) { +// int plus = str.indexOf('+'); +// if(plus<0) { + boolean ok = false; + boolean any = false; + for(Pair, List>>> type : types) { + ok = true; + if(type.x.equals(str)) { + for(Iterator iter = props.iterator();ok && iter.hasNext();) { + ok = props(type,iter.next(),iter.next()); + } + if(ok) { + any = true; + acceptable.add(type); + } + } + } +// } else { // Handle Accepts with "+" as in application/xaml+xml +// int prev = str.indexOf('/')+1; +// String first = str.substring(0,prev); +// String nstr; +// while(prev!=0) { +// nstr = first + (plus<0?str.substring(prev):str.substring(prev,plus)); +// +// for(Pair, List>>> type : types) { +// if(type.x.equals(nstr)) { +// acceptable.add(type); +// return type; +// } +// } +// prev = plus+1; +// plus=str.indexOf('+', prev); +// }; +// } + return any; + } - /** - * Evaluate Properties - * @param type - * @param tag - * @param value - * @return - */ - private boolean props(Pair, List>>> type, String tag, String value) { - boolean rv = false; - if(type.y!=null) { - for(Pair prop : type.y.y){ - if(tag.equals(prop.x)) { - if(tag.equals("charset")) { - return prop.x==null?false:prop.y.equals(value.toLowerCase()); // return True if Matched - } else if(tag.equals("version")) { - return prop.y.equals(new Version(value)); // Note: Version Class knows Minor Version encoding - } else if(tag.equals(Content.Q)) { // replace Q value - try { - type.y.y.get(0).y=Float.parseFloat(value); - } catch (NumberFormatException e) { - rv=false; // need to do something to make Sonar happy. But nothing to do. - } - return true; - } else { - return value.equals(prop.y); - } - } - } - } - return rv; - } + /** + * Evaluate Properties + * @param type + * @param tag + * @param value + * @return + */ + private boolean props(Pair, List>>> type, String tag, String value) { + boolean rv = false; + if(type.y!=null) { + for(Pair prop : type.y.y){ + if(tag.equals(prop.x)) { + if(tag.equals("charset")) { + return prop.x==null?false:prop.y.equals(value.toLowerCase()); // return True if Matched + } else if(tag.equals("version")) { + return prop.y.equals(new Version(value)); // Note: Version Class knows Minor Version encoding + } else if(tag.equals(Content.Q)) { // replace Q value + try { + type.y.y.get(0).y=Float.parseFloat(value); + } catch (NumberFormatException e) { + rv=false; // need to do something to make Sonar happy. But nothing to do. + } + return true; + } else { + return value.equals(prop.y); + } + } + } + } + return rv; + } - /** - * parse - * - * Note: I'm processing by index to avoid lots of memory creation, which speeds things - * up for this time critical section of code. - * @param code - * @param cntnt - * @return - */ - protected boolean parse(HttpCode code, String cntnt) { - byte bytes[] = cntnt.getBytes(); - - int cis,cie=-1,cend; - int sis,sie,send; - String name; - ArrayList props = new ArrayList<>(); - do { - // Clear these in case more than one Semi - props.clear(); // on loop, do not want mixed properties - name=null; - - cis = cie+1; // find comma start - while(ciscis && Character.isSpaceChar(bytes[cend-1]))--cend; - // Start SEMIS - sie=cis-1; - do { - sis = sie+1; // semi start is one after previous end - while(siscend || sie<0?cend:sie; // if the Semicolon is after the comma, or non-existent, use comma end, else keep - while(send>sis && Character.isSpaceChar(bytes[send-1]))--send; - if(name==null) { // first entry in Comma set is the name, not a property - name = new String(bytes,sis,send-sis); - } else { // We've looped past the first Semi, now process as properties - // If there are additional elements (more entities within Semi Colons) - // apply Properties - int eq = cntnt.indexOf('=',sis); - if(eq>sis && eq=cis); // End SEMI processing - // Now evaluate Comma set and return if true - if(eval(code,name,props))return true; // else loop again to check next comma - } while(cie>=0); // loop to next comma - return false; // didn't get even one match - } - + /** + * parse + * + * Note: I'm processing by index to avoid lots of memory creation, which speeds things + * up for this time critical section of code. + * @param code + * @param cntnt + * @return + */ + protected boolean parse(HttpCode code, String cntnt) { + byte bytes[] = cntnt.getBytes(); + + int cis,cie=-1,cend; + int sis,sie,send; + String name; + ArrayList props = new ArrayList<>(); + do { + // Clear these in case more than one Semi + props.clear(); // on loop, do not want mixed properties + name=null; + + cis = cie+1; // find comma start + while(ciscis && Character.isSpaceChar(bytes[cend-1]))--cend; + // Start SEMIS + sie=cis-1; + do { + sis = sie+1; // semi start is one after previous end + while(siscend || sie<0?cend:sie; // if the Semicolon is after the comma, or non-existent, use comma end, else keep + while(send>sis && Character.isSpaceChar(bytes[send-1]))--send; + if(name==null) { // first entry in Comma set is the name, not a property + name = new String(bytes,sis,send-sis); + } else { // We've looped past the first Semi, now process as properties + // If there are additional elements (more entities within Semi Colons) + // apply Properties + int eq = cntnt.indexOf('=',sis); + if(eq>sis && eq=cis); // End SEMI processing + // Now evaluate Comma set and return if true + if(eval(code,name,props))return true; // else loop again to check next comma + } while(cie>=0); // loop to next comma + return false; // didn't get even one match + } + } \ No newline at end of file diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java index 96349aed..53511b40 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java @@ -65,498 +65,498 @@ import org.onap.aaf.misc.env.Trans; * */ public class CachingFileAccess extends HttpCode { - public static void setEnv(Store store, String[] args) { - for(int i=0;i typeMap; - private final NavigableMap content; - private final Set attachOnly; - public final static String CFA_WEB_PATH = "aaf_cfa_web_path"; - // when to re-validate from file - // Re validating means comparing the Timestamp on the disk, and seeing it has changed. Cache is not marked - // dirty unless file has changed, but it still makes File IO, which for some kinds of cached data, i.e. - // deployed GUI elements is unnecessary, and wastes time. - // This parameter exists to cover the cases where data can be more volatile, so the user can choose how often the - // File IO will be accessed, based on probability of change. "0", of course, means, check every time. - private final static String CFA_CACHE_CHECK_INTERVAL = "aaf_cfa_cache_check_interval"; - private final static String CFA_MAX_SIZE = "aaf_cfa_max_size"; // Cache size limit - private final static String CFA_CLEAR_COMMAND = "aaf_cfa_clear_command"; + public static void setEnv(Store store, String[] args) { + for(int i=0;i typeMap; + private final NavigableMap content; + private final Set attachOnly; + public final static String CFA_WEB_PATH = "aaf_cfa_web_path"; + // when to re-validate from file + // Re validating means comparing the Timestamp on the disk, and seeing it has changed. Cache is not marked + // dirty unless file has changed, but it still makes File IO, which for some kinds of cached data, i.e. + // deployed GUI elements is unnecessary, and wastes time. + // This parameter exists to cover the cases where data can be more volatile, so the user can choose how often the + // File IO will be accessed, based on probability of change. "0", of course, means, check every time. + private final static String CFA_CACHE_CHECK_INTERVAL = "aaf_cfa_cache_check_interval"; + private final static String CFA_MAX_SIZE = "aaf_cfa_max_size"; // Cache size limit + private final static String CFA_CLEAR_COMMAND = "aaf_cfa_clear_command"; - // Note: can be null without a problem, but included - // to tie in with existing Logging. - public LogTarget logT = null; - public long checkInterval; // = 600000L; // only check if not hit in 10 mins by default - public int maxItemSize; // = 512000; // max file 500k - private Timer timer; - private String web_path; - // A command key is set in the Properties, preferably changed on deployment. - // it is compared at the beginning of the path, and if so, it is assumed to issue certain commands - // It's purpose is to protect, to some degree the command, even though it is HTTP, allowing - // local batch files to, for instance, clear caches on resetting of files. - private String clear_command; - - public CachingFileAccess(EnvJAXB env, String ... args) throws IOException { - super(null,"Caching File Access"); - setEnv(env,args); - content = new ConcurrentSkipListMap<>(); // multi-thread changes possible + // Note: can be null without a problem, but included + // to tie in with existing Logging. + public LogTarget logT = null; + public long checkInterval; // = 600000L; // only check if not hit in 10 mins by default + public int maxItemSize; // = 512000; // max file 500k + private Timer timer; + private String web_path; + // A command key is set in the Properties, preferably changed on deployment. + // it is compared at the beginning of the path, and if so, it is assumed to issue certain commands + // It's purpose is to protect, to some degree the command, even though it is HTTP, allowing + // local batch files to, for instance, clear caches on resetting of files. + private String clear_command; + + public CachingFileAccess(EnvJAXB env, String ... args) throws IOException { + super(null,"Caching File Access"); + setEnv(env,args); + content = new ConcurrentSkipListMap<>(); // multi-thread changes possible - attachOnly = new HashSet<>(); // short, unchanged + attachOnly = new HashSet<>(); // short, unchanged - typeMap = new TreeMap<>(); // Structure unchanged after Construction - typeMap.put("ico","image/icon"); - typeMap.put("html","text/html"); - typeMap.put("css","text/css"); - typeMap.put("js","text/javascript"); - typeMap.put("txt","text/plain"); - typeMap.put("xml","text/xml"); - typeMap.put("xsd","text/xml"); - attachOnly.add("xsd"); - typeMap.put("crl", "application/x-pkcs7-crl"); - typeMap.put("appcache","text/cache-manifest"); + typeMap = new TreeMap<>(); // Structure unchanged after Construction + typeMap.put("ico","image/icon"); + typeMap.put("html","text/html"); + typeMap.put("css","text/css"); + typeMap.put("js","text/javascript"); + typeMap.put("txt","text/plain"); + typeMap.put("xml","text/xml"); + typeMap.put("xsd","text/xml"); + attachOnly.add("xsd"); + typeMap.put("crl", "application/x-pkcs7-crl"); + typeMap.put("appcache","text/cache-manifest"); - typeMap.put("json","text/json"); - typeMap.put("ogg", "audio/ogg"); - typeMap.put("jpg","image/jpeg"); - typeMap.put("gif","image/gif"); - typeMap.put("png","image/png"); - typeMap.put("svg","image/svg+xml"); - typeMap.put("jar","application/x-java-applet"); - typeMap.put("jnlp", "application/x-java-jnlp-file"); - typeMap.put("class", "application/java"); - typeMap.put("props", "text/plain"); - typeMap.put("jks", "application/octet-stream"); - - timer = new Timer("Caching Cleanup",true); - timer.schedule(new Cleanup(content,500),60000,60000); - - // Property params - web_path = env.get(env.staticSlot(CFA_WEB_PATH)); - env.init().log("CachingFileAccess path: " + new File(web_path).getCanonicalPath()); - Object obj; - obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L); // Default is 10 mins - if(obj instanceof Long) {checkInterval=(Long)obj; - } else {checkInterval=Long.parseLong((String)obj);} - - obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000); // Default is max file 500k - if(obj instanceof Integer) {maxItemSize=(Integer)obj; - } else {maxItemSize =Integer.parseInt((String)obj);} - - clear_command = env.getProperty(CFA_CLEAR_COMMAND,null); - } + typeMap.put("json","text/json"); + typeMap.put("ogg", "audio/ogg"); + typeMap.put("jpg","image/jpeg"); + typeMap.put("gif","image/gif"); + typeMap.put("png","image/png"); + typeMap.put("svg","image/svg+xml"); + typeMap.put("jar","application/x-java-applet"); + typeMap.put("jnlp", "application/x-java-jnlp-file"); + typeMap.put("class", "application/java"); + typeMap.put("props", "text/plain"); + typeMap.put("jks", "application/octet-stream"); + + timer = new Timer("Caching Cleanup",true); + timer.schedule(new Cleanup(content,500),60000,60000); + + // Property params + web_path = env.get(env.staticSlot(CFA_WEB_PATH)); + env.init().log("CachingFileAccess path: " + new File(web_path).getCanonicalPath()); + Object obj; + obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L); // Default is 10 mins + if(obj instanceof Long) {checkInterval=(Long)obj; + } else {checkInterval=Long.parseLong((String)obj);} + + obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000); // Default is max file 500k + if(obj instanceof Integer) {maxItemSize=(Integer)obj; + } else {maxItemSize =Integer.parseInt((String)obj);} + + clear_command = env.getProperty(CFA_CLEAR_COMMAND,null); + } - + - @Override - public void handle(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException { - String key = pathParam(req, ":key"); - String cmd = pathParam(req,":cmd"); - if(key.equals(clear_command)) { - resp.setHeader("Content-Type",typeMap.get("txt")); - if("clear".equals(cmd)) { - content.clear(); - resp.setStatus(200/*HttpStatus.OK_200*/); - } else { - resp.setStatus(400/*HttpStatus.BAD_REQUEST_400 */); - } - return; - } - Content c = load(logT , web_path,cmd!=null && cmd.length()>0?key+'/'+cmd:key, null, checkInterval); - if(c.attachmentOnly) { - resp.setHeader("Content-disposition", "attachment"); - } - c.setHeader(resp); - c.write(resp.getOutputStream()); - trans.checkpoint(req.getPathInfo()); - } + @Override + public void handle(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException { + String key = pathParam(req, ":key"); + String cmd = pathParam(req,":cmd"); + if(key.equals(clear_command)) { + resp.setHeader("Content-Type",typeMap.get("txt")); + if("clear".equals(cmd)) { + content.clear(); + resp.setStatus(200/*HttpStatus.OK_200*/); + } else { + resp.setStatus(400/*HttpStatus.BAD_REQUEST_400 */); + } + return; + } + Content c = load(logT , web_path,cmd!=null && cmd.length()>0?key+'/'+cmd:key, null, checkInterval); + if(c.attachmentOnly) { + resp.setHeader("Content-disposition", "attachment"); + } + c.setHeader(resp); + c.write(resp.getOutputStream()); + trans.checkpoint(req.getPathInfo()); + } - public String webPath() { - return web_path; - } - - /** - * Reset the Cleanup size and interval - * - * The size and interval when started are 500 items (memory size unknown) checked every minute in a background thread. - * - * @param size - * @param interval - */ - public void cleanupParams(int size, long interval) { - timer.cancel(); - timer = new Timer(); - timer.schedule(new Cleanup(content,size), interval, interval); - } - + public String webPath() { + return web_path; + } + + /** + * Reset the Cleanup size and interval + * + * The size and interval when started are 500 items (memory size unknown) checked every minute in a background thread. + * + * @param size + * @param interval + */ + public void cleanupParams(int size, long interval) { + timer.cancel(); + timer = new Timer(); + timer.schedule(new Cleanup(content,size), interval, interval); + } + - - /** - * Load a file, first checking cache - * - * - * @param logTarget - logTarget can be null (won't log) - * @param dataRoot - data root storage directory - * @param key - relative File Path - * @param mediaType - what kind of file is it. If null, will check via file extension - * @param timeCheck - "-1" will take system default - Otherwise, will compare "now" + timeCheck(Millis) before looking at File mod - * @return - * @throws IOException - */ - public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException { - long timeCheck = _timeCheck; - if(timeCheck<0) { - timeCheck=checkInterval; // if time < 0, then use default - } - boolean isRoot; - String fileName; - if("-".equals(key)) { - fileName = dataRoot; - isRoot = true; - } else { - fileName=dataRoot + '/' + key; - isRoot = false; - } - Content c = content.get(key); - long systime = System.currentTimeMillis(); - File f=null; - if(c!=null) { - // Don't check every hit... only after certain time value - if(c.date < systime + timeCheck) { - f = new File(fileName); - if(f.lastModified()>c.date) { - c=null; - } - } - } - if(c==null) { - if(logTarget!=null) { - logTarget.log("File Read: ",key); - } - - if(f==null){ - f = new File(fileName); - } - boolean cacheMe; - if(f.exists()) { - if(f.isDirectory()) { - cacheMe = false; - c = new DirectoryContent(f,isRoot); - } else { - if(f.length() > maxItemSize) { - c = new DirectFileContent(f); - cacheMe = false; - } else { - c = new CachedContent(f); - cacheMe = checkInterval>0; - } - - if(mediaType==null) { // determine from file Ending - int idx = key.lastIndexOf('.'); - String subkey = key.substring(++idx); - if((c.contentType = idx<0?null:typeMap.get(subkey))==null) { - // if nothing else, just set to default type... - c.contentType = "application/octet-stream"; - } - c.attachmentOnly = attachOnly.contains(subkey); - } else { - c.contentType=mediaType; - c.attachmentOnly = false; - } - - c.date = f.lastModified(); - - if(cacheMe) { - content.put(key, c); - } - } - } else { - c=NULL; - } - } else { - if(logTarget!=null)logTarget.log("Cache Read: ",key); - } + + /** + * Load a file, first checking cache + * + * + * @param logTarget - logTarget can be null (won't log) + * @param dataRoot - data root storage directory + * @param key - relative File Path + * @param mediaType - what kind of file is it. If null, will check via file extension + * @param timeCheck - "-1" will take system default - Otherwise, will compare "now" + timeCheck(Millis) before looking at File mod + * @return + * @throws IOException + */ + public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException { + long timeCheck = _timeCheck; + if(timeCheck<0) { + timeCheck=checkInterval; // if time < 0, then use default + } + boolean isRoot; + String fileName; + if("-".equals(key)) { + fileName = dataRoot; + isRoot = true; + } else { + fileName=dataRoot + '/' + key; + isRoot = false; + } + Content c = content.get(key); + long systime = System.currentTimeMillis(); + File f=null; + if(c!=null) { + // Don't check every hit... only after certain time value + if(c.date < systime + timeCheck) { + f = new File(fileName); + if(f.lastModified()>c.date) { + c=null; + } + } + } + if(c==null) { + if(logTarget!=null) { + logTarget.log("File Read: ",key); + } + + if(f==null){ + f = new File(fileName); + } + boolean cacheMe; + if(f.exists()) { + if(f.isDirectory()) { + cacheMe = false; + c = new DirectoryContent(f,isRoot); + } else { + if(f.length() > maxItemSize) { + c = new DirectFileContent(f); + cacheMe = false; + } else { + c = new CachedContent(f); + cacheMe = checkInterval>0; + } + + if(mediaType==null) { // determine from file Ending + int idx = key.lastIndexOf('.'); + String subkey = key.substring(++idx); + if((c.contentType = idx<0?null:typeMap.get(subkey))==null) { + // if nothing else, just set to default type... + c.contentType = "application/octet-stream"; + } + c.attachmentOnly = attachOnly.contains(subkey); + } else { + c.contentType=mediaType; + c.attachmentOnly = false; + } + + c.date = f.lastModified(); + + if(cacheMe) { + content.put(key, c); + } + } + } else { + c=NULL; + } + } else { + if(logTarget!=null)logTarget.log("Cache Read: ",key); + } - // refresh hit time - c.access = systime; - return c; - } - - public Content loadOrDefault(Trans trans, String targetDir, String targetFileName, String sourcePath, String mediaType) throws IOException { - try { - return load(trans.info(),targetDir,targetFileName,mediaType,0); - } catch(FileNotFoundException e) { - String targetPath = targetDir + '/' + targetFileName; - TimeTaken tt = trans.start("File doesn't exist; copy " + sourcePath + " to " + targetPath, Env.SUB); - try { - FileInputStream sourceFIS = new FileInputStream(sourcePath); - FileChannel sourceFC = sourceFIS.getChannel(); - File targetFile = new File(targetPath); - targetFile.getParentFile().mkdirs(); // ensure directory exists - FileOutputStream targetFOS = new FileOutputStream(targetFile); - try { - ByteBuffer bb = ByteBuffer.allocate((int)sourceFC.size()); - sourceFC.read(bb); - bb.flip(); // ready for reading - targetFOS.getChannel().write(bb); - } finally { - sourceFIS.close(); - targetFOS.close(); - } - } finally { - tt.done(); - } - return load(trans.info(),targetDir,targetFileName,mediaType,0); - } - } + // refresh hit time + c.access = systime; + return c; + } + + public Content loadOrDefault(Trans trans, String targetDir, String targetFileName, String sourcePath, String mediaType) throws IOException { + try { + return load(trans.info(),targetDir,targetFileName,mediaType,0); + } catch(FileNotFoundException e) { + String targetPath = targetDir + '/' + targetFileName; + TimeTaken tt = trans.start("File doesn't exist; copy " + sourcePath + " to " + targetPath, Env.SUB); + try { + FileInputStream sourceFIS = new FileInputStream(sourcePath); + FileChannel sourceFC = sourceFIS.getChannel(); + File targetFile = new File(targetPath); + targetFile.getParentFile().mkdirs(); // ensure directory exists + FileOutputStream targetFOS = new FileOutputStream(targetFile); + try { + ByteBuffer bb = ByteBuffer.allocate((int)sourceFC.size()); + sourceFC.read(bb); + bb.flip(); // ready for reading + targetFOS.getChannel().write(bb); + } finally { + sourceFIS.close(); + targetFOS.close(); + } + } finally { + tt.done(); + } + return load(trans.info(),targetDir,targetFileName,mediaType,0); + } + } - public void invalidate(String key) { - content.remove(key); - } - - private static final Content NULL=new Content() { - - @Override - public void setHeader(HttpServletResponse resp) { - resp.setStatus(404/*NOT_FOUND_404*/); - resp.setHeader("Content-type","text/plain"); - } + public void invalidate(String key) { + content.remove(key); + } + + private static final Content NULL=new Content() { + + @Override + public void setHeader(HttpServletResponse resp) { + resp.setStatus(404/*NOT_FOUND_404*/); + resp.setHeader("Content-type","text/plain"); + } - @Override - public void write(Writer writer) throws IOException { - } + @Override + public void write(Writer writer) throws IOException { + } - @Override - public void write(OutputStream os) throws IOException { - } - - }; + @Override + public void write(OutputStream os) throws IOException { + } + + }; - private static abstract class Content { - private long date; // date of the actual artifact (i.e. File modified date) - private long access; // last accessed - - protected String contentType; - protected boolean attachmentOnly; - - public void setHeader(HttpServletResponse resp) { - resp.setStatus(200/*OK_200*/); - resp.setHeader("Content-Type",contentType); - resp.setHeader("Cache-Control", MAX_AGE); - } - - public abstract void write(Writer writer) throws IOException; - public abstract void write(OutputStream os) throws IOException; + private static abstract class Content { + private long date; // date of the actual artifact (i.e. File modified date) + private long access; // last accessed + + protected String contentType; + protected boolean attachmentOnly; + + public void setHeader(HttpServletResponse resp) { + resp.setStatus(200/*OK_200*/); + resp.setHeader("Content-Type",contentType); + resp.setHeader("Cache-Control", MAX_AGE); + } + + public abstract void write(Writer writer) throws IOException; + public abstract void write(OutputStream os) throws IOException; - } + } - private static class DirectFileContent extends Content { - private File file; - public DirectFileContent(File f) { - file = f; - } - - public String toString() { - return file.getName(); - } - - public void write(Writer writer) throws IOException { - FileReader fr = new FileReader(file); - char[] buff = new char[1024]; - try { - int read; - while((read = fr.read(buff,0,1024))>=0) { - writer.write(buff,0,read); - } - } finally { - fr.close(); - } - } + private static class DirectFileContent extends Content { + private File file; + public DirectFileContent(File f) { + file = f; + } + + public String toString() { + return file.getName(); + } + + public void write(Writer writer) throws IOException { + FileReader fr = new FileReader(file); + char[] buff = new char[1024]; + try { + int read; + while((read = fr.read(buff,0,1024))>=0) { + writer.write(buff,0,read); + } + } finally { + fr.close(); + } + } - public void write(OutputStream os) throws IOException { - FileInputStream fis = new FileInputStream(file); - byte[] buff = new byte[1024]; - try { - int read; - while((read = fis.read(buff,0,1024))>=0) { - os.write(buff,0,read); - } - } finally { - fis.close(); - } - } + public void write(OutputStream os) throws IOException { + FileInputStream fis = new FileInputStream(file); + byte[] buff = new byte[1024]; + try { + int read; + while((read = fis.read(buff,0,1024))>=0) { + os.write(buff,0,read); + } + } finally { + fis.close(); + } + } - } - private static class DirectoryContent extends Content { - private static final Pattern A_NUMBER = Pattern.compile("\\d"); - private static final String H1 = "AAF Fileserver

AAF Fileserver

"; - private static final String H2 = "

    \n"; - private static final String F = "\n
"; - private File[] files; - private String name; - private boolean notRoot; + } + private static class DirectoryContent extends Content { + private static final Pattern A_NUMBER = Pattern.compile("\\d"); + private static final String H1 = "AAF Fileserver

AAF Fileserver

"; + private static final String H2 = "

    \n"; + private static final String F = "\n
"; + private File[] files; + private String name; + private boolean notRoot; - public DirectoryContent(File directory, boolean isRoot) { - notRoot = !isRoot; - - files = directory.listFiles(); - Arrays.sort(files,new Comparator() { - @Override - public int compare(File f1, File f2) { - // See if there are Numbers in the name - Matcher m1 = A_NUMBER.matcher(f1.getName()); - Matcher m2 = A_NUMBER.matcher(f2.getName()); - if(m1.find() && m2.find()) { - // if numbers, are the numbers in the same start position - int i1 = m1.start(); - int i2 = m2.start(); - - // If same start position and the text is the same, then reverse sort - if(i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) { - // reverse sort files that start similarly, but have numbers in them - return f2.compareTo(f1); - } - } - return f1.compareTo(f2); - } - - }); - name = directory.getName(); - attachmentOnly = false; - contentType = "text/html"; - } - - - @Override - public void write(Writer w) throws IOException { - w.append(H1); - w.append(name); - w.append(H2); - for (File f : files) { - w.append("
  • "); - w.append(f.getName()); - w.append("
  • \n"); - } - w.append(F); - w.flush(); - } - - @Override - public void write(OutputStream os) throws IOException { - write(new OutputStreamWriter(os)); - } - - } + public DirectoryContent(File directory, boolean isRoot) { + notRoot = !isRoot; + + files = directory.listFiles(); + Arrays.sort(files,new Comparator() { + @Override + public int compare(File f1, File f2) { + // See if there are Numbers in the name + Matcher m1 = A_NUMBER.matcher(f1.getName()); + Matcher m2 = A_NUMBER.matcher(f2.getName()); + if(m1.find() && m2.find()) { + // if numbers, are the numbers in the same start position + int i1 = m1.start(); + int i2 = m2.start(); + + // If same start position and the text is the same, then reverse sort + if(i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) { + // reverse sort files that start similarly, but have numbers in them + return f2.compareTo(f1); + } + } + return f1.compareTo(f2); + } + + }); + name = directory.getName(); + attachmentOnly = false; + contentType = "text/html"; + } + + + @Override + public void write(Writer w) throws IOException { + w.append(H1); + w.append(name); + w.append(H2); + for (File f : files) { + w.append("
  • "); + w.append(f.getName()); + w.append("
  • \n"); + } + w.append(F); + w.flush(); + } + + @Override + public void write(OutputStream os) throws IOException { + write(new OutputStreamWriter(os)); + } + + } - private static class CachedContent extends Content { - private byte[] data; - private int end; - private char[] cdata; - - public CachedContent(File f) throws IOException { - // Read and Cache - ByteBuffer bb = ByteBuffer.allocate((int)f.length()); - FileInputStream fis = new FileInputStream(f); - try { - fis.getChannel().read(bb); - } finally { - fis.close(); - } + private static class CachedContent extends Content { + private byte[] data; + private int end; + private char[] cdata; + + public CachedContent(File f) throws IOException { + // Read and Cache + ByteBuffer bb = ByteBuffer.allocate((int)f.length()); + FileInputStream fis = new FileInputStream(f); + try { + fis.getChannel().read(bb); + } finally { + fis.close(); + } - data = bb.array(); - end = bb.position(); - cdata=null; - } - - public String toString() { - return Arrays.toString(data); - } - - public void write(Writer writer) throws IOException { - synchronized(this) { - // do the String Transformation once, and only if actually used - if(cdata==null) { - cdata = new char[end]; - new String(data).getChars(0, end, cdata, 0); - } - } - writer.write(cdata,0,end); - } - public void write(OutputStream os) throws IOException { - os.write(data,0,end); - } + data = bb.array(); + end = bb.position(); + cdata=null; + } + + public String toString() { + return Arrays.toString(data); + } + + public void write(Writer writer) throws IOException { + synchronized(this) { + // do the String Transformation once, and only if actually used + if(cdata==null) { + cdata = new char[end]; + new String(data).getChars(0, end, cdata, 0); + } + } + writer.write(cdata,0,end); + } + public void write(OutputStream os) throws IOException { + os.write(data,0,end); + } - } + } - public void setEnv(LogTarget env) { - logT = env; - } + public void setEnv(LogTarget env) { + logT = env; + } - /** - * Cleanup thread to remove older items if max Cache is reached. - * @author Jonathan - * - */ - private static class Cleanup extends TimerTask { - private int maxSize; - private NavigableMap content; - - public Cleanup(NavigableMap content, int size) { - maxSize = size; - this.content = content; - } - - private class Comp implements Comparable { - public Map.Entry entry; - - public Comp(Map.Entry en) { - entry = en; - } - - @Override - public int compareTo(Comp o) { - return (int)(entry.getValue().access-o.entry.getValue().access); - } - - } - @SuppressWarnings("unchecked") - @Override - public void run() { - int size = content.size(); - if(size>maxSize) { - ArrayList scont = new ArrayList<>(size); - Object[] entries = content.entrySet().toArray(); - for(int i=0;i)entries[i])); - } - Collections.sort(scont); - int end = size - ((maxSize/4)*3); // reduce to 3/4 of max size - //System.out.println("------ Cleanup Cycle ------ " + new Date().toString() + " -------"); - for(int i=0;i entry = scont.get(i).entry; - content.remove(entry.getKey()); - //System.out.println("removed Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString()); - } -// for(int i=end;i entry = scont.get(i).entry; -// //System.out.println("remaining Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString()); -// } - } - } - } + /** + * Cleanup thread to remove older items if max Cache is reached. + * @author Jonathan + * + */ + private static class Cleanup extends TimerTask { + private int maxSize; + private NavigableMap content; + + public Cleanup(NavigableMap content, int size) { + maxSize = size; + this.content = content; + } + + private class Comp implements Comparable { + public Map.Entry entry; + + public Comp(Map.Entry en) { + entry = en; + } + + @Override + public int compareTo(Comp o) { + return (int)(entry.getValue().access-o.entry.getValue().access); + } + + } + @SuppressWarnings("unchecked") + @Override + public void run() { + int size = content.size(); + if(size>maxSize) { + ArrayList scont = new ArrayList<>(size); + Object[] entries = content.entrySet().toArray(); + for(int i=0;i)entries[i])); + } + Collections.sort(scont); + int end = size - ((maxSize/4)*3); // reduce to 3/4 of max size + //System.out.println("------ Cleanup Cycle ------ " + new Date().toString() + " -------"); + for(int i=0;i entry = scont.get(i).entry; + content.remove(entry.getKey()); + //System.out.println("removed Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString()); + } +// for(int i=end;i entry = scont.get(i).entry; +// //System.out.println("remaining Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString()); +// } + } + } + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CodeSetter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CodeSetter.java index 6ea8880b..1c171fd7 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CodeSetter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CodeSetter.java @@ -31,22 +31,22 @@ import org.onap.aaf.misc.env.Trans; // Package on purpose. only want between RServlet and Routes class CodeSetter { - private HttpCode code; - private TRANS trans; - private HttpServletRequest req; - private HttpServletResponse resp; - public CodeSetter(TRANS trans, HttpServletRequest req, HttpServletResponse resp) { - this.trans = trans; - this.req = req; - this.resp = resp; - - } - public boolean matches(Route route) throws IOException, ServletException { - // Find best Code in Route based on "Accepts (Get) or Content-Type" (if exists) - return (code = route.getCode(trans, req, resp))!=null; - } - - public HttpCode code() { - return code; - } + private HttpCode code; + private TRANS trans; + private HttpServletRequest req; + private HttpServletResponse resp; + public CodeSetter(TRANS trans, HttpServletRequest req, HttpServletResponse resp) { + this.trans = trans; + this.req = req; + this.resp = resp; + + } + public boolean matches(Route route) throws IOException, ServletException { + // Find best Code in Route based on "Accepts (Get) or Content-Type" (if exists) + return (code = route.getCode(trans, req, resp))!=null; + } + + public HttpCode code() { + return code; + } } \ No newline at end of file diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java index ae329ce2..f8760ada 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java @@ -43,73 +43,73 @@ import org.onap.aaf.misc.env.Trans; * */ public abstract class Content { - public static final String Q = "q"; - protected abstract Pair,List>>> types(HttpCode code, String str); - protected abstract boolean props(Pair,List>>> type, String tag, String value); + public static final String Q = "q"; + protected abstract Pair,List>>> types(HttpCode code, String str); + protected abstract boolean props(Pair,List>>> type, String tag, String value); - /** - * Parse a Content-Type/Accept. As found, call "types" and "props", which do different - * things depending on if it's a Content-Type or Accepts. - * - * For Content-Type, it builds a tree suitable for Comparison - * For Accepts, it compares against the tree, and builds an acceptable type list - * - * Since this parse code is used for every incoming HTTP transaction, I have removed the implementation - * that uses String.split, and replaced with integers evaluating the Byte array. This results - * in only the necessary strings created, resulting in 1/3 better speed, and less - * Garbage collection. - * - * @param trans - * @param code - * @param cntnt - * @return - */ - protected boolean parse(HttpCode code, String cntnt) { - byte bytes[] = cntnt.getBytes(); - boolean contType=false,contProp=true; - int cis,cie=-1,cend; - int sis,sie,send; - do { - cis = cie+1; - cie = cntnt.indexOf(',',cis); - cend = cie<0?bytes.length:cie; - // Start SEMIS - sie=cis-1; - Pair, List>>> me = null; - do { - sis = sie+1; - sie = cntnt.indexOf(';',sis); - send = sie>cend || sie<0?cend:sie; - if(me==null) { - String semi = new String(bytes,sis,send-sis); - // trans.checkpoint(semi); - // Look at first entity within comma group - // Is this an acceptable Type? - me=types(code, semi); - if(me==null) { - sie=-1; // skip the rest of the processing... not a type - } else { - contType=true; - } - } else { // We've looped past the first Semi, now process as properties - // If there are additional elements (more entities within Semi Colons) - // apply Propertys - int eq = cntnt.indexOf('=',sis); - if(eq>sis && eq code, String cntnt) { + byte bytes[] = cntnt.getBytes(); + boolean contType=false,contProp=true; + int cis,cie=-1,cend; + int sis,sie,send; + do { + cis = cie+1; + cie = cntnt.indexOf(',',cis); + cend = cie<0?bytes.length:cie; + // Start SEMIS + sie=cis-1; + Pair, List>>> me = null; + do { + sis = sie+1; + sie = cntnt.indexOf(';',sis); + send = sie>cend || sie<0?cend:sie; + if(me==null) { + String semi = new String(bytes,sis,send-sis); + // trans.checkpoint(semi); + // Look at first entity within comma group + // Is this an acceptable Type? + me=types(code, semi); + if(me==null) { + sie=-1; // skip the rest of the processing... not a type + } else { + contType=true; + } + } else { // We've looped past the first Semi, now process as properties + // If there are additional elements (more entities within Semi Colons) + // apply Propertys + int eq = cntnt.indexOf('=',sis); + if(eq>sis && eq params; - private byte[] values[]; - private Integer vars[]; - private boolean wildcard; + private Map params; + private byte[] values[]; + private Integer vars[]; + private boolean wildcard; - - /* - * These two methods are pairs of searching performance for variables Spark Style. - * setParams evaluates the target path, and sets a HashMap that will return an Integer. - * the Keys are both :key and key so that there will be no string operations during - * a transaction - * - * For the Integer, if the High Order is 0, then it is just one value. If High Order >0, then it is - * a multi-field option, i.e. ending with a wild-card. - */ - public Match(String path) { - // IF DEBUG: System.out.print("\n[" + path + "]"); - params = new HashMap<>(); - if(path!=null) { - String[] pa = path.split("/"); - values = new byte[pa.length][]; - vars = new Integer[pa.length]; - - int val = 0; - String key; - for(int i=0;i1) { - /* remove * from value */ - int newlength = values[i].length-1; - byte[] real = new byte[newlength]; - System.arraycopy(values[i],0,real,0,newlength); - values[i]=real; - } else { - vars[i]=0; // this is actually a variable, if it only contains a "*" - } - } - // vars[i]=null; - } - } - } - } + + /* + * These two methods are pairs of searching performance for variables Spark Style. + * setParams evaluates the target path, and sets a HashMap that will return an Integer. + * the Keys are both :key and key so that there will be no string operations during + * a transaction + * + * For the Integer, if the High Order is 0, then it is just one value. If High Order >0, then it is + * a multi-field option, i.e. ending with a wild-card. + */ + public Match(String path) { + // IF DEBUG: System.out.print("\n[" + path + "]"); + params = new HashMap<>(); + if(path!=null) { + String[] pa = path.split("/"); + values = new byte[pa.length][]; + vars = new Integer[pa.length]; + + int val = 0; + String key; + for(int i=0;i1) { + /* remove * from value */ + int newlength = values[i].length-1; + byte[] real = new byte[newlength]; + System.arraycopy(values[i],0,real,0,newlength); + values[i]=real; + } else { + vars[i]=0; // this is actually a variable, if it only contains a "*" + } + } + // vars[i]=null; + } + } + } + } - /* - * This is the second of the param evaluation functions. First, we look up to see if there is - * any reference by key in the params Map created by the above. - * - * The resulting Integer, if not null, is split high/low order into start and end. - * We evaluate the string for '/', rather than splitting into String[] to avoid the time/mem needed - * We traverse to the proper field number for slash, evaluate the end (whether wild card or no), - * and return the substring. - * - * The result is something less than .003 milliseconds per evaluation - * - */ - public String param(String path,String key) { - Integer val = params.get(key); // :key or key - if(val!=null) { - int start = val & 0xFFFF; - int end = (val >> 16) & 0xFFFF; - int idx = -1; - int i; - for(i=0;i> 16) & 0xFFFF; + int idx = -1; + int i; + for(i=0;i0?(pabytes[0]=='/'):false; - // IF DEBUG: System.out.println("\n -- " + path + " --"); - for(int i=0;rv && i=lastField) { // checking here allows there to be a non-functional ending / - rv = false; - break; - } - if(values[field]==null) { // it's a variable, just look for /s - if(wildcard && field==lastField-1) return true;// we've made it this far. We accept all remaining characters - Integer val = vars[field]; - int start = val & 0xFFFF; - int end = (val >> 16) & 0xFFFF; - if(end==0)end=start+1; - int k = i; - for(int j=start; ji)i=k-1; // if we've incremented, have to accommodate the outer for loop incrementing as well - fieldMatched = false; // reset - fieldIdx = 0; - } else { - // IF DEBUG: System.out.print((char)pabytes[i]); - if(pabytes[i]=='/') { // end of field, eval if Field is matched - // if double slash, check if supposed to be empty - if(fieldIdx==0 && values[field].length==0) { - fieldMatched = true; - } - rv = fieldMatched && ++field getParamNames() { - return params.keySet(); - } + int lastField = values.length; + int lastByte = pabytes.length; + boolean fieldMatched = false; // = lastByte>0?(pabytes[0]=='/'):false; + // IF DEBUG: System.out.println("\n -- " + path + " --"); + for(int i=0;rv && i=lastField) { // checking here allows there to be a non-functional ending / + rv = false; + break; + } + if(values[field]==null) { // it's a variable, just look for /s + if(wildcard && field==lastField-1) return true;// we've made it this far. We accept all remaining characters + Integer val = vars[field]; + int start = val & 0xFFFF; + int end = (val >> 16) & 0xFFFF; + if(end==0)end=start+1; + int k = i; + for(int j=start; ji)i=k-1; // if we've incremented, have to accommodate the outer for loop incrementing as well + fieldMatched = false; // reset + fieldIdx = 0; + } else { + // IF DEBUG: System.out.print((char)pabytes[i]); + if(pabytes[i]=='/') { // end of field, eval if Field is matched + // if double slash, check if supposed to be empty + if(fieldIdx==0 && values[field].length==0) { + fieldMatched = true; + } + rv = fieldMatched && ++field getParamNames() { + return params.keySet(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Pair.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Pair.java index 810f9129..f4d1394b 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Pair.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Pair.java @@ -30,15 +30,15 @@ package org.onap.aaf.auth.rserv; * @param */ public class Pair { - public X x; - public Y y; - - public Pair(X x, Y y) { - this.x = x; - this.y = y; - } - - public String toString() { - return "X: " + x.toString() + "-->" + y.toString(); - } + public X x; + public Y y; + + public Pair(X x, Y y) { + this.x = x; + this.y = y; + } + + public String toString() { + return "X: " + x.toString() + "-->" + y.toString(); + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java index 4ae0f882..03264d56 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java @@ -37,118 +37,118 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.Trans; public abstract class RServlet implements Servlet { - private Routes routes = new Routes(); + private Routes routes = new Routes(); - private ServletConfig config; + private ServletConfig config; - @Override - public void init(ServletConfig config) throws ServletException { - this.config = config; - } + @Override + public void init(ServletConfig config) throws ServletException { + this.config = config; + } - @Override - public ServletConfig getServletConfig() { - return config; - } + @Override + public ServletConfig getServletConfig() { + return config; + } - public void route(Env env, HttpMethods meth, String path, HttpCode code, String ... moreTypes) { - Route r = routes.findOrCreate(meth,path); - r.add(code,moreTypes); - env.init().log(r.report(code),code); - } - - @Override - public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { - HttpServletRequest request = (HttpServletRequest)req; - HttpServletResponse response = (HttpServletResponse)res; - - @SuppressWarnings("unchecked") - TRANS trans = (TRANS)req.getAttribute(TransFilter.TRANS_TAG); - if(trans==null) { - response.setStatus(404); // Not Found, because it didn't go through TransFilter - return; - } - - Route route; - HttpCode code=null; - String ct = req.getContentType(); - TimeTaken tt = trans.start("Resolve to Code", Env.SUB); - try { - // routes have multiple code sets. This object picks the best code set - // based on Accept or Content-Type - CodeSetter codesetter = new CodeSetter(trans,request,response); - // Find declared route - route = routes.derive(request, codesetter); - if(route==null) { - String method = request.getMethod(); - trans.checkpoint("No Route matches "+ method + ' ' + request.getPathInfo()); - response.setStatus(404); // Not Found - } else { - // Find best Code in Route based on "Accepts (Get) or Content-Type" (if exists) - code = codesetter.code();// route.getCode(trans, request, response); - } - } finally { - tt.done(); - } - - if(route!=null && code!=null) { - StringBuilder sb = new StringBuilder(72); - sb.append(route.auditText); - sb.append(','); - sb.append(code.desc()); - if(ct!=null) { - sb.append(", ContentType: "); - sb.append(ct); - } - tt = trans.start(sb.toString(),Env.SUB); - try { - /*obj = */ - code.handle(trans, request, response); - response.flushBuffer(); - } catch (ServletException e) { - trans.error().log(e); - throw e; - } catch (Exception e) { - trans.error().log(e,request.getMethod(),request.getPathInfo()); - throw new ServletException(e); - } finally { - tt.done(); - } - } - } - - @Override - public String getServletInfo() { - return "RServlet for Jetty"; - } + public void route(Env env, HttpMethods meth, String path, HttpCode code, String ... moreTypes) { + Route r = routes.findOrCreate(meth,path); + r.add(code,moreTypes); + env.init().log(r.report(code),code); + } + + @Override + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { + HttpServletRequest request = (HttpServletRequest)req; + HttpServletResponse response = (HttpServletResponse)res; + + @SuppressWarnings("unchecked") + TRANS trans = (TRANS)req.getAttribute(TransFilter.TRANS_TAG); + if(trans==null) { + response.setStatus(404); // Not Found, because it didn't go through TransFilter + return; + } + + Route route; + HttpCode code=null; + String ct = req.getContentType(); + TimeTaken tt = trans.start("Resolve to Code", Env.SUB); + try { + // routes have multiple code sets. This object picks the best code set + // based on Accept or Content-Type + CodeSetter codesetter = new CodeSetter(trans,request,response); + // Find declared route + route = routes.derive(request, codesetter); + if(route==null) { + String method = request.getMethod(); + trans.checkpoint("No Route matches "+ method + ' ' + request.getPathInfo()); + response.setStatus(404); // Not Found + } else { + // Find best Code in Route based on "Accepts (Get) or Content-Type" (if exists) + code = codesetter.code();// route.getCode(trans, request, response); + } + } finally { + tt.done(); + } + + if(route!=null && code!=null) { + StringBuilder sb = new StringBuilder(72); + sb.append(route.auditText); + sb.append(','); + sb.append(code.desc()); + if(ct!=null) { + sb.append(", ContentType: "); + sb.append(ct); + } + tt = trans.start(sb.toString(),Env.SUB); + try { + /*obj = */ + code.handle(trans, request, response); + response.flushBuffer(); + } catch (ServletException e) { + trans.error().log(e); + throw e; + } catch (Exception e) { + trans.error().log(e,request.getMethod(),request.getPathInfo()); + throw new ServletException(e); + } finally { + tt.done(); + } + } + } + + @Override + public String getServletInfo() { + return "RServlet for Jetty"; + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } - public String applicationJSON(Class cls, String version) { - StringBuilder sb = new StringBuilder(); - sb.append("application/"); - sb.append(cls.getSimpleName()); - sb.append("+json"); - sb.append(";charset=utf-8"); - sb.append(";version="); - sb.append(version); - return sb.toString(); - } + public String applicationJSON(Class cls, String version) { + StringBuilder sb = new StringBuilder(); + sb.append("application/"); + sb.append(cls.getSimpleName()); + sb.append("+json"); + sb.append(";charset=utf-8"); + sb.append(";version="); + sb.append(version); + return sb.toString(); + } - public String applicationXML(Class cls, String version) { - StringBuilder sb = new StringBuilder(); - sb.append("application/"); - sb.append(cls.getSimpleName()); - sb.append("+xml"); - sb.append(";charset=utf-8"); - sb.append(";version="); - sb.append(version); - return sb.toString(); - } + public String applicationXML(Class cls, String version) { + StringBuilder sb = new StringBuilder(); + sb.append("application/"); + sb.append(cls.getSimpleName()); + sb.append("+xml"); + sb.append(";charset=utf-8"); + sb.append(";version="); + sb.append(version); + return sb.toString(); + } - public List routeReport() { - return routes.routeReport(); - } + public List routeReport() { + return routes.routeReport(); + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java index 9ae202a2..81b3d0a2 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java @@ -33,109 +33,109 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.Trans; public class Route { - public final String auditText; - public final HttpMethods meth; - public final String path; - - private Match match; - // package on purpose - private final TypedCode content; - private final boolean isGet; - - public Route(HttpMethods meth, String path) { - this.path = path; - auditText = meth.name() + ' ' + path; - this.meth = meth; // Note: Using Spark def for now. - isGet = meth.compareTo(HttpMethods.GET) == 0; - match = new Match(path); - content = new TypedCode(); - } - - public void add(HttpCode code, String ... others) { - code.match = match; - content.add(code, others); - } - -// public void add(HttpCode code, Class cls, String version, String ... others) { -// code.match = match; -// content.add(code, cls, version, others); -// } + public final String auditText; + public final HttpMethods meth; + public final String path; + + private Match match; + // package on purpose + private final TypedCode content; + private final boolean isGet; + + public Route(HttpMethods meth, String path) { + this.path = path; + auditText = meth.name() + ' ' + path; + this.meth = meth; // Note: Using Spark def for now. + isGet = meth.compareTo(HttpMethods.GET) == 0; + match = new Match(path); + content = new TypedCode(); + } + + public void add(HttpCode code, String ... others) { + code.match = match; + content.add(code, others); + } + +// public void add(HttpCode code, Class cls, String version, String ... others) { +// code.match = match; +// content.add(code, cls, version, others); +// } // - public HttpCode getCode(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { - // Type is associated with Accept for GET (since it is what is being returned - // We associate the rest with ContentType. - // FYI, thought about this a long time before implementing this way. - String compare; -// String special[]; // todo, expose Charset (in special) to outside - if(isGet) { - compare = req.getHeader("Accept"); // Accept is used for read, as we want to agree on what caller is ready to handle - } else { - compare = req.getContentType(); // Content type used to declare what data is being created, updated or deleted (might be used for key) - } + public HttpCode getCode(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { + // Type is associated with Accept for GET (since it is what is being returned + // We associate the rest with ContentType. + // FYI, thought about this a long time before implementing this way. + String compare; +// String special[]; // todo, expose Charset (in special) to outside + if(isGet) { + compare = req.getHeader("Accept"); // Accept is used for read, as we want to agree on what caller is ready to handle + } else { + compare = req.getContentType(); // Content type used to declare what data is being created, updated or deleted (might be used for key) + } - Pair, List>>> hl = content.prep(trans, compare); - if(hl==null) { - resp.setStatus(406); // NOT_ACCEPTABLE - } else { - if(isGet) { // Set Content Type to expected content - if("*".equals(hl.x) || "*/*".equals(hl.x)) {// if wild-card, then choose first kind of type - resp.setContentType(content.first()); - } else { - resp.setContentType(hl.x); - } - } - return hl.y.x; - } - return null; - } - - public Route matches(String method, String path) { - return meth.name().equalsIgnoreCase(method) && match.match(path)?this:null; - } - - public TimeTaken start(Trans trans, String auditText, HttpCode code, String type) { - StringBuilder sb = new StringBuilder(auditText); - sb.append(", "); - sb.append(code.desc()); - sb.append(", Content: "); - sb.append(type); - return trans.start(sb.toString(), Env.SUB); - } + Pair, List>>> hl = content.prep(trans, compare); + if(hl==null) { + resp.setStatus(406); // NOT_ACCEPTABLE + } else { + if(isGet) { // Set Content Type to expected content + if("*".equals(hl.x) || "*/*".equals(hl.x)) {// if wild-card, then choose first kind of type + resp.setContentType(content.first()); + } else { + resp.setContentType(hl.x); + } + } + return hl.y.x; + } + return null; + } + + public Route matches(String method, String path) { + return meth.name().equalsIgnoreCase(method) && match.match(path)?this:null; + } + + public TimeTaken start(Trans trans, String auditText, HttpCode code, String type) { + StringBuilder sb = new StringBuilder(auditText); + sb.append(", "); + sb.append(code.desc()); + sb.append(", Content: "); + sb.append(type); + return trans.start(sb.toString(), Env.SUB); + } - // Package on purpose.. for "find/Create" routes only - boolean resolvesTo(HttpMethods hm, String p) { - return(path.equals(p) && hm.equals(meth)); - } - - public String toString() { - return auditText + ' ' + content; - } + // Package on purpose.. for "find/Create" routes only + boolean resolvesTo(HttpMethods hm, String p) { + return(path.equals(p) && hm.equals(meth)); + } + + public String toString() { + return auditText + ' ' + content; + } - public String report(HttpCode code) { - StringBuilder sb = new StringBuilder(); - sb.append(auditText); - sb.append(' '); - content.relatedTo(code, sb); - return sb.toString(); - } + public String report(HttpCode code) { + StringBuilder sb = new StringBuilder(); + sb.append(auditText); + sb.append(' '); + content.relatedTo(code, sb); + return sb.toString(); + } - public RouteReport api() { - RouteReport tr = new RouteReport(); - tr.meth = meth; - tr.path = path; - content.api(tr); - return tr; - } + public RouteReport api() { + RouteReport tr = new RouteReport(); + tr.meth = meth; + tr.path = path; + content.api(tr); + return tr; + } - /** - * contentRelatedTo (For reporting) list routes that will end up at a specific Code - * @return - */ - public String contentRelatedTo(HttpCode code) { - StringBuilder sb = new StringBuilder(path); - sb.append(' '); - content.relatedTo(code, sb); - return sb.toString(); - } + /** + * contentRelatedTo (For reporting) list routes that will end up at a specific Code + * @return + */ + public String contentRelatedTo(HttpCode code) { + StringBuilder sb = new StringBuilder(path); + sb.append(' '); + content.relatedTo(code, sb); + return sb.toString(); + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RouteReport.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RouteReport.java index 1c946e83..cb7c48bc 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RouteReport.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RouteReport.java @@ -25,9 +25,9 @@ import java.util.ArrayList; import java.util.List; public class RouteReport { - public HttpMethods meth; - public String path; - public String desc; - public final List contextTypes = new ArrayList<>(); + public HttpMethods meth; + public String path; + public String desc; + public final List contextTypes = new ArrayList<>(); } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java index 7cfadf2b..7c69d9b7 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java @@ -32,58 +32,58 @@ import org.onap.aaf.misc.env.Trans; public class Routes { - // Since this must be very, very fast, and only needs one creation, we'll use just an array. - private Route[] routes; - private int end; - + // Since this must be very, very fast, and only needs one creation, we'll use just an array. + private Route[] routes; + private int end; + - @SuppressWarnings("unchecked") - public Routes() { - routes = new Route[10]; - end = 0; - } - - // This method for setup of Routes only... - // Package on purpose - synchronized Route findOrCreate(HttpMethods meth, String path) { - Route rv = null; - for(int i=0;i=routes.length) { - @SuppressWarnings("unchecked") - Route[] temp = new Route[end+10]; - System.arraycopy(routes, 0, temp, 0, routes.length); - routes = temp; - } - - routes[end++]=rv=new Route(meth,path); - } - return rv; - } - - public Route derive(HttpServletRequest req, CodeSetter codeSetter) throws IOException, ServletException { - Route rv = null; - String path = req.getPathInfo(); - String meth = req.getMethod(); - //TODO a TREE would be better - for(int i=0;rv==null && i routeReport() { - ArrayList ltr = new ArrayList<>(); - for(int i=0;i findOrCreate(HttpMethods meth, String path) { + Route rv = null; + for(int i=0;i=routes.length) { + @SuppressWarnings("unchecked") + Route[] temp = new Route[end+10]; + System.arraycopy(routes, 0, temp, 0, routes.length); + routes = temp; + } + + routes[end++]=rv=new Route(meth,path); + } + return rv; + } + + public Route derive(HttpServletRequest req, CodeSetter codeSetter) throws IOException, ServletException { + Route rv = null; + String path = req.getPathInfo(); + String meth = req.getMethod(); + //TODO a TREE would be better + for(int i=0;rv==null && i routeReport() { + ArrayList ltr = new ArrayList<>(); + for(int i=0;i implements Filter { - public static final String TRANS_TAG = "__TRANS__"; - - private CadiHTTPManip cadi; + public static final String TRANS_TAG = "__TRANS__"; + + private CadiHTTPManip cadi; - private final String[] no_authn; - - public TransFilter(Access access, Connector con, TrustChecker tc, Object ... additionalTafLurs) throws CadiException, LocatorException { - cadi = new CadiHTTPManip(access, con, tc, additionalTafLurs); - String no = access.getProperty(Config.CADI_NOAUTHN, null); - if(no!=null) { - no_authn = Split.split(':', no); - } else { - no_authn=null; - } - } + private final String[] no_authn; + + public TransFilter(Access access, Connector con, TrustChecker tc, Object ... additionalTafLurs) throws CadiException, LocatorException { + cadi = new CadiHTTPManip(access, con, tc, additionalTafLurs); + String no = access.getProperty(Config.CADI_NOAUTHN, null); + if(no!=null) { + no_authn = Split.split(':', no); + } else { + no_authn=null; + } + } - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } - - protected Lur getLur() { - return cadi.getLur(); - } + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + protected Lur getLur() { + return cadi.getLur(); + } - protected abstract TRANS newTrans(HttpServletRequest request); - protected abstract TimeTaken start(TRANS trans, ServletRequest request); - protected abstract void authenticated(TRANS trans, Principal p); - protected abstract void tallyHo(TRANS trans); - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - HttpServletRequest req = (HttpServletRequest)request; - HttpServletResponse res = (HttpServletResponse)response; - - TRANS trans = newTrans(req); - - TimeTaken overall = start(trans,request); - try { - request.setAttribute(TRANS_TAG, trans); - - if(no_authn!=null) { - for(String prefix : no_authn) { - if(req.getPathInfo().startsWith(prefix)) { - chain.doFilter(request, response); - return; - } - } - } + protected abstract TRANS newTrans(HttpServletRequest request); + protected abstract TimeTaken start(TRANS trans, ServletRequest request); + protected abstract void authenticated(TRANS trans, Principal p); + protected abstract void tallyHo(TRANS trans); + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest)request; + HttpServletResponse res = (HttpServletResponse)response; + + TRANS trans = newTrans(req); + + TimeTaken overall = start(trans,request); + try { + request.setAttribute(TRANS_TAG, trans); + + if(no_authn!=null) { + for(String prefix : no_authn) { + if(req.getPathInfo().startsWith(prefix)) { + chain.doFilter(request, response); + return; + } + } + } - TimeTaken security = trans.start("CADI Security", Env.SUB); - TafResp resp; - RESP r; - CadiWrap cw = null; - try { - resp = cadi.validate(req,res,trans); - switch(r=resp.isAuthenticated()) { - case IS_AUTHENTICATED: - cw = new CadiWrap(req,resp,cadi.getLur()); - authenticated(trans, cw.getUserPrincipal()); - break; - default: - break; - } - } finally { - security.done(); - } - - if(r==RESP.IS_AUTHENTICATED) { - trans.checkpoint(resp.desc()); - if(cadi.notCadi(cw, res)) { - chain.doFilter(cw, response); - } - } else { - //TODO this is a good place to check if too many checks recently - // Would need Cached Counter objects that are cleaned up on - // use - trans.checkpoint(resp.desc(),Env.ALWAYS); - if(resp.isFailedAttempt()) - trans.audit().log(resp.desc()); - } - } catch(Exception e) { - trans.error().log(e); - trans.checkpoint("Error: " + e.getClass().getSimpleName() + ": " + e.getMessage()); - throw new ServletException(e); - } finally { - overall.done(); - tallyHo(trans); - } - } + TimeTaken security = trans.start("CADI Security", Env.SUB); + TafResp resp; + RESP r; + CadiWrap cw = null; + try { + resp = cadi.validate(req,res,trans); + switch(r=resp.isAuthenticated()) { + case IS_AUTHENTICATED: + cw = new CadiWrap(req,resp,cadi.getLur()); + authenticated(trans, cw.getUserPrincipal()); + break; + default: + break; + } + } finally { + security.done(); + } + + if(r==RESP.IS_AUTHENTICATED) { + trans.checkpoint(resp.desc()); + if(cadi.notCadi(cw, res)) { + chain.doFilter(cw, response); + } + } else { + //TODO this is a good place to check if too many checks recently + // Would need Cached Counter objects that are cleaned up on + // use + trans.checkpoint(resp.desc(),Env.ALWAYS); + if(resp.isFailedAttempt()) + trans.audit().log(resp.desc()); + } + } catch(Exception e) { + trans.error().log(e); + trans.checkpoint("Error: " + e.getClass().getSimpleName() + ": " + e.getMessage()); + throw new ServletException(e); + } finally { + overall.done(); + tallyHo(trans); + } + } - @Override - public void destroy() { - }; + @Override + public void destroy() { + }; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransOnlyFilter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransOnlyFilter.java index e0f7512d..c3514b65 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransOnlyFilter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransOnlyFilter.java @@ -46,32 +46,32 @@ import org.onap.aaf.misc.env.TransStore; * */ public abstract class TransOnlyFilter implements Filter { - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } - + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + - protected abstract TRANS newTrans(); - protected abstract TimeTaken start(TRANS trans, ServletRequest request); - protected abstract void authenticated(TRANS trans, TaggedPrincipal p); - protected abstract void tallyHo(TRANS trans); - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - TRANS trans = newTrans(); - - TimeTaken overall = start(trans,request); - try { - request.setAttribute(TransFilter.TRANS_TAG, trans); - chain.doFilter(request, response); - } finally { - overall.done(); - } - tallyHo(trans); - } + protected abstract TRANS newTrans(); + protected abstract TimeTaken start(TRANS trans, ServletRequest request); + protected abstract void authenticated(TRANS trans, TaggedPrincipal p); + protected abstract void tallyHo(TRANS trans); + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + TRANS trans = newTrans(); + + TimeTaken overall = start(trans,request); + try { + request.setAttribute(TransFilter.TRANS_TAG, trans); + chain.doFilter(request, response); + } finally { + overall.done(); + } + tallyHo(trans); + } - @Override - public void destroy() { - }; + @Override + public void destroy() { + }; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java index 4425886c..8c57838d 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java @@ -44,7 +44,7 @@ import org.onap.aaf.misc.env.Trans; * I created type-safety at each level, which you can't get from a TreeSet, etc. * 4) Chaining through the Network is simply object dereferencing, which is as fast as Java can go. * 5) The drawback is that in your code is that all the variables are named "x" and "y", which can be a bit hard to - * read both in code, and in the debugger. However, TypeSafety allows your IDE (Eclipse) to help you make the + * read both in code, and in the debugger. However, TypeSafety allows your IDE (Eclipse) to help you make the * choices. Also, make sure you have a good "toString()" method on each object so you can see what's happening * in the IDE Debugger. * @@ -56,214 +56,214 @@ import org.onap.aaf.misc.env.Trans; * @param */ public class TypedCode extends Content { - private List,List>>>> types; + private List,List>>>> types; - public TypedCode() { - types = new ArrayList<>(); - } - - /** - * Construct Typed Code based on ContentType parameters passed in - * - * @param code - * @param others - * @return - */ - public TypedCode add(HttpCode code, String ... others) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for(String str : others) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(str); - } - parse(code, sb.toString()); - - return this; - } - - @Override - protected Pair, List>>> types(HttpCode code, String str) { - Pair,List>>> type = null; - ArrayList> props = new ArrayList<>(); - // Want Q percentage is to be first in the array everytime. If not listed, 1.0 is default - props.add(new Pair(Q,1f)); - Pair, List>> cl = new Pair, List>>(code, props); -// // breakup "plus" stuff, i.e. application/xaml+xml -// int plus = str.indexOf('+'); -// if(plus<0) { - type = new Pair,List>>>(str, cl); - types.add(type); - return type; -// } else { -// int prev = str.indexOf('/')+1; -// String first = str.substring(0,prev); -// String nstr; -// while(prev!=0) { -// nstr = first + (plus>-1?str.substring(prev,plus):str.substring(prev)); -// type = new Pair,List>>>(nstr, cl); -// types.add(type); -// prev = plus+1; -// plus = str.indexOf('+',prev); -// } -// return type; -// } - } + public TypedCode() { + types = new ArrayList<>(); + } + + /** + * Construct Typed Code based on ContentType parameters passed in + * + * @param code + * @param others + * @return + */ + public TypedCode add(HttpCode code, String ... others) { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for(String str : others) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(str); + } + parse(code, sb.toString()); + + return this; + } + + @Override + protected Pair, List>>> types(HttpCode code, String str) { + Pair,List>>> type = null; + ArrayList> props = new ArrayList<>(); + // Want Q percentage is to be first in the array everytime. If not listed, 1.0 is default + props.add(new Pair(Q,1f)); + Pair, List>> cl = new Pair, List>>(code, props); +// // breakup "plus" stuff, i.e. application/xaml+xml +// int plus = str.indexOf('+'); +// if(plus<0) { + type = new Pair,List>>>(str, cl); + types.add(type); + return type; +// } else { +// int prev = str.indexOf('/')+1; +// String first = str.substring(0,prev); +// String nstr; +// while(prev!=0) { +// nstr = first + (plus>-1?str.substring(prev,plus):str.substring(prev)); +// type = new Pair,List>>>(nstr, cl); +// types.add(type); +// prev = plus+1; +// plus = str.indexOf('+',prev); +// } +// return type; +// } + } - @Override - protected boolean props(Pair, List>>> type, String tag, String value) { - if(tag.equals(Q)) { // reset the Q value (first in array) - boolean rv = true; - try { - type.y.y.get(0).y=Float.parseFloat(value); - return rv; - } catch (NumberFormatException e) { - rv=false; // Note: this awkward syntax forced by Sonar, which doesn't like doing nothing with Exception - // which is what should happen - } - } - return type.y.y.add(new Pair(tag,"version".equals(tag)?new Version(value):value)); - } - - public Pair, List>>> prep(TRANS trans, String compare) throws IOException, ServletException { - Pair, List>>> c,rv=null; - if(types.size()==1 && "".equals((c=types.get(0)).x)) { // if there are no checks for type, skip - rv = c; - } else { - if(compare==null || compare.length()==0) { - rv = types.get(0); // first code is used - } else { - Acceptor acc = new Acceptor(types); - boolean accepted; - TimeTaken tt = trans.start(compare, Env.SUB); - try { - accepted = acc.parse(null, compare); - } finally { - tt.done(); - } - if(accepted) { - switch(acc.acceptable.size()) { - case 0: -// // TODO best Status Code? -// resp.setStatus(HttpStatus.NOT_ACCEPTABLE_406); - break; - case 1: - rv = acc.acceptable.get(0); - break; - default: // compare Q values to get Best Match - float bestQ = -1.0f; - Pair, List>>> bestT = null; - for(Pair, List>>> type : acc.acceptable) { - Float f = (Float)type.y.y.get(0).y; // first property is always Q - if(f>bestQ) { - bestQ=f; - bestT = type; - } - } - if(bestT!=null) { - // When it is a GET, the matched type is what is returned, so set ContentType -// if(isGet)resp.setContentType(bestT.x); // set ContentType of Code -// rv = bestT.y.x; - rv = bestT; - } - } - } else { - trans.checkpoint("No Match found for Accept"); - } - } - } - return rv; - } - - /** - * Print on String Builder content related to specific Code - * - * This is for Reporting and Debugging purposes, so the content is not cached. - * - * If code is "null", then all content is matched - * - * @param code - * @return - */ - public StringBuilder relatedTo(HttpCode code, StringBuilder sb) { - boolean first = true; - for(Pair, List>>> pair : types) { - if(code==null || pair.y.x == code) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(pair.x); - for(Pair prop : pair.y.y) { - // Don't print "Q". it's there for internal use, but it is only meaningful for "Accepts" - if(!prop.x.equals(Q) || !prop.y.equals(1f) ) { - sb.append(';'); - sb.append(prop.x); - sb.append('='); - sb.append(prop.y); - } - } - } - } - return sb; - } - - public List> getContent(HttpCode code) { - for(Pair, List>>> pair : types) { - if(pair.y.x == code) { - return pair.y.y; - } - } - return null; - } - - public String toString() { - return relatedTo(null,new StringBuilder()).toString(); - } - - public void api(RouteReport tr) { - // Need to build up a map, because Prop entries can be in several places. - HashMap,StringBuilder> psb = new HashMap<>(); - StringBuilder temp; - tr.desc = null; - - // Read through Code/TypeCode trees for all accepted Typecodes - for(Pair, List>>> tc : types) { - // If new, then it's new Code set, create prefix content - if((temp=psb.get(tc.y.x))==null) { - psb.put(tc.y.x,temp=new StringBuilder()); - if(tr.desc==null) { - tr.desc = tc.y.x.desc(); - } - } else { - temp.append(','); - } - temp.append(tc.x); + @Override + protected boolean props(Pair, List>>> type, String tag, String value) { + if(tag.equals(Q)) { // reset the Q value (first in array) + boolean rv = true; + try { + type.y.y.get(0).y=Float.parseFloat(value); + return rv; + } catch (NumberFormatException e) { + rv=false; // Note: this awkward syntax forced by Sonar, which doesn't like doing nothing with Exception + // which is what should happen + } + } + return type.y.y.add(new Pair(tag,"version".equals(tag)?new Version(value):value)); + } + + public Pair, List>>> prep(TRANS trans, String compare) throws IOException, ServletException { + Pair, List>>> c,rv=null; + if(types.size()==1 && "".equals((c=types.get(0)).x)) { // if there are no checks for type, skip + rv = c; + } else { + if(compare==null || compare.length()==0) { + rv = types.get(0); // first code is used + } else { + Acceptor acc = new Acceptor(types); + boolean accepted; + TimeTaken tt = trans.start(compare, Env.SUB); + try { + accepted = acc.parse(null, compare); + } finally { + tt.done(); + } + if(accepted) { + switch(acc.acceptable.size()) { + case 0: +// // TODO best Status Code? +// resp.setStatus(HttpStatus.NOT_ACCEPTABLE_406); + break; + case 1: + rv = acc.acceptable.get(0); + break; + default: // compare Q values to get Best Match + float bestQ = -1.0f; + Pair, List>>> bestT = null; + for(Pair, List>>> type : acc.acceptable) { + Float f = (Float)type.y.y.get(0).y; // first property is always Q + if(f>bestQ) { + bestQ=f; + bestT = type; + } + } + if(bestT!=null) { + // When it is a GET, the matched type is what is returned, so set ContentType +// if(isGet)resp.setContentType(bestT.x); // set ContentType of Code +// rv = bestT.y.x; + rv = bestT; + } + } + } else { + trans.checkpoint("No Match found for Accept"); + } + } + } + return rv; + } + + /** + * Print on String Builder content related to specific Code + * + * This is for Reporting and Debugging purposes, so the content is not cached. + * + * If code is "null", then all content is matched + * + * @param code + * @return + */ + public StringBuilder relatedTo(HttpCode code, StringBuilder sb) { + boolean first = true; + for(Pair, List>>> pair : types) { + if(code==null || pair.y.x == code) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(pair.x); + for(Pair prop : pair.y.y) { + // Don't print "Q". it's there for internal use, but it is only meaningful for "Accepts" + if(!prop.x.equals(Q) || !prop.y.equals(1f) ) { + sb.append(';'); + sb.append(prop.x); + sb.append('='); + sb.append(prop.y); + } + } + } + } + return sb; + } + + public List> getContent(HttpCode code) { + for(Pair, List>>> pair : types) { + if(pair.y.x == code) { + return pair.y.y; + } + } + return null; + } + + public String toString() { + return relatedTo(null,new StringBuilder()).toString(); + } + + public void api(RouteReport tr) { + // Need to build up a map, because Prop entries can be in several places. + HashMap,StringBuilder> psb = new HashMap<>(); + StringBuilder temp; + tr.desc = null; + + // Read through Code/TypeCode trees for all accepted Typecodes + for(Pair, List>>> tc : types) { + // If new, then it's new Code set, create prefix content + if((temp=psb.get(tc.y.x))==null) { + psb.put(tc.y.x,temp=new StringBuilder()); + if(tr.desc==null) { + tr.desc = tc.y.x.desc(); + } + } else { + temp.append(','); + } + temp.append(tc.x); - // add all properties - for(Pair props : tc.y.y) { - temp.append(';'); - temp.append(props.x); - temp.append('='); - temp.append(props.y); - } - } - // Gather all ContentType possibilities for the same code together - - for(StringBuilder sb : psb.values()) { - tr.contextTypes.add(sb.toString()); - } - } + // add all properties + for(Pair props : tc.y.y) { + temp.append(';'); + temp.append(props.x); + temp.append('='); + temp.append(props.y); + } + } + // Gather all ContentType possibilities for the same code together + + for(StringBuilder sb : psb.values()) { + tr.contextTypes.add(sb.toString()); + } + } - public String first() { - if(types.size()>0) { - return types.get(0).x; - } - return null; - } - - } \ No newline at end of file + public String first() { + if(types.size()>0) { + return types.get(0).x; + } + return null; + } + + } \ No newline at end of file diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java index ce0981fe..f4818579 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java @@ -29,65 +29,65 @@ package org.onap.aaf.auth.rserv; * */ public class Version { - private Object[] parts; + private Object[] parts; - public Version(String v) { - String sparts[] = v.split("\\."); - parts = new Object[sparts.length]; - System.arraycopy(sparts, 0, parts, 0, sparts.length); - if(parts.length>1) { // has at least a minor - try { - parts[1]=Integer.decode(sparts[1]); // minor elements need to be converted to Integer for comparison - } catch (NumberFormatException e) { - // it's ok, leave it as a string - parts[1]=sparts[1]; // This useless piece of code forced by Sonar which calls empty Exceptions "Blockers". - } - } - } + public Version(String v) { + String sparts[] = v.split("\\."); + parts = new Object[sparts.length]; + System.arraycopy(sparts, 0, parts, 0, sparts.length); + if(parts.length>1) { // has at least a minor + try { + parts[1]=Integer.decode(sparts[1]); // minor elements need to be converted to Integer for comparison + } catch (NumberFormatException e) { + // it's ok, leave it as a string + parts[1]=sparts[1]; // This useless piece of code forced by Sonar which calls empty Exceptions "Blockers". + } + } + } - public boolean equals(Object obj) { - if(obj instanceof Version) { - Version ver = (Version)obj; - int length = Math.min(parts.length, ver.parts.length); - for(int i=0;i extends RServlet { - public final Access access; - public final ENV env; - private AAFConHttp aafCon; + public final Access access; + public final ENV env; + private AAFConHttp aafCon; - public final String app_name; - public final String app_version; - public final String app_interface_version; - public final String ROOT_NS; + public final String app_name; + public final String app_version; + public final String app_interface_version; + public final String ROOT_NS; public AbsService(final Access access, final ENV env) throws CadiException { - Define.set(access); - ROOT_NS = Define.ROOT_NS(); - this.access = access; - this.env = env; + Define.set(access); + ROOT_NS = Define.ROOT_NS(); + this.access = access; + this.env = env; - String component = access.getProperty(Config.AAF_COMPONENT, null); - final String[] locator_deploy; - - if(component == null) { - locator_deploy = null; - } else { - locator_deploy = Split.splitTrim(':', component); - } - - if(component == null || locator_deploy==null || locator_deploy.length<2) { - throw new CadiException("AAF Component must include the " + Config.AAF_COMPONENT + " property, ::[] registrants(final int port) throws CadiException, LocatorException; - // Lazy Instantiation + // Lazy Instantiation public synchronized AAFConHttp aafCon() throws CadiException, LocatorException { - if(aafCon==null) { - if(access.getProperty(Config.AAF_URL,null)!=null) { - aafCon = _newAAFConHttp(); - } else { - throw new CadiException("AAFCon cannot be constructed without " + Config.AAF_URL); - } - } - return aafCon; + if(aafCon==null) { + if(access.getProperty(Config.AAF_URL,null)!=null) { + aafCon = _newAAFConHttp(); + } else { + throw new CadiException("AAFCon cannot be constructed without " + Config.AAF_URL); + } + } + return aafCon; } /** @@ -136,52 +136,52 @@ public abstract class AbsService exte * @return * @throws LocatorException */ - protected synchronized AAFConHttp _newAAFConHttp() throws CadiException, LocatorException { - if(aafCon==null) { - aafCon = new AAFConHttp(access); - } - return aafCon; + protected synchronized AAFConHttp _newAAFConHttp() throws CadiException, LocatorException { + if(aafCon==null) { + aafCon = new AAFConHttp(access); + } + return aafCon; - } + } // This is a method, so we can overload for AAFAPI public String aaf_url() { - return access.getProperty(Config.AAF_URL, null); + return access.getProperty(Config.AAF_URL, null); } - public Rcli client() throws CadiException { - return aafCon.client(Config.AAF_DEFAULT_VERSION); - } + public Rcli client() throws CadiException { + return aafCon.client(Config.AAF_DEFAULT_VERSION); + } - public Rcli clientAsUser(TaggedPrincipal p) throws CadiException { - return aafCon.client(Config.AAF_DEFAULT_VERSION).forUser( - new HTransferSS(p,app_name, aafCon.securityInfo())); - } + public Rcli clientAsUser(TaggedPrincipal p) throws CadiException { + return aafCon.client(Config.AAF_DEFAULT_VERSION).forUser( + new HTransferSS(p,app_name, aafCon.securityInfo())); + } - public RET clientAsUser(TaggedPrincipal p,Retryable retryable) throws APIException, LocatorException, CadiException { - return aafCon.hman().best(new HTransferSS(p,app_name, aafCon.securityInfo()), retryable); - } - - protected static final String loadFromArgOrSystem(final Properties props, final String tag, final String args[], final String def) { - String tagEQ = tag + '='; - String value; - for(String arg : args) { - if(arg.startsWith(tagEQ)) { - props.put(tag, value=arg.substring(tagEQ.length())); - return value; - } - } - // check System.properties - value = System.getProperty(tag); - if(value!=null) { - props.put(tag, value); - return value; - } - - if(def!=null) { - props.put(tag,def); - } - return def; - } + public RET clientAsUser(TaggedPrincipal p,Retryable retryable) throws APIException, LocatorException, CadiException { + return aafCon.hman().best(new HTransferSS(p,app_name, aafCon.securityInfo()), retryable); + } + + protected static final String loadFromArgOrSystem(final Properties props, final String tag, final String args[], final String def) { + String tagEQ = tag + '='; + String value; + for(String arg : args) { + if(arg.startsWith(tagEQ)) { + props.put(tag, value=arg.substring(tagEQ.length())); + return value; + } + } + // check System.properties + value = System.getProperty(tag); + if(value!=null) { + props.put(tag, value); + return value; + } + + if(def!=null) { + props.put(tag,def); + } + return def; + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java index 1a6c54d7..f14d6c32 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java @@ -29,67 +29,67 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.rosetta.env.RosettaEnv; public abstract class AbsServiceStarter implements ServiceStarter { - private Registrar registrar; - private boolean do_register; - protected AbsService service; + private Registrar registrar; + private boolean do_register; + protected AbsService service; - public AbsServiceStarter(final AbsService service) { - this.service = service; - try { - OrganizationFactory.init(service.env); - } catch (OrganizationException e) { - service.access.log(e, "Missing defined Organzation Plugins"); - System.exit(3); - } - // do_register - this is used for specialty Debug Situations. Developer can create an Instance for a remote system - // for Debugging purposes without fear that real clients will start to call your debug instance - do_register = !"TRUE".equalsIgnoreCase(access().getProperty("aaf_locate_no_register",null)); - _propertyAdjustment(); - } - - public abstract void _start(RServlet rserv) throws Exception; - public abstract void _propertyAdjustment(); - - public ENV env() { - return service.env; - } - - public Access access() { - return service.access; - } + public AbsServiceStarter(final AbsService service) { + this.service = service; + try { + OrganizationFactory.init(service.env); + } catch (OrganizationException e) { + service.access.log(e, "Missing defined Organzation Plugins"); + System.exit(3); + } + // do_register - this is used for specialty Debug Situations. Developer can create an Instance for a remote system + // for Debugging purposes without fear that real clients will start to call your debug instance + do_register = !"TRUE".equalsIgnoreCase(access().getProperty("aaf_locate_no_register",null)); + _propertyAdjustment(); + } + + public abstract void _start(RServlet rserv) throws Exception; + public abstract void _propertyAdjustment(); + + public ENV env() { + return service.env; + } + + public Access access() { + return service.access; + } - @Override - public final void start() throws Exception { - _start(service); - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - shutdown(); - } - }); - } + @Override + public final void start() throws Exception { + _start(service); + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + shutdown(); + } + }); + } - @SafeVarargs - public final synchronized void register(final Registrant ... registrants) { - if(do_register) { - if(registrar==null) { - registrar = new Registrar(env(),false); - } - for(Registrant r : registrants) { - registrar.register(r); - } - } - } + @SafeVarargs + public final synchronized void register(final Registrant ... registrants) { + if(do_register) { + if(registrar==null) { + registrar = new Registrar(env(),false); + } + for(Registrant r : registrants) { + registrar.register(r); + } + } + } - @Override + @Override public void shutdown() { - if(registrar!=null) { - registrar.close(env()); - registrar=null; - } - if(service!=null) { - service.destroy(); - } + if(registrar!=null) { + registrar.close(env()); + registrar=null; + } + if(service!=null) { + service.destroy(); + } } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java index cefc7a23..a0dafed1 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java @@ -57,213 +57,213 @@ import org.onap.aaf.misc.rosetta.env.RosettaEnv; public class JettyServiceStarter extends AbsServiceStarter { - private boolean secure; + private boolean secure; - public JettyServiceStarter(final AbsService service) throws OrganizationException { - super(service); - secure = true; - } - - /** - * Specifically set this Service starter to Insecure (HTTP) Mode. - * @return - */ - public JettyServiceStarter insecure() { - secure = false; - return this; - } + public JettyServiceStarter(final AbsService service) throws OrganizationException { + super(service); + secure = true; + } + + /** + * Specifically set this Service starter to Insecure (HTTP) Mode. + * @return + */ + public JettyServiceStarter insecure() { + secure = false; + return this; + } -// @Override -// public void _propertyAdjustment() { -// Properties props = access().getProperties(); -// Object temp = null; -// // Critical - if no Security Protocols set, then set it. We'll just get messed up if not -// if((temp=props.get(Config.CADI_PROTOCOLS))==null) { -// if((temp=props.get(Config.HTTPS_PROTOCOLS))==null) { -// props.put(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT); -// } else { -// props.put(Config.CADI_PROTOCOLS, temp); -// } -// } -// -// if("1.7".equals(System.getProperty("java.specification.version"))) { -// System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); -// } -// System.setProperty(Config.HTTPS_CIPHER_SUITES, temp.toString()); -// } +// @Override +// public void _propertyAdjustment() { +// Properties props = access().getProperties(); +// Object temp = null; +// // Critical - if no Security Protocols set, then set it. We'll just get messed up if not +// if((temp=props.get(Config.CADI_PROTOCOLS))==null) { +// if((temp=props.get(Config.HTTPS_PROTOCOLS))==null) { +// props.put(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT); +// } else { +// props.put(Config.CADI_PROTOCOLS, temp); +// } +// } +// +// if("1.7".equals(System.getProperty("java.specification.version"))) { +// System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); +// } +// System.setProperty(Config.HTTPS_CIPHER_SUITES, temp.toString()); +// } - @Override - public void _propertyAdjustment() { -// System.setProperty("com.sun.management.jmxremote.port", "8081"); - Properties props = access().getProperties(); - Object httpproto = null; - // Critical - if no Security Protocols set, then set it. We'll just get messed up if not - if((httpproto=props.get(Config.CADI_PROTOCOLS))==null) { - if((httpproto=props.get(Config.HTTPS_PROTOCOLS))==null) { - props.put(Config.CADI_PROTOCOLS, (httpproto=SecurityInfo.HTTPS_PROTOCOLS_DEFAULT)); - } else { - props.put(Config.CADI_PROTOCOLS, httpproto); - } - } - - if("1.7".equals(System.getProperty("java.specification.version")) && (httpproto==null || (httpproto instanceof String && ((String)httpproto).contains("TLSv1.2")))) { - System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); - } - } + @Override + public void _propertyAdjustment() { +// System.setProperty("com.sun.management.jmxremote.port", "8081"); + Properties props = access().getProperties(); + Object httpproto = null; + // Critical - if no Security Protocols set, then set it. We'll just get messed up if not + if((httpproto=props.get(Config.CADI_PROTOCOLS))==null) { + if((httpproto=props.get(Config.HTTPS_PROTOCOLS))==null) { + props.put(Config.CADI_PROTOCOLS, (httpproto=SecurityInfo.HTTPS_PROTOCOLS_DEFAULT)); + } else { + props.put(Config.CADI_PROTOCOLS, httpproto); + } + } + + if("1.7".equals(System.getProperty("java.specification.version")) && (httpproto==null || (httpproto instanceof String && ((String)httpproto).contains("TLSv1.2")))) { + System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); + } + } - @Override - public void _start(RServlet rserv) throws Exception { - String hostname = access().getProperty(Config.HOSTNAME, null); - if(hostname==null) { - hostname = Inet4Address.getLocalHost().getHostName(); - } - final int port = Integer.parseInt(access().getProperty("port","0")); - final String keystore = access().getProperty(Config.CADI_KEYSTORE, null); - final int IDLE_TIMEOUT = Integer.parseInt(access().getProperty(Config.AAF_CONN_IDLE_TIMEOUT, Config.AAF_CONN_IDLE_TIMEOUT_DEF)); - Server server = new Server(); - - ServerConnector conn; - String protocol; - if(!secure || keystore==null) { - conn = new ServerConnector(server); - protocol = "http"; - } else { - protocol = "https"; + @Override + public void _start(RServlet rserv) throws Exception { + String hostname = access().getProperty(Config.HOSTNAME, null); + if(hostname==null) { + hostname = Inet4Address.getLocalHost().getHostName(); + } + final int port = Integer.parseInt(access().getProperty("port","0")); + final String keystore = access().getProperty(Config.CADI_KEYSTORE, null); + final int IDLE_TIMEOUT = Integer.parseInt(access().getProperty(Config.AAF_CONN_IDLE_TIMEOUT, Config.AAF_CONN_IDLE_TIMEOUT_DEF)); + Server server = new Server(); + + ServerConnector conn; + String protocol; + if(!secure || keystore==null) { + conn = new ServerConnector(server); + protocol = "http"; + } else { + protocol = "https"; - String keystorePassword = access().getProperty(Config.CADI_KEYSTORE_PASSWORD, null); - if(keystorePassword==null) { - throw new CadiException("No Keystore Password configured for " + keystore); - } - SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath(keystore); - String temp; - sslContextFactory.setKeyStorePassword(temp=access().decrypt(keystorePassword, true)); // don't allow unencrypted - sslContextFactory.setKeyManagerPassword(temp); - temp=null; // don't leave lying around - - String truststore = access().getProperty(Config.CADI_TRUSTSTORE, null); - if(truststore!=null) { - String truststorePassword = access().getProperty(Config.CADI_TRUSTSTORE_PASSWORD, null); - if(truststorePassword==null) { - throw new CadiException("No Truststore Password configured for " + truststore); - } - sslContextFactory.setTrustStorePath(truststore); - sslContextFactory.setTrustStorePassword(access().decrypt(truststorePassword, true)); - } - // Be able to accept only certain protocols, i.e. TLSv1.1+ - final String[] protocols = Split.splitTrim(',', access().getProperty(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT)); - sslContextFactory.setIncludeProtocols(protocols); - - // Want to use Client Certificates, if they exist. - sslContextFactory.setWantClientAuth(true); - - // Optional future checks. - // sslContextFactory.setValidateCerts(true); - // sslContextFactory.setValidatePeerCerts(true); - // sslContextFactory.setEnableCRLDP(false); - // sslContextFactory.setEnableOCSP(false); - String certAlias = access().getProperty(Config.CADI_ALIAS, null); - if(certAlias!=null) { - sslContextFactory.setCertAlias(certAlias); - } - - HttpConfiguration httpConfig = new HttpConfiguration(); - httpConfig.setSecureScheme(protocol); - httpConfig.setSecurePort(port); - httpConfig.addCustomizer(new SecureRequestCustomizer()); - // httpConfig.setOutputBufferSize(32768); Not sure why take this setting - - conn = new ServerConnector(server, - new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()), - new HttpConnectionFactory(httpConfig) - ); - } - - // Setup JMX - // TODO trying to figure out how to set up/log ports -// MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); -// MBeanContainer mbContainer=new MBeanContainer(mbeanServer); -// server.addEventListener(mbContainer); -// server.addBean(mbContainer); - - // Add loggers MBean to server (will be picked up by MBeanContainer above) -// server.addBean(Log.getLog()); - - conn.setHost(hostname); - conn.setPort(port); - conn.setIdleTimeout(IDLE_TIMEOUT); - server.addConnector(conn); - - server.setHandler(new AbstractHandler() { - private FilterChain fc = buildFilterChain(service,new FilterChain() { - @Override - public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException { - rserv.service(req, resp); - } - }); - - @Override - public void handle(String target, Request baseRequest, HttpServletRequest hreq, HttpServletResponse hresp) throws IOException, ServletException { - try { - fc.doFilter(hreq,hresp); - } catch (Exception e) { - service.access.log(e, "Error Processing " + target); - hresp.setStatus(500 /* Service Error */); - } - baseRequest.setHandled(true); - } - } - ); - - try { - access().printf(Level.INIT, "Starting service on %s:%d (%s)",hostname,port,InetAddress.getLocalHost().getHostAddress()); - server.start(); - access().log(Level.INIT,server.dump()); - } catch (Exception e) { - access().log(e,"Error starting " + service.app_name); - String doExit = access().getProperty("cadi_exitOnFailure", "true"); - if (doExit == "true") { - System.exit(1); - } else { - throw e; - } - } - try { - register(service.registrants(port)); - access().printf(Level.INIT, "Starting Jetty Service for %s, version %s, on %s://%s:%d", service.app_name,service.app_version,protocol,hostname,port); - server.join(); - } catch(Exception e) { - access().log(e,"Error registering " + service.app_name); - String doExit = access().getProperty("cadi_exitOnFailure", "true"); - if (doExit == "true") { - System.exit(1); - } else { - throw e; - } - } - } + String keystorePassword = access().getProperty(Config.CADI_KEYSTORE_PASSWORD, null); + if(keystorePassword==null) { + throw new CadiException("No Keystore Password configured for " + keystore); + } + SslContextFactory sslContextFactory = new SslContextFactory(); + sslContextFactory.setKeyStorePath(keystore); + String temp; + sslContextFactory.setKeyStorePassword(temp=access().decrypt(keystorePassword, true)); // don't allow unencrypted + sslContextFactory.setKeyManagerPassword(temp); + temp=null; // don't leave lying around + + String truststore = access().getProperty(Config.CADI_TRUSTSTORE, null); + if(truststore!=null) { + String truststorePassword = access().getProperty(Config.CADI_TRUSTSTORE_PASSWORD, null); + if(truststorePassword==null) { + throw new CadiException("No Truststore Password configured for " + truststore); + } + sslContextFactory.setTrustStorePath(truststore); + sslContextFactory.setTrustStorePassword(access().decrypt(truststorePassword, true)); + } + // Be able to accept only certain protocols, i.e. TLSv1.1+ + final String[] protocols = Split.splitTrim(',', access().getProperty(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT)); + sslContextFactory.setIncludeProtocols(protocols); + + // Want to use Client Certificates, if they exist. + sslContextFactory.setWantClientAuth(true); + + // Optional future checks. + // sslContextFactory.setValidateCerts(true); + // sslContextFactory.setValidatePeerCerts(true); + // sslContextFactory.setEnableCRLDP(false); + // sslContextFactory.setEnableOCSP(false); + String certAlias = access().getProperty(Config.CADI_ALIAS, null); + if(certAlias!=null) { + sslContextFactory.setCertAlias(certAlias); + } + + HttpConfiguration httpConfig = new HttpConfiguration(); + httpConfig.setSecureScheme(protocol); + httpConfig.setSecurePort(port); + httpConfig.addCustomizer(new SecureRequestCustomizer()); + // httpConfig.setOutputBufferSize(32768); Not sure why take this setting + + conn = new ServerConnector(server, + new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()), + new HttpConnectionFactory(httpConfig) + ); + } + + // Setup JMX + // TODO trying to figure out how to set up/log ports +// MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); +// MBeanContainer mbContainer=new MBeanContainer(mbeanServer); +// server.addEventListener(mbContainer); +// server.addBean(mbContainer); + + // Add loggers MBean to server (will be picked up by MBeanContainer above) +// server.addBean(Log.getLog()); + + conn.setHost(hostname); + conn.setPort(port); + conn.setIdleTimeout(IDLE_TIMEOUT); + server.addConnector(conn); + + server.setHandler(new AbstractHandler() { + private FilterChain fc = buildFilterChain(service,new FilterChain() { + @Override + public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException { + rserv.service(req, resp); + } + }); + + @Override + public void handle(String target, Request baseRequest, HttpServletRequest hreq, HttpServletResponse hresp) throws IOException, ServletException { + try { + fc.doFilter(hreq,hresp); + } catch (Exception e) { + service.access.log(e, "Error Processing " + target); + hresp.setStatus(500 /* Service Error */); + } + baseRequest.setHandled(true); + } + } + ); + + try { + access().printf(Level.INIT, "Starting service on %s:%d (%s)",hostname,port,InetAddress.getLocalHost().getHostAddress()); + server.start(); + access().log(Level.INIT,server.dump()); + } catch (Exception e) { + access().log(e,"Error starting " + service.app_name); + String doExit = access().getProperty("cadi_exitOnFailure", "true"); + if (doExit == "true") { + System.exit(1); + } else { + throw e; + } + } + try { + register(service.registrants(port)); + access().printf(Level.INIT, "Starting Jetty Service for %s, version %s, on %s://%s:%d", service.app_name,service.app_version,protocol,hostname,port); + server.join(); + } catch(Exception e) { + access().log(e,"Error registering " + service.app_name); + String doExit = access().getProperty("cadi_exitOnFailure", "true"); + if (doExit == "true") { + System.exit(1); + } else { + throw e; + } + } + } - private FilterChain buildFilterChain(final AbsService as, final FilterChain doLast) throws CadiException, LocatorException { - Filter[] filters = as.filters(); - FilterChain fc = doLast; - for(int i=filters.length-1;i>=0;--i) { - fc = new FCImpl(filters[i],fc); - } - return fc; - } - - private class FCImpl implements FilterChain { - private Filter f; - private FilterChain next; - - public FCImpl(final Filter f, final FilterChain fc) { - this.f=f; - next = fc; - - } - @Override - public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException { - f.doFilter(req,resp, next); - } - } + private FilterChain buildFilterChain(final AbsService as, final FilterChain doLast) throws CadiException, LocatorException { + Filter[] filters = as.filters(); + FilterChain fc = doLast; + for(int i=filters.length-1;i>=0;--i) { + fc = new FCImpl(filters[i],fc); + } + return fc; + } + + private class FCImpl implements FilterChain { + private Filter f; + private FilterChain next; + + public FCImpl(final Filter f, final FilterChain fc) { + this.f=f; + next = fc; + + } + @Override + public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException { + f.doFilter(req,resp, next); + } + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java index 3fb250f9..31b76395 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java @@ -33,104 +33,104 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.log4j.LogFileNamer; public class Log4JLogIt implements LogIt { - protected static final String AAF_LOG4J_PREFIX = "aaf_log4j_prefix"; + protected static final String AAF_LOG4J_PREFIX = "aaf_log4j_prefix"; - // Sonar says cannot be static... it's ok. not too many PropAccesses created. - private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - - private final String service; - private final String audit; - private final String init; - private final String trace; + // Sonar says cannot be static... it's ok. not too many PropAccesses created. + private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + private final String service; + private final String audit; + private final String init; + private final String trace; - private final Logger lservice; - private final Logger laudit; - private final Logger linit; - private final Logger ltrace; + private final Logger lservice; + private final Logger laudit; + private final Logger linit; + private final Logger ltrace; - public Log4JLogIt(final String[] args, final String root) throws APIException { - String propsFile = getArgOrVM(AAF_LOG4J_PREFIX, args, "org.osaaf.aaf")+".log4j.props"; - String log_dir = getArgOrVM(Config.CADI_LOGDIR,args,"/opt/app/osaaf/logs"); - String etc_dir = getArgOrVM(Config.CADI_ETCDIR,args,"/opt/app/osaaf/etc"); - String log_level = getArgOrVM(Config.CADI_LOGLEVEL,args,"INFO"); - File logs = new File(log_dir); - if(!logs.isDirectory()) { - logs.delete(); - } - if(!logs.exists()) { - logs.mkdirs(); - } + public Log4JLogIt(final String[] args, final String root) throws APIException { + String propsFile = getArgOrVM(AAF_LOG4J_PREFIX, args, "org.osaaf.aaf")+".log4j.props"; + String log_dir = getArgOrVM(Config.CADI_LOGDIR,args,"/opt/app/osaaf/logs"); + String etc_dir = getArgOrVM(Config.CADI_ETCDIR,args,"/opt/app/osaaf/etc"); + String log_level = getArgOrVM(Config.CADI_LOGLEVEL,args,"INFO"); + File logs = new File(log_dir); + if(!logs.isDirectory()) { + logs.delete(); + } + if(!logs.exists()) { + logs.mkdirs(); + } - if(System.getProperty("log4j.configuration")==null) { - System.setProperty("log4j.configuration", etc_dir+'/'+propsFile); - } - LogFileNamer lfn = new LogFileNamer(log_dir,root); - try { - service=lfn.setAppender("service"); // when name is split, i.e. authz|service, the Appender is "authz", and "service" - audit=lfn.setAppender("audit"); // is part of the log-file name - init=lfn.setAppender("init"); - trace=lfn.setAppender("trace"); + if(System.getProperty("log4j.configuration")==null) { + System.setProperty("log4j.configuration", etc_dir+'/'+propsFile); + } + LogFileNamer lfn = new LogFileNamer(log_dir,root); + try { + service=lfn.setAppender("service"); // when name is split, i.e. authz|service, the Appender is "authz", and "service" + audit=lfn.setAppender("audit"); // is part of the log-file name + init=lfn.setAppender("init"); + trace=lfn.setAppender("trace"); - lservice = Logger.getLogger(service); - laudit = Logger.getLogger(audit); - linit = Logger.getLogger(init); - ltrace = Logger.getLogger(trace); - - lfn.configure(etc_dir,propsFile, log_level); - } catch (IOException e) { - throw new APIException(e); - } - } - - private static final String getArgOrVM(final String tag, final String args[], final String def) { - String tagEQ = tag + '='; - String value; - for(String arg : args) { - if(arg.startsWith(tagEQ)) { - return arg.substring(tagEQ.length()); - } - } - // check System.properties - value = System.getProperty(tag); - if(value!=null) { - return value; - } - - return def; - } + lservice = Logger.getLogger(service); + laudit = Logger.getLogger(audit); + linit = Logger.getLogger(init); + ltrace = Logger.getLogger(trace); + + lfn.configure(etc_dir,propsFile, log_level); + } catch (IOException e) { + throw new APIException(e); + } + } + + private static final String getArgOrVM(final String tag, final String args[], final String def) { + String tagEQ = tag + '='; + String value; + for(String arg : args) { + if(arg.startsWith(tagEQ)) { + return arg.substring(tagEQ.length()); + } + } + // check System.properties + value = System.getProperty(tag); + if(value!=null) { + return value; + } + + return def; + } - @Override - public void push(Level level, Object... elements) { - switch(level) { - case AUDIT: - laudit.warn(PropAccess.buildMsg(audit, iso8601, level, elements)); - break; - case INIT: - linit.warn(PropAccess.buildMsg(init, iso8601, level, elements)); - break; - case ERROR: - lservice.error(PropAccess.buildMsg(service, iso8601, level, elements)); - break; - case WARN: - lservice.warn(PropAccess.buildMsg(service, iso8601, level, elements)); - break; - case INFO: - lservice.info(PropAccess.buildMsg(service, iso8601, level, elements)); - break; - case DEBUG: - lservice.debug(PropAccess.buildMsg(service, iso8601, level, elements)); - break; - case TRACE: - ltrace.trace(PropAccess.buildMsg(service, iso8601, level, elements)); - break; - case NONE: - break; - default: - lservice.info(PropAccess.buildMsg(service, iso8601, level, elements)); - break; - - } + @Override + public void push(Level level, Object... elements) { + switch(level) { + case AUDIT: + laudit.warn(PropAccess.buildMsg(audit, iso8601, level, elements)); + break; + case INIT: + linit.warn(PropAccess.buildMsg(init, iso8601, level, elements)); + break; + case ERROR: + lservice.error(PropAccess.buildMsg(service, iso8601, level, elements)); + break; + case WARN: + lservice.warn(PropAccess.buildMsg(service, iso8601, level, elements)); + break; + case INFO: + lservice.info(PropAccess.buildMsg(service, iso8601, level, elements)); + break; + case DEBUG: + lservice.debug(PropAccess.buildMsg(service, iso8601, level, elements)); + break; + case TRACE: + ltrace.trace(PropAccess.buildMsg(service, iso8601, level, elements)); + break; + case NONE: + break; + default: + lservice.info(PropAccess.buildMsg(service, iso8601, level, elements)); + break; + + } - } + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/ServiceStarter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/ServiceStarter.java index 529d2d35..6f2d4cb9 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/ServiceStarter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/ServiceStarter.java @@ -21,6 +21,6 @@ package org.onap.aaf.auth.server; public interface ServiceStarter { - public void start() throws Exception; - public void shutdown(); + public void start() throws Exception; + public void shutdown(); } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java index 8302e771..eb721285 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java @@ -29,182 +29,182 @@ import org.onap.aaf.auth.layer.Result; public class Validator { - private static final String ESSENTIAL = "\\x25\\x28\\x29\\x2C-\\x2E\\x30-\\x39\\x3D\\x40-\\x5A\\x5F\\x61-\\x7A"; - private static final Pattern ESSENTIAL_CHARS = Pattern.compile("["+ESSENTIAL+"]+"); - public static final Pattern ACTION_CHARS = Pattern.compile( - "["+ESSENTIAL+"]+" + // All AlphaNumeric+ - "|\\*" // Just Star - ); - public static final Pattern INST_CHARS = Pattern.compile( - "["+ESSENTIAL+"]+[\\*]*" + // All AlphaNumeric+ possibly ending with * - "|\\*" + // Just Star - "|(([:/]\\*)|([:/][!]{0,1}["+ESSENTIAL+"]+[\\*]*[:/]*))+" // Key :asdf:*:sdf*:sdk - ); - public static final Pattern ID_CHARS = Pattern.compile("[\\w.-]+@[\\w.-]+"); - public static final Pattern NAME_CHARS = Pattern.compile("[\\w.-]+"); - public static final Pattern DESC_CHAR = Pattern.compile("["+ESSENTIAL+"\\x20]+"); - protected static List nsKeywords; - private final Pattern actionChars; - private final Pattern instChars; - private StringBuilder msgs; - - static { - nsKeywords = new ArrayList<>(); - nsKeywords.add(".access"); - nsKeywords.add(".owner"); - nsKeywords.add(".admin"); - nsKeywords.add(".member"); - nsKeywords.add(".perm"); - nsKeywords.add(".role"); - nsKeywords.add(".ns"); - nsKeywords.add(".cred"); - } - - public Validator() { - actionChars = ACTION_CHARS; - instChars = INST_CHARS; - } - - public final String errs() { - return msgs.toString(); - } - - public final Validator nullOrBlank(String name, String str) { - if(str==null) { - msg(name + " is null."); - } else if(str.length()==0) { - msg(name + " is blank."); - } - return this; - } - - public final Validator isNull(String name, Object o) { - if(o==null) { - msg(name + " is null."); - } - return this; - } - - protected final boolean noMatch(String str, Pattern p) { - return !p.matcher(str).matches(); - } - protected final boolean nob(String str, Pattern p) { - return str==null || !p.matcher(str).matches(); - } - - protected final void msg(String ... strs) { - if(msgs==null) { - msgs=new StringBuilder(); - } - for(String str : strs) { - msgs.append(str); - } - msgs.append('\n'); - } - - public final boolean err() { - return msgs!=null; - } - - public final Validator notOK(Result res) { - if(res==null) { - msgs.append("Result object is blank"); - } else if(res.notOK()) { - msgs.append(res.getClass().getSimpleName()).append(" is not OK"); - } - return this; - } - - protected Validator intRange(String text, int target, int start, int end) { - if(targetend) { - msg(text + " is out of range (" + start + '-' + end + ')'); - } - return this; - } - - protected Validator floatRange(String text, float target, float start, float end) { - if(targetend) { - msg(text + " is out of range (" + start + '-' + end + ')'); - } - return this; - } - - protected Validator description(String type, String description) { - if (description != null && noMatch(description, DESC_CHAR)) { - msg(type + " Description is invalid."); - } - return this; - } - - public final Validator permType(String type) { - if(nob(type,NAME_CHARS)) { - msg("Perm Type [" +type + "] is invalid."); - } - return this; - } - - public final Validator permType(String type, String ns) { - if(type==null) { - msg("Perm Type is null"); - } else if(ns==null) { - msg("Perm NS is null"); - } else if(nob(type,NAME_CHARS)) { - msg("Perm Type [" + (ns+(type.length()==0?"":'.')) + type + "] is invalid."); - } - return this; - } - - public final Validator permInstance(String instance) { - if(nob(instance,instChars)) { - msg("Perm Instance [" + instance + "] is invalid."); - } - return this; - } - - public final Validator permAction(String action) { - // TODO check for correct Splits? Type|Instance|Action ? - if(nob(action, actionChars)) { - msg("Perm Action [" + action + "] is invalid."); - } - return this; - } - - public final Validator role(String role) { - if(nob(role, NAME_CHARS)) { - msg("Role [" + role + "] is invalid."); - } - return this; - } - - public final Validator ns(String ns) { - if(ns==null) { - msg("NS is null"); - return this; - } else if(nob(ns,NAME_CHARS)) { - msg("NS [" + ns + "] is invalid."); - } - for(String s : nsKeywords) { - if(ns.endsWith(s)) { - msg("NS [" + ns + "] may not be named with NS keywords"); - break; - } - } - return this; - } - - public final Validator key(String key) { - if(nob(key,NAME_CHARS)) { - msg("NS Prop Key [" + key + "] is invalid"); - } - return this; - } - - public final Validator value(String value) { - if(nob(value,ESSENTIAL_CHARS)) { - msg("NS Prop value [" + value + "] is invalid"); - } - return this; - } + private static final String ESSENTIAL = "\\x25\\x28\\x29\\x2C-\\x2E\\x30-\\x39\\x3D\\x40-\\x5A\\x5F\\x61-\\x7A"; + private static final Pattern ESSENTIAL_CHARS = Pattern.compile("["+ESSENTIAL+"]+"); + public static final Pattern ACTION_CHARS = Pattern.compile( + "["+ESSENTIAL+"]+" + // All AlphaNumeric+ + "|\\*" // Just Star + ); + public static final Pattern INST_CHARS = Pattern.compile( + "["+ESSENTIAL+"]+[\\*]*" + // All AlphaNumeric+ possibly ending with * + "|\\*" + // Just Star + "|(([:/]\\*)|([:/][!]{0,1}["+ESSENTIAL+"]+[\\*]*[:/]*))+" // Key :asdf:*:sdf*:sdk + ); + public static final Pattern ID_CHARS = Pattern.compile("[\\w.-]+@[\\w.-]+"); + public static final Pattern NAME_CHARS = Pattern.compile("[\\w.-]+"); + public static final Pattern DESC_CHAR = Pattern.compile("["+ESSENTIAL+"\\x20]+"); + protected static List nsKeywords; + private final Pattern actionChars; + private final Pattern instChars; + private StringBuilder msgs; + + static { + nsKeywords = new ArrayList<>(); + nsKeywords.add(".access"); + nsKeywords.add(".owner"); + nsKeywords.add(".admin"); + nsKeywords.add(".member"); + nsKeywords.add(".perm"); + nsKeywords.add(".role"); + nsKeywords.add(".ns"); + nsKeywords.add(".cred"); + } + + public Validator() { + actionChars = ACTION_CHARS; + instChars = INST_CHARS; + } + + public final String errs() { + return msgs.toString(); + } + + public final Validator nullOrBlank(String name, String str) { + if(str==null) { + msg(name + " is null."); + } else if(str.length()==0) { + msg(name + " is blank."); + } + return this; + } + + public final Validator isNull(String name, Object o) { + if(o==null) { + msg(name + " is null."); + } + return this; + } + + protected final boolean noMatch(String str, Pattern p) { + return !p.matcher(str).matches(); + } + protected final boolean nob(String str, Pattern p) { + return str==null || !p.matcher(str).matches(); + } + + protected final void msg(String ... strs) { + if(msgs==null) { + msgs=new StringBuilder(); + } + for(String str : strs) { + msgs.append(str); + } + msgs.append('\n'); + } + + public final boolean err() { + return msgs!=null; + } + + public final Validator notOK(Result res) { + if(res==null) { + msgs.append("Result object is blank"); + } else if(res.notOK()) { + msgs.append(res.getClass().getSimpleName()).append(" is not OK"); + } + return this; + } + + protected Validator intRange(String text, int target, int start, int end) { + if(targetend) { + msg(text + " is out of range (" + start + '-' + end + ')'); + } + return this; + } + + protected Validator floatRange(String text, float target, float start, float end) { + if(targetend) { + msg(text + " is out of range (" + start + '-' + end + ')'); + } + return this; + } + + protected Validator description(String type, String description) { + if (description != null && noMatch(description, DESC_CHAR)) { + msg(type + " Description is invalid."); + } + return this; + } + + public final Validator permType(String type) { + if(nob(type,NAME_CHARS)) { + msg("Perm Type [" +type + "] is invalid."); + } + return this; + } + + public final Validator permType(String type, String ns) { + if(type==null) { + msg("Perm Type is null"); + } else if(ns==null) { + msg("Perm NS is null"); + } else if(nob(type,NAME_CHARS)) { + msg("Perm Type [" + (ns+(type.length()==0?"":'.')) + type + "] is invalid."); + } + return this; + } + + public final Validator permInstance(String instance) { + if(nob(instance,instChars)) { + msg("Perm Instance [" + instance + "] is invalid."); + } + return this; + } + + public final Validator permAction(String action) { + // TODO check for correct Splits? Type|Instance|Action ? + if(nob(action, actionChars)) { + msg("Perm Action [" + action + "] is invalid."); + } + return this; + } + + public final Validator role(String role) { + if(nob(role, NAME_CHARS)) { + msg("Role [" + role + "] is invalid."); + } + return this; + } + + public final Validator ns(String ns) { + if(ns==null) { + msg("NS is null"); + return this; + } else if(nob(ns,NAME_CHARS)) { + msg("NS [" + ns + "] is invalid."); + } + for(String s : nsKeywords) { + if(ns.endsWith(s)) { + msg("NS [" + ns + "] may not be named with NS keywords"); + break; + } + } + return this; + } + + public final Validator key(String key) { + if(nob(key,NAME_CHARS)) { + msg("NS Prop Key [" + key + "] is invalid"); + } + return this; + } + + public final Validator value(String value) { + if(nob(value,ESSENTIAL_CHARS)) { + msg("NS Prop value [" + value + "] is invalid"); + } + return this; + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java index 0f986f24..68f359c5 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java @@ -37,48 +37,48 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_Define { - private static final String AAF_NS_DOT = "AAF_NS."; - public static String ROOT_NS="NS.Not.Set"; - public static String ROOT_COMPANY=ROOT_NS; - Access acc; - @Mock - Env envMock; + private static final String AAF_NS_DOT = "AAF_NS."; + public static String ROOT_NS="NS.Not.Set"; + public static String ROOT_COMPANY=ROOT_NS; + Access acc; + @Mock + Env envMock; - @Before - public void setUp() throws CadiException{ - acc = mock(Access.class); - } - - @Test - public void testSet() throws CadiException { - PropAccess prop = new PropAccess(); - prop.setProperty(AAF_NS_DOT, AAF_NS_DOT); - prop.setProperty(Config.AAF_ROOT_NS, ".ns_Test"); - prop.setProperty(Config.AAF_ROOT_COMPANY, "company_Test"); - Define.set(prop); - Define.ROOT_NS(); - Define.ROOT_COMPANY(); - - PropAccess prop1 = new PropAccess(); - prop1.setProperty(AAF_NS_DOT, AAF_NS_DOT); - prop1.setProperty(Config.AAF_ROOT_NS, ".ns_Test"); - Define.set(prop1); - } + @Before + public void setUp() throws CadiException{ + acc = mock(Access.class); + } + + @Test + public void testSet() throws CadiException { + PropAccess prop = new PropAccess(); + prop.setProperty(AAF_NS_DOT, AAF_NS_DOT); + prop.setProperty(Config.AAF_ROOT_NS, ".ns_Test"); + prop.setProperty(Config.AAF_ROOT_COMPANY, "company_Test"); + Define.set(prop); + Define.ROOT_NS(); + Define.ROOT_COMPANY(); + + PropAccess prop1 = new PropAccess(); + prop1.setProperty(AAF_NS_DOT, AAF_NS_DOT); + prop1.setProperty(Config.AAF_ROOT_NS, ".ns_Test"); + Define.set(prop1); + } -// @Test //TODO: AAF-111 exception fix -// public void testRootNS() throws RuntimeException{ -// Define.ROOT_NS(); -// } +// @Test //TODO: AAF-111 exception fix +// public void testRootNS() throws RuntimeException{ +// Define.ROOT_NS(); +// } // -// @Test -// public void testRootCompany() throws RuntimeException{ -// Define.ROOT_COMPANY(); -// } +// @Test +// public void testRootCompany() throws RuntimeException{ +// Define.ROOT_COMPANY(); +// } - @Test - public void testVarReplace() { - Define.varReplace(AAF_NS_DOT); - Define.varReplace("test"); - } + @Test + public void testVarReplace() { + Define.varReplace(AAF_NS_DOT); + Define.varReplace("test"); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java index b30085fc..b170ae55 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java @@ -41,137 +41,137 @@ import org.onap.aaf.cadi.config.Config; public class JU_AuthzEnv { - AuthzEnv authzEnv; - ByteArrayOutputStream outStream; - ByteArrayOutputStream errStream; - enum Level {DEBUG, INFO, AUDIT, INIT, WARN, ERROR}; - - @Before - public void setUp() { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); - - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - - authzEnv = new AuthzEnv(); - } - - @After - public void tearDown() { - System.setOut(System.out); - System.setErr(System.err); - } - - @Test - @SuppressWarnings("unused") - public void testConstructors() { - AuthzEnv authzEnv1 = new AuthzEnv("Test"); - AuthzEnv authzEnv2 = new AuthzEnv((PropAccess)null); - AuthzEnv authzEnv3 = new AuthzEnv((Properties)null); - } - - @Test - public void testTransRate() { - Long Result = authzEnv.transRate(); - assertNotNull(Result); - } - - @Test - public void checkNewTransNoAvg() { - assertNotNull(authzEnv.newTransNoAvg()); - } - - @Test - public void checkNewTrans() { - assertNotNull(authzEnv.newTrans()); - } - - @Test - public void checkPropAccess() { - assertNotNull(authzEnv.access()); - } - - @Test - public void checkgetProperties() { //TODO:[GABE]No setter for this, add? - assertNotNull(authzEnv.getProperties()); - assertNotNull(authzEnv.getProperties("test")); - } - - @Test - public void checkPropertyGetters(){ - authzEnv.setProperty("key","value"); - assertEquals(authzEnv.getProperty("key"), "value"); - assertEquals(authzEnv.getProperty("key","value"), "value"); - } - - @Test - public void checkPropertySetters(){ - assertEquals(authzEnv.getProperty("key","value"), authzEnv.setProperty("key","value")); - } - - @Test(expected = IOException.class) - public void testDecryptException() throws IOException{ - authzEnv.setProperty(Config.CADI_KEYFILE, "test/keyfile"); - authzEnv.decrypt(null, false); - } - - @Test - public void testDecrypt() throws IOException{ - String encrypted = "encrypted"; - String Result = authzEnv.decrypt(encrypted, true); - assertEquals("encrypted",Result); - } - - @Test - public void testClassLoader() { - ClassLoader cLoad = mock(ClassLoader.class); - cLoad = authzEnv.classLoader(); - assertNotNull(cLoad); - } - - @Test - public void testLoad() throws IOException { - InputStream is = mock(InputStream.class); - authzEnv.load(is); - } - - @Test - public void testLog() { - Access.Level lvl = Access.Level.DEBUG; - Object msgs = null; - authzEnv.log(lvl, msgs); - } - - @Test - public void testLog1() { - - Exception e = new Exception(); - Object msgs = null; - authzEnv.log(e, msgs); - } - - @Test - public void testPrintf() { - Access.Level lvl = Access.Level.DEBUG; - Object msgs = null; - authzEnv.printf(lvl, "Test", msgs); - } - - @Test - public void testWillLog() { - Access.Level lvl = Access.Level.DEBUG; - Access.Level lvl1 = Access.Level.AUDIT; - boolean test = authzEnv.willLog(lvl); - assertFalse(test); - test = authzEnv.willLog(lvl1); - assertTrue(test); - } - - @Test - public void testSetLogLevel() { - Access.Level lvl = Access.Level.DEBUG; - authzEnv.setLogLevel(lvl); - } + AuthzEnv authzEnv; + ByteArrayOutputStream outStream; + ByteArrayOutputStream errStream; + enum Level {DEBUG, INFO, AUDIT, INIT, WARN, ERROR}; + + @Before + public void setUp() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + + authzEnv = new AuthzEnv(); + } + + @After + public void tearDown() { + System.setOut(System.out); + System.setErr(System.err); + } + + @Test + @SuppressWarnings("unused") + public void testConstructors() { + AuthzEnv authzEnv1 = new AuthzEnv("Test"); + AuthzEnv authzEnv2 = new AuthzEnv((PropAccess)null); + AuthzEnv authzEnv3 = new AuthzEnv((Properties)null); + } + + @Test + public void testTransRate() { + Long Result = authzEnv.transRate(); + assertNotNull(Result); + } + + @Test + public void checkNewTransNoAvg() { + assertNotNull(authzEnv.newTransNoAvg()); + } + + @Test + public void checkNewTrans() { + assertNotNull(authzEnv.newTrans()); + } + + @Test + public void checkPropAccess() { + assertNotNull(authzEnv.access()); + } + + @Test + public void checkgetProperties() { //TODO:[GABE]No setter for this, add? + assertNotNull(authzEnv.getProperties()); + assertNotNull(authzEnv.getProperties("test")); + } + + @Test + public void checkPropertyGetters(){ + authzEnv.setProperty("key","value"); + assertEquals(authzEnv.getProperty("key"), "value"); + assertEquals(authzEnv.getProperty("key","value"), "value"); + } + + @Test + public void checkPropertySetters(){ + assertEquals(authzEnv.getProperty("key","value"), authzEnv.setProperty("key","value")); + } + + @Test(expected = IOException.class) + public void testDecryptException() throws IOException{ + authzEnv.setProperty(Config.CADI_KEYFILE, "test/keyfile"); + authzEnv.decrypt(null, false); + } + + @Test + public void testDecrypt() throws IOException{ + String encrypted = "encrypted"; + String Result = authzEnv.decrypt(encrypted, true); + assertEquals("encrypted",Result); + } + + @Test + public void testClassLoader() { + ClassLoader cLoad = mock(ClassLoader.class); + cLoad = authzEnv.classLoader(); + assertNotNull(cLoad); + } + + @Test + public void testLoad() throws IOException { + InputStream is = mock(InputStream.class); + authzEnv.load(is); + } + + @Test + public void testLog() { + Access.Level lvl = Access.Level.DEBUG; + Object msgs = null; + authzEnv.log(lvl, msgs); + } + + @Test + public void testLog1() { + + Exception e = new Exception(); + Object msgs = null; + authzEnv.log(e, msgs); + } + + @Test + public void testPrintf() { + Access.Level lvl = Access.Level.DEBUG; + Object msgs = null; + authzEnv.printf(lvl, "Test", msgs); + } + + @Test + public void testWillLog() { + Access.Level lvl = Access.Level.DEBUG; + Access.Level lvl1 = Access.Level.AUDIT; + boolean test = authzEnv.willLog(lvl); + assertFalse(test); + test = authzEnv.willLog(lvl1); + assertTrue(test); + } + + @Test + public void testSetLogLevel() { + Access.Level lvl = Access.Level.DEBUG; + authzEnv.setLogLevel(lvl); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransFilter.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransFilter.java index ccfb01aa..e5b4209f 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransFilter.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransFilter.java @@ -49,62 +49,62 @@ import org.onap.aaf.misc.env.Trans.Metric; public class JU_AuthzTransFilter { - @Mock private AuthzEnv envMock; - @Mock private Connector connectorMock; - @Mock private TrustChecker tcMock; - @Mock private AuthzTrans authzTransMock; - @Mock private Object additionalTafLurs; - - private PropAccess access; + @Mock private AuthzEnv envMock; + @Mock private Connector connectorMock; + @Mock private TrustChecker tcMock; + @Mock private AuthzTrans authzTransMock; + @Mock private Object additionalTafLurs; + + private PropAccess access; - @Before - public void setUp() throws CadiException{ - MockitoAnnotations.initMocks(this); + @Before + public void setUp() throws CadiException{ + MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - when(envMock.access()).thenReturn(access); - } - - // TODO: These tests only work on the AT&T network. Fix them - Ian - @Test - public void testAuthenticated() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, CadiException { -// AuthzTransFilter filter = new AuthzTransFilter(envMock, connectorMock, tcMock); -// AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, (Object)null); -// Class c = aTF.getClass(); -// Class[] cArg = new Class[2]; -// cArg[0] = AuthzTrans.class; -// cArg[1] = Principal.class; //Steps to test a protected method -// Method authenticatedMethod = c.getDeclaredMethod("authenticated", cArg); -// authenticatedMethod.setAccessible(true); -// authenticatedMethod.invoke(aTF, authzTransMock, null); - } - - @Test - public void testTallyHo() throws CadiException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { -// Slot specialLogSlot = authzEnvMock.slot("SPECIAL_LOG_SLOT"); -// LogTarget lt = mock(LogTarget.class); -// AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, additionalTafLurs); -// TaggedPrincipal tPrin = mock(TaggedPrincipal.class); -// Metric met = new Metric(); -// met.total = 199.33F; -// met.entries = 15; -// met.buckets = new float[] {199.33F,99.33F}; -// Class c = aTF.getClass(); -// Class[] cArg = new Class[1]; -// cArg[0] = AuthzTrans.class; //Steps to test a protected method -// Method tallyHoMethod = c.getDeclaredMethod("tallyHo", cArg); + when(envMock.access()).thenReturn(access); + } + + // TODO: These tests only work on the AT&T network. Fix them - Ian + @Test + public void testAuthenticated() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, CadiException { +// AuthzTransFilter filter = new AuthzTransFilter(envMock, connectorMock, tcMock); +// AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, (Object)null); +// Class c = aTF.getClass(); +// Class[] cArg = new Class[2]; +// cArg[0] = AuthzTrans.class; +// cArg[1] = Principal.class; //Steps to test a protected method +// Method authenticatedMethod = c.getDeclaredMethod("authenticated", cArg); +// authenticatedMethod.setAccessible(true); +// authenticatedMethod.invoke(aTF, authzTransMock, null); + } + + @Test + public void testTallyHo() throws CadiException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { +// Slot specialLogSlot = authzEnvMock.slot("SPECIAL_LOG_SLOT"); +// LogTarget lt = mock(LogTarget.class); +// AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, additionalTafLurs); +// TaggedPrincipal tPrin = mock(TaggedPrincipal.class); +// Metric met = new Metric(); +// met.total = 199.33F; +// met.entries = 15; +// met.buckets = new float[] {199.33F,99.33F}; +// Class c = aTF.getClass(); +// Class[] cArg = new Class[1]; +// cArg[0] = AuthzTrans.class; //Steps to test a protected method +// Method tallyHoMethod = c.getDeclaredMethod("tallyHo", cArg); // -// when(authzTransMock.auditTrail(((LogTarget)any()), anyInt(), (StringBuilder)any(), anyInt(), anyInt())).thenReturn(met); -// tallyHoMethod.setAccessible(true); +// when(authzTransMock.auditTrail(((LogTarget)any()), anyInt(), (StringBuilder)any(), anyInt(), anyInt())).thenReturn(met); +// tallyHoMethod.setAccessible(true); // -// when(authzTransMock.get(specialLogSlot, false)).thenReturn(false); -// when(authzTransMock.warn()).thenReturn(lt); -// when(authzTransMock.info()).thenReturn(lt); -// tallyHoMethod.invoke(aTF, authzTransMock); +// when(authzTransMock.get(specialLogSlot, false)).thenReturn(false); +// when(authzTransMock.warn()).thenReturn(lt); +// when(authzTransMock.info()).thenReturn(lt); +// tallyHoMethod.invoke(aTF, authzTransMock); // -// when(authzTransMock.getUserPrincipal()).thenReturn(tPrin); -// tallyHoMethod.invoke(aTF, authzTransMock); - } - +// when(authzTransMock.getUserPrincipal()).thenReturn(tPrin); +// tallyHoMethod.invoke(aTF, authzTransMock); + } + } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransImpl.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransImpl.java index 317fb94a..8e6d5028 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransImpl.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransImpl.java @@ -50,120 +50,120 @@ import junit.framework.Assert; @RunWith(PowerMockRunner.class) public class JU_AuthzTransImpl { - AuthzTransImpl authzTransImpl; - @Mock - AuthzEnv authzEnvMock; - AuthzTransImpl trans1; - - private Organization org=null; - private AuthzTransImpl mockAuthzTransImpl; - private static HttpServletRequest req; - private static HttpServletResponse res; - private Lur lur1 = mock(Lur.class); - - @Before - public void setUp(){ - authzTransImpl = new AuthzTransImpl(authzEnvMock); - req = mock(HttpServletRequest.class); - authzTransImpl.set(req); - when(req.getParameter("request")).thenReturn("NotNull"); - authzTransImpl.set(req); - when(req.getParameter("request")).thenReturn(""); - authzTransImpl.set(req); - } - - @Test - public void testOrg() { - Organization result=null; - result = authzTransImpl.org(); - OrganizationFactory test = mock(OrganizationFactory.class); - //result = OrganizationFactory.obtain(authzTransImpl.env(), authzTransImpl.user()); - authzTransImpl.org(); - //when(test).thenReturn(null); - //assertTrue(true); - } - - @Mock - LogTarget logTargetMock; - - @Test - public void testLogAuditTrail(){ - - when(logTargetMock.isLoggable()).thenReturn(false); - authzTransImpl.logAuditTrail(logTargetMock); - when(logTargetMock.isLoggable()).thenReturn(true); - Env delegate = mock(Env.class); - //when(logTargetMock.isLoggable()).thenReturn(true);//TODO: Figure this out - //authzTransImpl.logAuditTrail(logTargetMock); - } - -// @Test //TODO:Fix this AAF-111 -// public void testSetUser() { -// Principal user = mock(Principal.class); -// authzTransImpl.setUser(user); -// Principal user1 = authzTransImpl.getUserPrincipal(); -// String username = user1.getName(); -// Assert.assertNotNull(user1); -// } - -// @Test //TODO:Fix this AAF-111 -// public void testUser() { -// Assert.assertEquals("n/a", authzTransImpl.user()); -// Principal user = mock(Principal.class); //Unsure how to modify name -// when(user.toString()).thenReturn("name"); -// when(user.getName()).thenReturn("name"); -// authzTransImpl.setUser(user); -// Assert.assertEquals("name", authzTransImpl.user()); -// } -// - @Test - public void testRequested() { - REQD_TYPE user = REQD_TYPE.move; - REQD_TYPE user1 = REQD_TYPE.future; - HttpServletRequest req = mock(HttpServletRequest.class); - String p = user1.name(); - boolean boolUser = authzTransImpl.requested(user); - Assert.assertEquals(false, boolUser); - Assert.assertNotNull(p); - authzTransImpl.requested(user,true); - when(authzTransImpl.requested(user)).thenReturn(null); - Assert.assertEquals(true, authzTransImpl.requested(user)); - /* String p1 = req.getParameter(user1.name()); //unable to access private method call in all instances - when(req.getParameter(user1.name())).thenReturn("test"); - authzTransImpl.requested(user,false); - */ - - - } - - @Test - public void testFish() { - mockAuthzTransImpl = mock(AuthzTransImpl.class); - Permission p = mock(Permission.class); - authzTransImpl.fish(p); - String str = "Test"; - lur1.createPerm(str); - when(p.match(p)).thenReturn(true); - authzTransImpl.setLur(lur1); - authzTransImpl.fish(p); - } - - @Test - public void testSetVariables() { //TODO: refactor this better - Assert.assertNull(authzTransImpl.agent()); - Assert.assertNull(authzTransImpl.ip()); - Assert.assertNull(authzTransImpl.path()); - Assert.assertNotNull(authzTransImpl.port()); - Assert.assertNull(authzTransImpl.meth()); - Assert.assertNull(authzTransImpl.getUserPrincipal()); - Assert.assertNotNull(authzTransImpl.user()); - } - - @Test - public void testNow() { - Date date = authzTransImpl.now(); - Assert.assertEquals(date,authzTransImpl.now()); - when(authzTransImpl.now()).thenReturn(null); - } - + AuthzTransImpl authzTransImpl; + @Mock + AuthzEnv authzEnvMock; + AuthzTransImpl trans1; + + private Organization org=null; + private AuthzTransImpl mockAuthzTransImpl; + private static HttpServletRequest req; + private static HttpServletResponse res; + private Lur lur1 = mock(Lur.class); + + @Before + public void setUp(){ + authzTransImpl = new AuthzTransImpl(authzEnvMock); + req = mock(HttpServletRequest.class); + authzTransImpl.set(req); + when(req.getParameter("request")).thenReturn("NotNull"); + authzTransImpl.set(req); + when(req.getParameter("request")).thenReturn(""); + authzTransImpl.set(req); + } + + @Test + public void testOrg() { + Organization result=null; + result = authzTransImpl.org(); + OrganizationFactory test = mock(OrganizationFactory.class); + //result = OrganizationFactory.obtain(authzTransImpl.env(), authzTransImpl.user()); + authzTransImpl.org(); + //when(test).thenReturn(null); + //assertTrue(true); + } + + @Mock + LogTarget logTargetMock; + + @Test + public void testLogAuditTrail(){ + + when(logTargetMock.isLoggable()).thenReturn(false); + authzTransImpl.logAuditTrail(logTargetMock); + when(logTargetMock.isLoggable()).thenReturn(true); + Env delegate = mock(Env.class); + //when(logTargetMock.isLoggable()).thenReturn(true);//TODO: Figure this out + //authzTransImpl.logAuditTrail(logTargetMock); + } + +// @Test //TODO:Fix this AAF-111 +// public void testSetUser() { +// Principal user = mock(Principal.class); +// authzTransImpl.setUser(user); +// Principal user1 = authzTransImpl.getUserPrincipal(); +// String username = user1.getName(); +// Assert.assertNotNull(user1); +// } + +// @Test //TODO:Fix this AAF-111 +// public void testUser() { +// Assert.assertEquals("n/a", authzTransImpl.user()); +// Principal user = mock(Principal.class); //Unsure how to modify name +// when(user.toString()).thenReturn("name"); +// when(user.getName()).thenReturn("name"); +// authzTransImpl.setUser(user); +// Assert.assertEquals("name", authzTransImpl.user()); +// } +// + @Test + public void testRequested() { + REQD_TYPE user = REQD_TYPE.move; + REQD_TYPE user1 = REQD_TYPE.future; + HttpServletRequest req = mock(HttpServletRequest.class); + String p = user1.name(); + boolean boolUser = authzTransImpl.requested(user); + Assert.assertEquals(false, boolUser); + Assert.assertNotNull(p); + authzTransImpl.requested(user,true); + when(authzTransImpl.requested(user)).thenReturn(null); + Assert.assertEquals(true, authzTransImpl.requested(user)); + /* String p1 = req.getParameter(user1.name()); //unable to access private method call in all instances + when(req.getParameter(user1.name())).thenReturn("test"); + authzTransImpl.requested(user,false); + */ + + + } + + @Test + public void testFish() { + mockAuthzTransImpl = mock(AuthzTransImpl.class); + Permission p = mock(Permission.class); + authzTransImpl.fish(p); + String str = "Test"; + lur1.createPerm(str); + when(p.match(p)).thenReturn(true); + authzTransImpl.setLur(lur1); + authzTransImpl.fish(p); + } + + @Test + public void testSetVariables() { //TODO: refactor this better + Assert.assertNull(authzTransImpl.agent()); + Assert.assertNull(authzTransImpl.ip()); + Assert.assertNull(authzTransImpl.path()); + Assert.assertNotNull(authzTransImpl.port()); + Assert.assertNull(authzTransImpl.meth()); + Assert.assertNull(authzTransImpl.getUserPrincipal()); + Assert.assertNotNull(authzTransImpl.user()); + } + + @Test + public void testNow() { + Date date = authzTransImpl.now(); + Assert.assertEquals(date,authzTransImpl.now()); + when(authzTransImpl.now()).thenReturn(null); + } + } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java index f1243513..4d233990 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java @@ -49,71 +49,71 @@ import org.onap.aaf.misc.env.Trans.Metric; @RunWith(MockitoJUnitRunner.class) public class JU_AuthzTransOnlyFilter { - AuthzTransFilter authzTransFilter; - AuthzEnv authzEnvMock = mock(AuthzEnv.class); - Connector connectorMock = mock(Connector.class); - TrustChecker trustCheckerMock = mock(TrustChecker.class); - AuthzTrans authzTransMock = mock(AuthzTrans.class); - Object additionalTafLurs = mock(Object.class); - ServletRequest servletRequestMock = mock(ServletRequest.class); - AuthzTransOnlyFilter authzTransOnlyFilter; + AuthzTransFilter authzTransFilter; + AuthzEnv authzEnvMock = mock(AuthzEnv.class); + Connector connectorMock = mock(Connector.class); + TrustChecker trustCheckerMock = mock(TrustChecker.class); + AuthzTrans authzTransMock = mock(AuthzTrans.class); + Object additionalTafLurs = mock(Object.class); + ServletRequest servletRequestMock = mock(ServletRequest.class); + AuthzTransOnlyFilter authzTransOnlyFilter; - @Before - public void setUp(){ - authzTransOnlyFilter = new AuthzTransOnlyFilter(authzEnvMock); - } + @Before + public void setUp(){ + authzTransOnlyFilter = new AuthzTransOnlyFilter(authzEnvMock); + } - /*@Test - public void testProtected() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method newTransMethod = AuthzTransFilter.class.getDeclaredMethod("newTrans"); - newTransMethod.setAccessible(true); + /*@Test + public void testProtected() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method newTransMethod = AuthzTransFilter.class.getDeclaredMethod("newTrans"); + newTransMethod.setAccessible(true); - newTransMethod.invoke(authzTransFilter); - }*/ + newTransMethod.invoke(authzTransFilter); + }*/ - @Test - public void testStart() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); - Class c = aTF.getClass(); - Class[] cArg = new Class[2]; - cArg[0] = AuthzTrans.class; - cArg[1] = ServletRequest.class; //Steps to test a protected method - Method startMethod = c.getDeclaredMethod("start", cArg); - startMethod.setAccessible(true); - //startMethod.invoke(aTF, authzTransMock, servletRequestMock); - } + @Test + public void testStart() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); + Class c = aTF.getClass(); + Class[] cArg = new Class[2]; + cArg[0] = AuthzTrans.class; + cArg[1] = ServletRequest.class; //Steps to test a protected method + Method startMethod = c.getDeclaredMethod("start", cArg); + startMethod.setAccessible(true); + //startMethod.invoke(aTF, authzTransMock, servletRequestMock); + } - @Test - public void testAuthenticated() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, CadiException { - TaggedPrincipal p = mock(TaggedPrincipal.class); - AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); - Class c = aTF.getClass(); - Class[] cArg = new Class[2]; - cArg[0] = AuthzTrans.class; - cArg[1] = TaggedPrincipal.class; //Steps to test a protected method - Method authenticatedMethod = c.getDeclaredMethod("authenticated", cArg); - authenticatedMethod.setAccessible(true); - authenticatedMethod.invoke(aTF,authzTransMock, null); - } + @Test + public void testAuthenticated() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, CadiException { + TaggedPrincipal p = mock(TaggedPrincipal.class); + AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); + Class c = aTF.getClass(); + Class[] cArg = new Class[2]; + cArg[0] = AuthzTrans.class; + cArg[1] = TaggedPrincipal.class; //Steps to test a protected method + Method authenticatedMethod = c.getDeclaredMethod("authenticated", cArg); + authenticatedMethod.setAccessible(true); + authenticatedMethod.invoke(aTF,authzTransMock, null); + } - @Test - public void testTallyHo() throws CadiException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); - LogTarget log = mock(LogTarget.class); - Metric met = new Metric(); - met.total = 199.33F; - met.entries = 15; - met.buckets = new float[] {199.33F,99.33F}; - Class c = aTF.getClass(); - Class[] cArg = new Class[1]; - cArg[0] = AuthzTrans.class; //Steps to test a protected method - StringBuilder sb = new StringBuilder("AuditTrail\n"); - when(authzTransMock.auditTrail(anyInt(),(StringBuilder)any(),anyInt(),anyInt())).thenReturn(met); - when(authzTransMock.info()).thenReturn(log); - doNothing().when(log).log((StringBuilder)any()); - Method tallyHoMethod = c.getDeclaredMethod("tallyHo", cArg); - tallyHoMethod.setAccessible(true); - tallyHoMethod.invoke(aTF,authzTransMock); - } + @Test + public void testTallyHo() throws CadiException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); + LogTarget log = mock(LogTarget.class); + Metric met = new Metric(); + met.total = 199.33F; + met.entries = 15; + met.buckets = new float[] {199.33F,99.33F}; + Class c = aTF.getClass(); + Class[] cArg = new Class[1]; + cArg[0] = AuthzTrans.class; //Steps to test a protected method + StringBuilder sb = new StringBuilder("AuditTrail\n"); + when(authzTransMock.auditTrail(anyInt(),(StringBuilder)any(),anyInt(),anyInt())).thenReturn(met); + when(authzTransMock.info()).thenReturn(log); + doNothing().when(log).log((StringBuilder)any()); + Method tallyHoMethod = c.getDeclaredMethod("tallyHo", cArg); + tallyHoMethod.setAccessible(true); + tallyHoMethod.invoke(aTF,authzTransMock); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_NullTrans.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_NullTrans.java index e82aa163..9428bdc6 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_NullTrans.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_NullTrans.java @@ -50,224 +50,224 @@ import java.util.Date; @RunWith(MockitoJUnitRunner.class) public class JU_NullTrans { - NullTrans nullTrans; - - @Before - public void setUp(){ - nullTrans = new NullTrans(); - } - - @Test - public void testAuditTrail() { - Assert.assertNull(nullTrans.auditTrail(0, null, 0)); - } - - @Test - public void testSingleton() { - AuthzTrans single = nullTrans.singleton(); - Assert.assertTrue(single instanceof AuthzTrans); - } - - @Test - public void testCheckpoints() { - nullTrans.checkpoint("Test"); - nullTrans.checkpoint(null, 0); - } - - @Test - public void testFatal() { - LogTarget log = nullTrans.fatal(); - Assert.assertEquals(LogTarget.NULL, log); - } - - @Test - public void testError() { - LogTarget log = nullTrans.error(); - Assert.assertEquals(LogTarget.NULL, log); - } - - @Test - public void testAudit() { - LogTarget log = nullTrans.audit(); - Assert.assertEquals(LogTarget.NULL, log); - } - - @Test - public void testInit() { - LogTarget log = nullTrans.init(); - Assert.assertEquals(LogTarget.NULL, log); - } - - @Test - public void testWarn() { - LogTarget log = nullTrans.warn(); - Assert.assertEquals(LogTarget.NULL, log); - } - - @Test - public void testInfo() { - LogTarget log = nullTrans.info(); - Assert.assertEquals(LogTarget.NULL, log); - } - - @Test - public void testDebug() { - LogTarget log = nullTrans.debug(); - Assert.assertEquals(LogTarget.NULL, log); - } + NullTrans nullTrans; + + @Before + public void setUp(){ + nullTrans = new NullTrans(); + } + + @Test + public void testAuditTrail() { + Assert.assertNull(nullTrans.auditTrail(0, null, 0)); + } + + @Test + public void testSingleton() { + AuthzTrans single = nullTrans.singleton(); + Assert.assertTrue(single instanceof AuthzTrans); + } + + @Test + public void testCheckpoints() { + nullTrans.checkpoint("Test"); + nullTrans.checkpoint(null, 0); + } + + @Test + public void testFatal() { + LogTarget log = nullTrans.fatal(); + Assert.assertEquals(LogTarget.NULL, log); + } + + @Test + public void testError() { + LogTarget log = nullTrans.error(); + Assert.assertEquals(LogTarget.NULL, log); + } + + @Test + public void testAudit() { + LogTarget log = nullTrans.audit(); + Assert.assertEquals(LogTarget.NULL, log); + } + + @Test + public void testInit() { + LogTarget log = nullTrans.init(); + Assert.assertEquals(LogTarget.NULL, log); + } + + @Test + public void testWarn() { + LogTarget log = nullTrans.warn(); + Assert.assertEquals(LogTarget.NULL, log); + } + + @Test + public void testInfo() { + LogTarget log = nullTrans.info(); + Assert.assertEquals(LogTarget.NULL, log); + } + + @Test + public void testDebug() { + LogTarget log = nullTrans.debug(); + Assert.assertEquals(LogTarget.NULL, log); + } - @Test - public void testTrace() { - LogTarget log = nullTrans.trace(); - Assert.assertEquals(LogTarget.NULL, log); - } - - @Test - public void testStart() { - TimeTaken test = nullTrans.start("test", 1); - StringBuilder sb = new StringBuilder(); - test.output(sb); - StringBuilder sb1 = new StringBuilder(); - sb1.append(test); - String s = sb.toString(); - String s1 = sb1.toString(); - s1 = s1.trim(); - Assert.assertEquals(s,s1); - } - - @Test - public void testSetProperty() { - String tag = "tag"; - String value = "value"; - nullTrans.setProperty(tag, value); - String expected = nullTrans.getProperty(tag, value); - Assert.assertEquals(expected, value); - String expectedTag = nullTrans.getProperty(tag); - Assert.assertEquals(expectedTag, tag); - } - - @Test - public void testDecryptor() { - Decryptor decry = nullTrans.decryptor(); - Assert.assertNull(decry); - } - - @Test - public void testEncryptor() { - Encryptor encry = nullTrans.encryptor(); - Assert.assertNull(encry); - } - - @Test - public void testSet() { - HttpServletRequest req = mock(HttpServletRequest.class); - AuthzTrans set = nullTrans.set(req); - Assert.assertNull(set); - } - - @Test - public void testUser() { - String user = nullTrans.user(); - Assert.assertNull(user); - } - - @Test - public void testGetUserPrincipal() { - Principal principal = nullTrans.getUserPrincipal(); - Assert.assertNull(principal); - } - - @Test - public void testIp() { - String ip = nullTrans.ip(); - Assert.assertNull(ip); - } - - @Test - public void testMeth() { - String meth = nullTrans.meth(); - Assert.assertNull(meth); - } - - @Test - public void testPort() { - int port = nullTrans.port(); - Assert.assertEquals(port,0); - } - - @Test - public void testPath() { - String path = nullTrans.path(); - Assert.assertNull(path); - } - - @Test - public void testPut() { - nullTrans.put(null, nullTrans); - } - - @Test - public void testSetUser() { - Principal principal = mock(Principal.class); - //nullTrans.setUser(principal); - } - - @Test - public void testSlot() { - Slot slot = nullTrans.slot(null); - Assert.assertNull(slot); - } - - @Test - public void testEnv() { - AuthzEnv env = nullTrans.env(); - Assert.assertNull(env); - } - - @Test - public void testAgent() { - String agent = nullTrans.agent(); - Assert.assertNull(agent); - } - - @Test - public void testSetLur() { - nullTrans.setLur(null); - } - - @Test - public void testFish() { - Permission perm = mock(Permission.class); - Boolean fish = nullTrans.fish(perm); - Assert.assertFalse(fish); - } - - @Test - public void testOrg() { - Organization org = nullTrans.org(); - Assert.assertEquals(Organization.NULL, org); - } - - @Test - public void testLogAuditTrail() { - LogTarget lt = mock(LogTarget.class); - nullTrans.logAuditTrail(lt); - } - - @Test - public void testRequested() { - Boolean reqd = nullTrans.requested(null); - Assert.assertFalse(reqd); - nullTrans.requested(null, true); - } - - @Test - public void testNow() { - Date date = new Date(); - Assert.assertEquals(date,nullTrans.now()); - //when(nullTrans.now()).thenReturn(null); - } - - - + @Test + public void testTrace() { + LogTarget log = nullTrans.trace(); + Assert.assertEquals(LogTarget.NULL, log); + } + + @Test + public void testStart() { + TimeTaken test = nullTrans.start("test", 1); + StringBuilder sb = new StringBuilder(); + test.output(sb); + StringBuilder sb1 = new StringBuilder(); + sb1.append(test); + String s = sb.toString(); + String s1 = sb1.toString(); + s1 = s1.trim(); + Assert.assertEquals(s,s1); + } + + @Test + public void testSetProperty() { + String tag = "tag"; + String value = "value"; + nullTrans.setProperty(tag, value); + String expected = nullTrans.getProperty(tag, value); + Assert.assertEquals(expected, value); + String expectedTag = nullTrans.getProperty(tag); + Assert.assertEquals(expectedTag, tag); + } + + @Test + public void testDecryptor() { + Decryptor decry = nullTrans.decryptor(); + Assert.assertNull(decry); + } + + @Test + public void testEncryptor() { + Encryptor encry = nullTrans.encryptor(); + Assert.assertNull(encry); + } + + @Test + public void testSet() { + HttpServletRequest req = mock(HttpServletRequest.class); + AuthzTrans set = nullTrans.set(req); + Assert.assertNull(set); + } + + @Test + public void testUser() { + String user = nullTrans.user(); + Assert.assertNull(user); + } + + @Test + public void testGetUserPrincipal() { + Principal principal = nullTrans.getUserPrincipal(); + Assert.assertNull(principal); + } + + @Test + public void testIp() { + String ip = nullTrans.ip(); + Assert.assertNull(ip); + } + + @Test + public void testMeth() { + String meth = nullTrans.meth(); + Assert.assertNull(meth); + } + + @Test + public void testPort() { + int port = nullTrans.port(); + Assert.assertEquals(port,0); + } + + @Test + public void testPath() { + String path = nullTrans.path(); + Assert.assertNull(path); + } + + @Test + public void testPut() { + nullTrans.put(null, nullTrans); + } + + @Test + public void testSetUser() { + Principal principal = mock(Principal.class); + //nullTrans.setUser(principal); + } + + @Test + public void testSlot() { + Slot slot = nullTrans.slot(null); + Assert.assertNull(slot); + } + + @Test + public void testEnv() { + AuthzEnv env = nullTrans.env(); + Assert.assertNull(env); + } + + @Test + public void testAgent() { + String agent = nullTrans.agent(); + Assert.assertNull(agent); + } + + @Test + public void testSetLur() { + nullTrans.setLur(null); + } + + @Test + public void testFish() { + Permission perm = mock(Permission.class); + Boolean fish = nullTrans.fish(perm); + Assert.assertFalse(fish); + } + + @Test + public void testOrg() { + Organization org = nullTrans.org(); + Assert.assertEquals(Organization.NULL, org); + } + + @Test + public void testLogAuditTrail() { + LogTarget lt = mock(LogTarget.class); + nullTrans.logAuditTrail(lt); + } + + @Test + public void testRequested() { + Boolean reqd = nullTrans.requested(null); + Assert.assertFalse(reqd); + nullTrans.requested(null, true); + } + + @Test + public void testNow() { + Date date = new Date(); + Assert.assertEquals(date,nullTrans.now()); + //when(nullTrans.now()).thenReturn(null); + } + + + } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java index a172ad26..59483f46 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java @@ -42,150 +42,150 @@ import org.onap.aaf.auth.layer.Result; import junit.framework.Assert; public class JU_Result { - Result result; -// @Mock -// RV value; - int status=0; - String details = "details"; - String[] variables; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Before - public void setUp(){ - //result = mock(Result.class); - - } - - @Test - public void testOk() { - Object value = null; - Collection col = new ArrayList(); - List list = mock(List.class); - Set set = mock(Set.class); - Integer[] R = new Integer[1]; - - Assert.assertNotNull(Result.ok()); - Assert.assertNotNull(Result.ok(value)); - Assert.assertNotNull(Result.ok(col)); - Assert.assertNotNull(Result.ok(list)); - Assert.assertNotNull(Result.ok(set)); - Assert.assertNotNull(Result.ok(R)); - - Collection col1 = new ArrayList(); - List list1 = new ArrayList(); - Set set1 = new HashSet<>(); - Integer[] R1 = new Integer[0]; - set1.add("derp"); - list1.add("test"); - col1.add("TEST"); - - Assert.assertNotNull(Result.ok(col1)); - Assert.assertNotNull(Result.ok(list1)); - Assert.assertNotNull(Result.ok(set1)); - Assert.assertNotNull(Result.ok(R1)); - } - - @Test - public void testErr() { - Result result = Result.create(null, 0, null, null); - Result r = result; - Exception e = mock(Exception.class); - - Assert.assertNotNull(result.err(r)); //Result case - Assert.assertNotNull(result.err(e)); //Exception case - Assert.assertNotNull(result.err(0, "test", "test")); //Multiple case - - } - - @Test - public void testCreate() { - Result result = Result.create(null, 0, null, null); - Assert.assertNotNull(Result.create(null, 0, null, null)); - Assert.assertNotNull(Result.create(null, 0, null, "arg")); - Assert.assertNotNull(result.create(0, result)); - } - - @Test - public void testOks() { - Result result = Result.create(null, 0, null, null); - - Assert.assertNotNull(result.isOK()); - Assert.assertNotNull(result.notOK()); - Assert.assertNotNull(result.isOKhasData()); - Assert.assertNotNull(result.notOKorIsEmpty()); - - Result result1 = Result.create(null, 5, "test", "test"); - Assert.assertNotNull(result1.emptyList(true)); - Assert.assertNotNull(result1.isOK()); - Assert.assertNotNull(result1.notOK()); - Assert.assertNotNull(result1.isOKhasData()); - Assert.assertNotNull(result1.notOKorIsEmpty()); - - Result result2 = Result.create(null, 0, "test", "test"); - Assert.assertNotNull(result2.emptyList(false)); - Assert.assertNotNull(result2.isOKhasData()); - Assert.assertNotNull(result2.notOKorIsEmpty()); - } - - @Test - public void testEmptyList() { - Result result = Result.create(null, 0, null, null); - - Assert.assertNotNull(result.emptyList(true)); - Assert.assertNotNull(result.emptyList(false)); - Assert.assertFalse(result.isEmpty()); - } - - @Test - public void testPartialContent() { - Result result = Result.create(null, 0, null, null); - - Assert.assertNotNull(result.partialContent(true)); - Assert.assertNotNull(result.partialContent(false)); - Assert.assertFalse(result.partialContent()); - - Result result1 = Result.create(null, 1, "test", null); - Assert.assertNotNull(result1.partialContent(true)); - Assert.assertNotNull(result1.partialContent()); - } - - @Test - public void testToString() { - Result result = Result.create(null, 0, null, null); - - Assert.assertNull(result.toString() ); - - Result result1 = Result.create(null, 5, "test", "test"); - - Assert.assertNotNull(result1.toString()); - - int value = 1; - Result result2 = Result.create(value , 5, "test", "test"); - - Assert.assertNotNull(result2.toString()); - } - - @Test - public void testErrorString() { - Result result = Result.create(null, 0, "test", "test"); - Assert.assertEquals("Error - test", result.errorString()); - Result result1 = Result.create(null, 1, "test", "test"); - Assert.assertEquals("Security - test",result1.errorString()); - Result result2 = Result.create(null, 2, "test", "test"); - Assert.assertEquals("Denied - test",result2.errorString()); - Result result3 = Result.create(null, 3, "test", "test"); - Assert.assertEquals("Policy - test",result3.errorString()); - Result result4 = Result.create(null, 4, "test", "test"); - Assert.assertEquals("BadData - test",result4.errorString()); - Result result5 = Result.create(null, 5, "test", "test"); - Assert.assertEquals("NotImplemented - test",result5.errorString()); - Result result6 = Result.create(null, 6, "test", "test"); - Assert.assertEquals("NotFound - test",result6.errorString()); - Result result7 = Result.create(null, 7, "test", "test"); - Assert.assertEquals("AlreadyExists - test",result7.errorString()); - Result result8 = Result.create(null, 8, "test", "test"); - Assert.assertEquals("ActionNotComplete - test",result8.errorString()); - } + Result result; +// @Mock +// RV value; + int status=0; + String details = "details"; + String[] variables; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Before + public void setUp(){ + //result = mock(Result.class); + + } + + @Test + public void testOk() { + Object value = null; + Collection col = new ArrayList(); + List list = mock(List.class); + Set set = mock(Set.class); + Integer[] R = new Integer[1]; + + Assert.assertNotNull(Result.ok()); + Assert.assertNotNull(Result.ok(value)); + Assert.assertNotNull(Result.ok(col)); + Assert.assertNotNull(Result.ok(list)); + Assert.assertNotNull(Result.ok(set)); + Assert.assertNotNull(Result.ok(R)); + + Collection col1 = new ArrayList(); + List list1 = new ArrayList(); + Set set1 = new HashSet<>(); + Integer[] R1 = new Integer[0]; + set1.add("derp"); + list1.add("test"); + col1.add("TEST"); + + Assert.assertNotNull(Result.ok(col1)); + Assert.assertNotNull(Result.ok(list1)); + Assert.assertNotNull(Result.ok(set1)); + Assert.assertNotNull(Result.ok(R1)); + } + + @Test + public void testErr() { + Result result = Result.create(null, 0, null, null); + Result r = result; + Exception e = mock(Exception.class); + + Assert.assertNotNull(result.err(r)); //Result case + Assert.assertNotNull(result.err(e)); //Exception case + Assert.assertNotNull(result.err(0, "test", "test")); //Multiple case + + } + + @Test + public void testCreate() { + Result result = Result.create(null, 0, null, null); + Assert.assertNotNull(Result.create(null, 0, null, null)); + Assert.assertNotNull(Result.create(null, 0, null, "arg")); + Assert.assertNotNull(result.create(0, result)); + } + + @Test + public void testOks() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNotNull(result.isOK()); + Assert.assertNotNull(result.notOK()); + Assert.assertNotNull(result.isOKhasData()); + Assert.assertNotNull(result.notOKorIsEmpty()); + + Result result1 = Result.create(null, 5, "test", "test"); + Assert.assertNotNull(result1.emptyList(true)); + Assert.assertNotNull(result1.isOK()); + Assert.assertNotNull(result1.notOK()); + Assert.assertNotNull(result1.isOKhasData()); + Assert.assertNotNull(result1.notOKorIsEmpty()); + + Result result2 = Result.create(null, 0, "test", "test"); + Assert.assertNotNull(result2.emptyList(false)); + Assert.assertNotNull(result2.isOKhasData()); + Assert.assertNotNull(result2.notOKorIsEmpty()); + } + + @Test + public void testEmptyList() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNotNull(result.emptyList(true)); + Assert.assertNotNull(result.emptyList(false)); + Assert.assertFalse(result.isEmpty()); + } + + @Test + public void testPartialContent() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNotNull(result.partialContent(true)); + Assert.assertNotNull(result.partialContent(false)); + Assert.assertFalse(result.partialContent()); + + Result result1 = Result.create(null, 1, "test", null); + Assert.assertNotNull(result1.partialContent(true)); + Assert.assertNotNull(result1.partialContent()); + } + + @Test + public void testToString() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNull(result.toString() ); + + Result result1 = Result.create(null, 5, "test", "test"); + + Assert.assertNotNull(result1.toString()); + + int value = 1; + Result result2 = Result.create(value , 5, "test", "test"); + + Assert.assertNotNull(result2.toString()); + } + + @Test + public void testErrorString() { + Result result = Result.create(null, 0, "test", "test"); + Assert.assertEquals("Error - test", result.errorString()); + Result result1 = Result.create(null, 1, "test", "test"); + Assert.assertEquals("Security - test",result1.errorString()); + Result result2 = Result.create(null, 2, "test", "test"); + Assert.assertEquals("Denied - test",result2.errorString()); + Result result3 = Result.create(null, 3, "test", "test"); + Assert.assertEquals("Policy - test",result3.errorString()); + Result result4 = Result.create(null, 4, "test", "test"); + Assert.assertEquals("BadData - test",result4.errorString()); + Result result5 = Result.create(null, 5, "test", "test"); + Assert.assertEquals("NotImplemented - test",result5.errorString()); + Result result6 = Result.create(null, 6, "test", "test"); + Assert.assertEquals("NotFound - test",result6.errorString()); + Result result7 = Result.create(null, 7, "test", "test"); + Assert.assertEquals("AlreadyExists - test",result7.errorString()); + Result result8 = Result.create(null, 8, "test", "test"); + Assert.assertEquals("ActionNotComplete - test",result8.errorString()); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java index dc768862..3280482c 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java @@ -49,68 +49,68 @@ import java.lang.reflect.Method; import java.security.Principal; public class JU_AbsData { - char character = 'x'; - String filePath = "test/output_.key"; - File keyfile = new File(filePath); - AuthzTrans trans = mock(AuthzTrans.class); - - private class AbsDataStub extends AbsData { + char character = 'x'; + String filePath = "test/output_.key"; + File keyfile = new File(filePath); + AuthzTrans trans = mock(AuthzTrans.class); + + private class AbsDataStub extends AbsData { - - public AbsDataStub(File dataf, char sepChar, int maxLineSize, int fieldOffset) { - super(dataf, sepChar, maxLineSize, fieldOffset); - // TODO Auto-generated constructor stub - - } - - } + + public AbsDataStub(File dataf, char sepChar, int maxLineSize, int fieldOffset) { + super(dataf, sepChar, maxLineSize, fieldOffset); + // TODO Auto-generated constructor stub + + } + + } - @Test - public void testStub() throws IOException { - char character = 'x'; - String filePath = "test/output_.key"; - File keyfile = new File(filePath); - FileOutputStream is = new FileOutputStream(keyfile); + @Test + public void testStub() throws IOException { + char character = 'x'; + String filePath = "test/output_.key"; + File keyfile = new File(filePath); + FileOutputStream is = new FileOutputStream(keyfile); OutputStreamWriter osw = new OutputStreamWriter(is); BufferedWriter w = new BufferedWriter(osw); - for(int i = 0; i< 10; i++) { //Write lines to file - w.write("a\nsdfasdfxasdf" + i + "\n"); + for(int i = 0; i< 10; i++) { //Write lines to file + w.write("a\nsdfasdfxasdf" + i + "\n"); } w.close(); - AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); - ads.skipLines(0); - ads.name(); - - long lng = 1823286886660L; - //ads.open(trans, lng); - keyfile.delete(); - } - - @Test - public void testClose() throws IOException { - AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); - ads.close(trans); - } - - @Test - public void testReuse() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - char character = 'x'; - AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); - Reuse reuse = ads.reuse(); - reuse.reset(); - Assert.assertEquals("", reuse.at(1)); - Assert.assertNull(reuse.next()); - //reuse.atToEnd(0); - //reuse.pos(10); - keyfile.delete(); - } - - @Test - public void testIter() throws IOException { - AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); - TextIndex textIndex = new TextIndex(keyfile); - //Iter iter = ads.iterator(); //Need actual input to run textIndex.create to have a datafile to read + AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); + ads.skipLines(0); + ads.name(); + + long lng = 1823286886660L; + //ads.open(trans, lng); + keyfile.delete(); + } + + @Test + public void testClose() throws IOException { + AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); + ads.close(trans); + } + + @Test + public void testReuse() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + char character = 'x'; + AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); + Reuse reuse = ads.reuse(); + reuse.reset(); + Assert.assertEquals("", reuse.at(1)); + Assert.assertNull(reuse.next()); + //reuse.atToEnd(0); + //reuse.pos(10); + keyfile.delete(); + } + + @Test + public void testIter() throws IOException { + AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); + TextIndex textIndex = new TextIndex(keyfile); + //Iter iter = ads.iterator(); //Need actual input to run textIndex.create to have a datafile to read - } + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java index 559b275f..238d36d3 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java @@ -32,39 +32,39 @@ import org.onap.aaf.auth.local.DataFile.Token.Field; public class JU_DataFile { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } -// @Test -// public void netYetTested() { -// fail("Tests not yet implemented"); -// } - -// @Test -// public void test() throws Exception { -// File file = new File("../authz-batch/data/v1.dat"); -// DataFile df = new DataFile(file,"r"); -// int count = 0; -// List list = new ArrayList<>(); -// try { -// df.open(); -// Token tok = df.new Token(1024000); -// Field fld = tok.new Field('|'); -// -// while(tok.nextLine()) { -// ++count; -// fld.reset(); -// list.add(fld.at(0)); -// } -//// Collections.sort(list); -// for(String s: list) { -// System.out.println(s); +// @Test +// public void netYetTested() { +// fail("Tests not yet implemented"); +// } + +// @Test +// public void test() throws Exception { +// File file = new File("../authz-batch/data/v1.dat"); +// DataFile df = new DataFile(file,"r"); +// int count = 0; +// List list = new ArrayList<>(); +// try { +// df.open(); +// Token tok = df.new Token(1024000); +// Field fld = tok.new Field('|'); +// +// while(tok.nextLine()) { +// ++count; +// fld.reset(); +// list.add(fld.at(0)); +// } +//// Collections.sort(list); +// for(String s: list) { +// System.out.println(s); // -// } -// } finally { -// System.out.printf("%15s:%12d\n","Total",count); -// } -// } +// } +// } finally { +// System.out.printf("%15s:%12d\n","Total",count); +// } +// } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java index 1252a69d..df2d5464 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java @@ -56,88 +56,88 @@ import org.onap.aaf.misc.env.Trans; @RunWith(MockitoJUnitRunner.class) public class JU_TextIndex { - TextIndex textIndex; - Iter iter; - Trans trans; - DataFile datafile; - @Mock - File file; - - private class AbsDataStub extends AbsData { + TextIndex textIndex; + Iter iter; + Trans trans; + DataFile datafile; + @Mock + File file; + + private class AbsDataStub extends AbsData { - - public AbsDataStub(File dataf, char sepChar, int maxLineSize, int fieldOffset) { - super(dataf, sepChar, maxLineSize, fieldOffset); - // TODO Auto-generated constructor stub - - } - - } - - @Before - public void setUp() throws IOException{ - char character = 'x'; - String filePath = "test/output_key"; - File keyfile = new File(filePath); - FileOutputStream is = new FileOutputStream(keyfile); + + public AbsDataStub(File dataf, char sepChar, int maxLineSize, int fieldOffset) { + super(dataf, sepChar, maxLineSize, fieldOffset); + // TODO Auto-generated constructor stub + + } + + } + + @Before + public void setUp() throws IOException{ + char character = 'x'; + String filePath = "test/output_key"; + File keyfile = new File(filePath); + FileOutputStream is = new FileOutputStream(keyfile); OutputStreamWriter osw = new OutputStreamWriter(is); BufferedWriter w = new BufferedWriter(osw); - for(int i = 0; i< 10; i++) { //Write lines to file - w.write("a\nsdfasdfxasdf" + i + "\n"); + for(int i = 0; i< 10; i++) { //Write lines to file + w.write("a\nsdfasdfxasdf" + i + "\n"); } w.close(); - datafile = new DataFile(keyfile, "r"); - datafile.open(); - datafile = new DataFile(keyfile, "rws");// "S" for synchronized - datafile.open(); - - trans = mock(Trans.class); - TimeTaken ttMock = mock(TimeTaken.class); - TimeTaken ttMock1 = mock(TimeTaken.class); - when(trans.start("Open Files", Env.SUB)).thenReturn(ttMock); - when(trans.start("Read", Env.SUB)).thenReturn(ttMock); - textIndex = new TextIndex(keyfile); - textIndex.close(); - textIndex.open(); - //textIndex.create(trans, datafile, 4, character, 2, 0); //TODO: AAF-111 once actual input is aquired - keyfile.delete(); - - iter = textIndex.new Iter(); - } - - @Test - public void testClose() throws IOException { - textIndex.close(); - } - - @Test - public void testFind() throws IOException { - char character = 'x'; - String filePath = "test/output_.key"; - File keyfile = new File(filePath); - AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); - Reuse reuse = ads.reuse(); - textIndex.find("a", reuse , 0); - } - - @Test - public void testIterNext() { - iter.next(); - iter.hasNext(); - } - - @Test - public void testIdx() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - TextIndex outerObject = new TextIndex(file); + datafile = new DataFile(keyfile, "r"); + datafile.open(); + datafile = new DataFile(keyfile, "rws");// "S" for synchronized + datafile.open(); + + trans = mock(Trans.class); + TimeTaken ttMock = mock(TimeTaken.class); + TimeTaken ttMock1 = mock(TimeTaken.class); + when(trans.start("Open Files", Env.SUB)).thenReturn(ttMock); + when(trans.start("Read", Env.SUB)).thenReturn(ttMock); + textIndex = new TextIndex(keyfile); + textIndex.close(); + textIndex.open(); + //textIndex.create(trans, datafile, 4, character, 2, 0); //TODO: AAF-111 once actual input is aquired + keyfile.delete(); + + iter = textIndex.new Iter(); + } + + @Test + public void testClose() throws IOException { + textIndex.close(); + } + + @Test + public void testFind() throws IOException { + char character = 'x'; + String filePath = "test/output_.key"; + File keyfile = new File(filePath); + AbsDataStub ads = new AbsDataStub(keyfile, character, 0, 0); + Reuse reuse = ads.reuse(); + textIndex.find("a", reuse , 0); + } + + @Test + public void testIterNext() { + iter.next(); + iter.hasNext(); + } + + @Test + public void testIdx() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + TextIndex outerObject = new TextIndex(file); Class idxClass = TextIndex.class.getDeclaredClasses()[0]; Constructor idxConstructor = idxClass.getDeclaredConstructors()[0]; Class[] cArg = new Class[2]; - cArg[0] = Object.class; - cArg[1] = Integer.class; + cArg[0] = Object.class; + cArg[1] = Integer.class; idxConstructor.setAccessible(true); //Object innerObject = idxConstructor.newInstance(outerObject,cArg); - //idxConstructor.hashCode(); //TODO: AAF-111 access inner private class - } + //idxConstructor.hashCode(); //TODO: AAF-111 access inner private class + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_Organization.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_Organization.java index b898e885..ee95d7c4 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_Organization.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_Organization.java @@ -43,46 +43,46 @@ import junit.framework.Assert; public class JU_Organization { - AuthzTrans trans; - GregorianCalendar gc; - @Before - public void setUp() { - gc = new GregorianCalendar(1900, 1, 1); - trans = mock(AuthzTrans.class); - } - - @Test - public void test() throws OrganizationException { - //tests for Org null - Assert.assertEquals("n/a",Organization.NULL.getName()); - Assert.assertEquals("n/a",Organization.NULL.getDomain()); - Assert.assertEquals("n/a",Organization.NULL.getRealm()); - Assert.assertTrue(Organization.NULL.getIdentity(trans, "test") instanceof Identity); - Assert.assertEquals("n/a",Organization.NULL.isValidID(trans, null)); - Assert.assertEquals("n/a",Organization.NULL.isValidPassword(trans, null, null, null)); - Assert.assertTrue(Organization.NULL.getIdentityTypes() instanceof HashSet); - Assert.assertTrue(Organization.NULL.notify(trans, Notify.PasswordExpiration, null, null, null, null, null) instanceof Response); - Assert.assertEquals(0,Organization.NULL.sendEmail(trans, null, null, null, null, null)); - Assert.assertEquals(gc.getTime(),Organization.NULL.whenToValidate(null, null)); - Assert.assertEquals(gc,Organization.NULL.expiration(gc, Expiration.Password)); - Assert.assertTrue(Organization.NULL.getApprovers(trans, null) instanceof ArrayList); - Assert.assertEquals("",Organization.NULL.getApproverType()); - Assert.assertEquals(0,Organization.NULL.startOfDay()); - Assert.assertFalse(Organization.NULL.canHaveMultipleCreds(null)); - Assert.assertFalse(Organization.NULL.isValidCred(trans, null)); - Assert.assertEquals("Null Organization rejects all Policies",Organization.NULL.validate(trans, Policy.CHANGE_JOB, null, null)); - Assert.assertFalse(Organization.NULL.isTestEnv()); - Organization.NULL.setTestMode(true); - - //tests for org emailWarnings - Assert.assertTrue(Organization.NULL.emailWarningPolicy() instanceof EmailWarnings); - Assert.assertEquals(604800000L, Organization.NULL.emailWarningPolicy().credEmailInterval()); - Assert.assertEquals(604800000L, Organization.NULL.emailWarningPolicy().roleEmailInterval()); - Assert.assertEquals(259200000L, Organization.NULL.emailWarningPolicy().apprEmailInterval()); - Assert.assertEquals(2592000000L, Organization.NULL.emailWarningPolicy().credExpirationWarning()); - Assert.assertEquals(2592000000L, Organization.NULL.emailWarningPolicy().roleExpirationWarning()); - Assert.assertEquals(1209600000L, Organization.NULL.emailWarningPolicy().emailUrgentWarning()); - Assert.assertTrue(Organization.NULL.getPasswordRules() instanceof String[]); + AuthzTrans trans; + GregorianCalendar gc; + @Before + public void setUp() { + gc = new GregorianCalendar(1900, 1, 1); + trans = mock(AuthzTrans.class); + } + + @Test + public void test() throws OrganizationException { + //tests for Org null + Assert.assertEquals("n/a",Organization.NULL.getName()); + Assert.assertEquals("n/a",Organization.NULL.getDomain()); + Assert.assertEquals("n/a",Organization.NULL.getRealm()); + Assert.assertTrue(Organization.NULL.getIdentity(trans, "test") instanceof Identity); + Assert.assertEquals("n/a",Organization.NULL.isValidID(trans, null)); + Assert.assertEquals("n/a",Organization.NULL.isValidPassword(trans, null, null, null)); + Assert.assertTrue(Organization.NULL.getIdentityTypes() instanceof HashSet); + Assert.assertTrue(Organization.NULL.notify(trans, Notify.PasswordExpiration, null, null, null, null, null) instanceof Response); + Assert.assertEquals(0,Organization.NULL.sendEmail(trans, null, null, null, null, null)); + Assert.assertEquals(gc.getTime(),Organization.NULL.whenToValidate(null, null)); + Assert.assertEquals(gc,Organization.NULL.expiration(gc, Expiration.Password)); + Assert.assertTrue(Organization.NULL.getApprovers(trans, null) instanceof ArrayList); + Assert.assertEquals("",Organization.NULL.getApproverType()); + Assert.assertEquals(0,Organization.NULL.startOfDay()); + Assert.assertFalse(Organization.NULL.canHaveMultipleCreds(null)); + Assert.assertFalse(Organization.NULL.isValidCred(trans, null)); + Assert.assertEquals("Null Organization rejects all Policies",Organization.NULL.validate(trans, Policy.CHANGE_JOB, null, null)); + Assert.assertFalse(Organization.NULL.isTestEnv()); + Organization.NULL.setTestMode(true); + + //tests for org emailWarnings + Assert.assertTrue(Organization.NULL.emailWarningPolicy() instanceof EmailWarnings); + Assert.assertEquals(604800000L, Organization.NULL.emailWarningPolicy().credEmailInterval()); + Assert.assertEquals(604800000L, Organization.NULL.emailWarningPolicy().roleEmailInterval()); + Assert.assertEquals(259200000L, Organization.NULL.emailWarningPolicy().apprEmailInterval()); + Assert.assertEquals(2592000000L, Organization.NULL.emailWarningPolicy().credExpirationWarning()); + Assert.assertEquals(2592000000L, Organization.NULL.emailWarningPolicy().roleExpirationWarning()); + Assert.assertEquals(1209600000L, Organization.NULL.emailWarningPolicy().emailUrgentWarning()); + Assert.assertTrue(Organization.NULL.getPasswordRules() instanceof String[]); - } + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java index 79e8a4a1..eaabfd82 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java @@ -32,20 +32,20 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_OrganizationException { - OrganizationException organizationException; - OrganizationException organizationException1; - OrganizationException organizationException2; - OrganizationException organizationException3; - OrganizationException organizationException4; + OrganizationException organizationException; + OrganizationException organizationException1; + OrganizationException organizationException2; + OrganizationException organizationException3; + OrganizationException organizationException4; - @Test - public void testOrganizationException() { - Throwable thr = new Throwable(); - organizationException = new OrganizationException(); - organizationException1 = new OrganizationException("test"); - organizationException2 = new OrganizationException(thr); - organizationException3 = new OrganizationException("test", thr); - organizationException4 = new OrganizationException("test", thr, true, true); - } + @Test + public void testOrganizationException() { + Throwable thr = new Throwable(); + organizationException = new OrganizationException(); + organizationException1 = new OrganizationException("test"); + organizationException2 = new OrganizationException(thr); + organizationException3 = new OrganizationException("test", thr); + organizationException4 = new OrganizationException("test", thr, true, true); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java index 902e94c0..87f65e92 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java @@ -37,35 +37,35 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_OrganizationFactory { - private static final String ORG_SLOT = null; - OrganizationFactory organizationFactory; - BasicEnv bEnv; - @Mock - AuthzEnv authzEnvMock; - String orgClass="orgclass"; - String orgNS="orgns"; - @Before - public void setUp(){ - organizationFactory = new OrganizationFactory(); - bEnv = new BasicEnv(); - } + private static final String ORG_SLOT = null; + OrganizationFactory organizationFactory; + BasicEnv bEnv; + @Mock + AuthzEnv authzEnvMock; + String orgClass="orgclass"; + String orgNS="orgns"; + @Before + public void setUp(){ + organizationFactory = new OrganizationFactory(); + bEnv = new BasicEnv(); + } - @SuppressWarnings("static-access") - @Test - public void testInit() throws OrganizationException { - organizationFactory.init(bEnv); - } + @SuppressWarnings("static-access") + @Test + public void testInit() throws OrganizationException { + organizationFactory.init(bEnv); + } - @SuppressWarnings("static-access") //TODO:Fix this once real input is available AAF-111 - @Test - public void testObtain() throws OrganizationException{ - PowerMockito.when(authzEnvMock.getProperty("Organization."+orgNS)).thenReturn("notnull"); - //organizationFactory.obtain(authzEnvMock, orgNS); - } + @SuppressWarnings("static-access") //TODO:Fix this once real input is available AAF-111 + @Test + public void testObtain() throws OrganizationException{ + PowerMockito.when(authzEnvMock.getProperty("Organization."+orgNS)).thenReturn("notnull"); + //organizationFactory.obtain(authzEnvMock, orgNS); + } - @Test - public void testGet() throws OrganizationException { //TODO: Fix with when then return on fail - AuthzTrans trans = mock(AuthzTrans.class); - //organizationFactory.get(trans); - } + @Test + public void testGet() throws OrganizationException { //TODO: Fix with when then return on fail + AuthzTrans trans = mock(AuthzTrans.class); + //organizationFactory.get(trans); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/CredCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/CredCompare.java index cac26a88..87a86d7c 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/CredCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/CredCompare.java @@ -30,35 +30,35 @@ import org.onap.aaf.misc.env.util.Chrono; import aaf.v2_0.CredRequest; public class CredCompare extends RosettaCompare { - public CredCompare() { - super(CredRequest.class); - } - - public static CredRequest create() { - CredRequest rr = new CredRequest(); - String in = instance(); - rr.setId("m888"+ in + "@ns.att.com"); - rr.setPassword("Bogus0"+in); - rr.setType(200); - GregorianCalendar gc = new GregorianCalendar(); - rr.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - rr.setEnd(Chrono.timeStamp(gc)); - return rr; - } - - @Override - public void compare(CredRequest t1, CredRequest t2) { - assertEquals(t1.getId(),t2.getId()); - assertEquals(t1.getPassword(),t2.getPassword()); - assertEquals(t1.getType(),t2.getType()); - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } + public CredCompare() { + super(CredRequest.class); + } + + public static CredRequest create() { + CredRequest rr = new CredRequest(); + String in = instance(); + rr.setId("m888"+ in + "@ns.att.com"); + rr.setPassword("Bogus0"+in); + rr.setType(200); + GregorianCalendar gc = new GregorianCalendar(); + rr.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + rr.setEnd(Chrono.timeStamp(gc)); + return rr; + } + + @Override + public void compare(CredRequest t1, CredRequest t2) { + assertEquals(t1.getId(),t2.getId()); + assertEquals(t1.getPassword(),t2.getPassword()); + assertEquals(t1.getType(),t2.getType()); + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } - @Override - public CredRequest newOne() { - return create(); - } + @Override + public CredRequest newOne() { + return create(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/JU_RequestCheck.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/JU_RequestCheck.java index 38bd51fc..832f5188 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/JU_RequestCheck.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/JU_RequestCheck.java @@ -26,17 +26,17 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.rosetta.env.RosettaEnv; public class JU_RequestCheck { - - @Test - public void testNSRequest() throws APIException { - RosettaEnv env = new RosettaEnv(); - new NSCompare().run(env); - new NSAttribCompare().run(env); - new RoleCompare().run(env); - new PermCompare().run(env); - new CredCompare().run(env); - new UserRoleCompare().run(env); - new RolePermCompare().run(env); - new MultiCompare().run(env); - }; + + @Test + public void testNSRequest() throws APIException { + RosettaEnv env = new RosettaEnv(); + new NSCompare().run(env); + new NSAttribCompare().run(env); + new RoleCompare().run(env); + new PermCompare().run(env); + new CredCompare().run(env); + new UserRoleCompare().run(env); + new RolePermCompare().run(env); + new MultiCompare().run(env); + }; } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/MultiCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/MultiCompare.java index 5450bf55..024a5237 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/MultiCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/MultiCompare.java @@ -30,40 +30,40 @@ import org.onap.aaf.misc.env.util.Chrono; import aaf.v2_0.MultiRequest; public class MultiCompare extends RosettaCompare { - public MultiCompare() { - super(MultiRequest.class); - } - - @Override - public MultiRequest newOne() { - MultiRequest multi = new MultiRequest(); - multi.setNsRequest(NSCompare.create()); - multi.getNsAttribRequest().add(NSAttribCompare.create()); - multi.getNsAttribRequest().add(NSAttribCompare.create()); - multi.getRoleRequest().add(RoleCompare.create()); - multi.getRoleRequest().add(RoleCompare.create()); - multi.getPermRequest().add(PermCompare.create()); - multi.getPermRequest().add(PermCompare.create()); - multi.getCredRequest().add(CredCompare.create()); - multi.getCredRequest().add(CredCompare.create()); - multi.getUserRoleRequest().add(UserRoleCompare.create()); - multi.getUserRoleRequest().add(UserRoleCompare.create()); - multi.getRolePermRequest().add(RolePermCompare.create()); - multi.getRolePermRequest().add(RolePermCompare.create()); - - - GregorianCalendar gc = new GregorianCalendar(); - multi.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - multi.setEnd(Chrono.timeStamp(gc)); - return multi; - } - - public void compare(MultiRequest t1, MultiRequest t2) { - new NSCompare().compare(t1.getNsRequest(), t2.getNsRequest()); - // Will have to find by key for others. - - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } + public MultiCompare() { + super(MultiRequest.class); + } + + @Override + public MultiRequest newOne() { + MultiRequest multi = new MultiRequest(); + multi.setNsRequest(NSCompare.create()); + multi.getNsAttribRequest().add(NSAttribCompare.create()); + multi.getNsAttribRequest().add(NSAttribCompare.create()); + multi.getRoleRequest().add(RoleCompare.create()); + multi.getRoleRequest().add(RoleCompare.create()); + multi.getPermRequest().add(PermCompare.create()); + multi.getPermRequest().add(PermCompare.create()); + multi.getCredRequest().add(CredCompare.create()); + multi.getCredRequest().add(CredCompare.create()); + multi.getUserRoleRequest().add(UserRoleCompare.create()); + multi.getUserRoleRequest().add(UserRoleCompare.create()); + multi.getRolePermRequest().add(RolePermCompare.create()); + multi.getRolePermRequest().add(RolePermCompare.create()); + + + GregorianCalendar gc = new GregorianCalendar(); + multi.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + multi.setEnd(Chrono.timeStamp(gc)); + return multi; + } + + public void compare(MultiRequest t1, MultiRequest t2) { + new NSCompare().compare(t1.getNsRequest(), t2.getNsRequest()); + // Will have to find by key for others. + + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java index 9f6ce21e..acbaa9c8 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java @@ -32,62 +32,62 @@ import aaf.v2_0.NsAttribRequest; import aaf.v2_0.NsAttribRequest.Attrib; public class NSAttribCompare extends RosettaCompare { - public NSAttribCompare() { - super(NsAttribRequest.class); - } - - public static NsAttribRequest create() { - NsAttribRequest nar = new NsAttribRequest(); - String in = instance(); - - nar.setNs("org.osaaf.ns"+in); - Attrib attrib = new Attrib(); - attrib.setKey("swm"); - attrib.setValue("v"+instance()); - nar.getAttrib().add(attrib); - attrib = new Attrib(); - attrib.setKey("scamp"); - attrib.setValue("v"+instance()); - nar.getAttrib().add(attrib); - GregorianCalendar gc = new GregorianCalendar(); - nar.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - nar.setEnd(Chrono.timeStamp(gc)); - return nar; - } - - @Override - public void compare(NsAttribRequest t1, NsAttribRequest t2) { - assertEquals(t1.getNs(),t2.getNs()); - for(Attrib a1 : t1.getAttrib()) { - boolean ok = false; - for(Attrib a2 : t2.getAttrib()) { - if(a1.getKey().equals(a2.getKey()) && - a1.getValue().equals(a2.getValue())) { - ok = true; - break; - } - } - assertTrue("a2 Attribs in a1",ok); - } - for(Attrib a2 : t2.getAttrib()) { - boolean ok = false; - for(Attrib a1 : t1.getAttrib()) { - if(a1.getKey().equals(a2.getKey()) && - a1.getValue().equals(a2.getValue())) { - ok = true; - break; - } - } - assertTrue("a2 Attribs in a1",ok); - } - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } + public NSAttribCompare() { + super(NsAttribRequest.class); + } + + public static NsAttribRequest create() { + NsAttribRequest nar = new NsAttribRequest(); + String in = instance(); + + nar.setNs("org.osaaf.ns"+in); + Attrib attrib = new Attrib(); + attrib.setKey("swm"); + attrib.setValue("v"+instance()); + nar.getAttrib().add(attrib); + attrib = new Attrib(); + attrib.setKey("scamp"); + attrib.setValue("v"+instance()); + nar.getAttrib().add(attrib); + GregorianCalendar gc = new GregorianCalendar(); + nar.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + nar.setEnd(Chrono.timeStamp(gc)); + return nar; + } + + @Override + public void compare(NsAttribRequest t1, NsAttribRequest t2) { + assertEquals(t1.getNs(),t2.getNs()); + for(Attrib a1 : t1.getAttrib()) { + boolean ok = false; + for(Attrib a2 : t2.getAttrib()) { + if(a1.getKey().equals(a2.getKey()) && + a1.getValue().equals(a2.getValue())) { + ok = true; + break; + } + } + assertTrue("a2 Attribs in a1",ok); + } + for(Attrib a2 : t2.getAttrib()) { + boolean ok = false; + for(Attrib a1 : t1.getAttrib()) { + if(a1.getKey().equals(a2.getKey()) && + a1.getValue().equals(a2.getValue())) { + ok = true; + break; + } + } + assertTrue("a2 Attribs in a1",ok); + } + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } - @Override - public NsAttribRequest newOne() { - return create(); - } + @Override + public NsAttribRequest newOne() { + return create(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java index b7fc28cc..53f78b7c 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java @@ -31,45 +31,45 @@ import org.onap.aaf.misc.env.util.Chrono; import aaf.v2_0.NsRequest; public class NSCompare extends RosettaCompare { - public NSCompare() { - super(NsRequest.class); - } - - public static NsRequest create() { - NsRequest nsr = new NsRequest(); - String in = instance(); - nsr.setName("org.osaaf.ns"+in); - nsr.setDescription("Hello World"+in); - nsr.getAdmin().add("Fred"+in); - nsr.getAdmin().add("Barney"+in); - nsr.getResponsible().add("Wilma"+in); - nsr.getResponsible().add("Betty"+in); - nsr.setType("Hello"+in); - GregorianCalendar gc = new GregorianCalendar(); - nsr.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - nsr.setEnd(Chrono.timeStamp(gc)); - return nsr; - } - - @Override - public void compare(NsRequest t1, NsRequest t2) { - assertEquals(t1.getName(),t2.getName()); - assertEquals(t1.getDescription(),t2.getDescription()); - for(String s : t1.getAdmin()) { - assertTrue(t2.getAdmin().contains(s)); - } - for(String s : t2.getAdmin()) { - assertTrue(t1.getAdmin().contains(s)); - } - assertEquals(t1.getType(),t2.getType()); - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } + public NSCompare() { + super(NsRequest.class); + } + + public static NsRequest create() { + NsRequest nsr = new NsRequest(); + String in = instance(); + nsr.setName("org.osaaf.ns"+in); + nsr.setDescription("Hello World"+in); + nsr.getAdmin().add("Fred"+in); + nsr.getAdmin().add("Barney"+in); + nsr.getResponsible().add("Wilma"+in); + nsr.getResponsible().add("Betty"+in); + nsr.setType("Hello"+in); + GregorianCalendar gc = new GregorianCalendar(); + nsr.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + nsr.setEnd(Chrono.timeStamp(gc)); + return nsr; + } + + @Override + public void compare(NsRequest t1, NsRequest t2) { + assertEquals(t1.getName(),t2.getName()); + assertEquals(t1.getDescription(),t2.getDescription()); + for(String s : t1.getAdmin()) { + assertTrue(t2.getAdmin().contains(s)); + } + for(String s : t2.getAdmin()) { + assertTrue(t1.getAdmin().contains(s)); + } + assertEquals(t1.getType(),t2.getType()); + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } - @Override - public NsRequest newOne() { - return create(); - } + @Override + public NsRequest newOne() { + return create(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/PermCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/PermCompare.java index 3d9a9fdb..92e07655 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/PermCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/PermCompare.java @@ -30,37 +30,37 @@ import org.onap.aaf.misc.env.util.Chrono; import aaf.v2_0.PermRequest; public class PermCompare extends RosettaCompare { - public PermCompare() { - super(PermRequest.class); - } - - public static PermRequest create() { - PermRequest pr = new PermRequest(); - String in = instance(); - pr.setType("org.osaaf.ns.perm"+in); - pr.setInstance("instance"+in); - pr.setAction("read"); - pr.setDescription("Hello World, Perm"+in); - GregorianCalendar gc = new GregorianCalendar(); - pr.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - pr.setEnd(Chrono.timeStamp(gc)); - return pr; - } - - @Override - public void compare(PermRequest t1, PermRequest t2) { - assertEquals(t1.getType(),t2.getType()); - assertEquals(t1.getInstance(),t2.getInstance()); - assertEquals(t1.getAction(),t2.getAction()); - assertEquals(t1.getDescription(),t2.getDescription()); - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } + public PermCompare() { + super(PermRequest.class); + } + + public static PermRequest create() { + PermRequest pr = new PermRequest(); + String in = instance(); + pr.setType("org.osaaf.ns.perm"+in); + pr.setInstance("instance"+in); + pr.setAction("read"); + pr.setDescription("Hello World, Perm"+in); + GregorianCalendar gc = new GregorianCalendar(); + pr.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + pr.setEnd(Chrono.timeStamp(gc)); + return pr; + } + + @Override + public void compare(PermRequest t1, PermRequest t2) { + assertEquals(t1.getType(),t2.getType()); + assertEquals(t1.getInstance(),t2.getInstance()); + assertEquals(t1.getAction(),t2.getAction()); + assertEquals(t1.getDescription(),t2.getDescription()); + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } - @Override - public PermRequest newOne() { - return create(); - } + @Override + public PermRequest newOne() { + return create(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RoleCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RoleCompare.java index 35bd3370..0a3a164c 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RoleCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RoleCompare.java @@ -30,33 +30,33 @@ import org.onap.aaf.misc.env.util.Chrono; import aaf.v2_0.RoleRequest; public class RoleCompare extends RosettaCompare { - public RoleCompare() { - super(RoleRequest.class); - } - - public static RoleRequest create() { - RoleRequest rr = new RoleRequest(); - String in = instance(); - rr.setName("org.osaaf.ns.role"+in); - rr.setDescription("Hello World, Role"+in); - GregorianCalendar gc = new GregorianCalendar(); - rr.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - rr.setEnd(Chrono.timeStamp(gc)); - return rr; - } - - @Override - public void compare(RoleRequest t1, RoleRequest t2) { - assertEquals(t1.getName(),t2.getName()); - assertEquals(t1.getDescription(),t2.getDescription()); - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } - - - @Override - public RoleRequest newOne() { - return create(); - } + public RoleCompare() { + super(RoleRequest.class); + } + + public static RoleRequest create() { + RoleRequest rr = new RoleRequest(); + String in = instance(); + rr.setName("org.osaaf.ns.role"+in); + rr.setDescription("Hello World, Role"+in); + GregorianCalendar gc = new GregorianCalendar(); + rr.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + rr.setEnd(Chrono.timeStamp(gc)); + return rr; + } + + @Override + public void compare(RoleRequest t1, RoleRequest t2) { + assertEquals(t1.getName(),t2.getName()); + assertEquals(t1.getDescription(),t2.getDescription()); + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } + + + @Override + public RoleRequest newOne() { + return create(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RolePermCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RolePermCompare.java index d6ea98b9..24a84b53 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RolePermCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RolePermCompare.java @@ -31,39 +31,39 @@ import aaf.v2_0.Pkey; import aaf.v2_0.RolePermRequest; public class RolePermCompare extends RosettaCompare { - public RolePermCompare() { - super(RolePermRequest.class); - } - - public static RolePermRequest create() { - RolePermRequest urr = new RolePermRequest(); - String in = instance(); - urr.setRole("org.osaaf.ns.role"+in); - Pkey pkey = new Pkey(); - pkey.setType("org.osaaf.ns.myType"+in); - pkey.setInstance("myInstance"+in); - pkey.setAction("myAction"+in); - urr.setPerm(pkey); - GregorianCalendar gc = new GregorianCalendar(); - urr.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - urr.setEnd(Chrono.timeStamp(gc)); - return urr; - } - - @Override - public void compare(RolePermRequest t1, RolePermRequest t2) { - assertEquals(t1.getRole(),t2.getRole()); - assertEquals(t1.getPerm().getType(),t1.getPerm().getType()); - assertEquals(t1.getPerm().getInstance(),t1.getPerm().getInstance()); - assertEquals(t1.getPerm().getAction(),t1.getPerm().getAction()); - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } + public RolePermCompare() { + super(RolePermRequest.class); + } + + public static RolePermRequest create() { + RolePermRequest urr = new RolePermRequest(); + String in = instance(); + urr.setRole("org.osaaf.ns.role"+in); + Pkey pkey = new Pkey(); + pkey.setType("org.osaaf.ns.myType"+in); + pkey.setInstance("myInstance"+in); + pkey.setAction("myAction"+in); + urr.setPerm(pkey); + GregorianCalendar gc = new GregorianCalendar(); + urr.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + urr.setEnd(Chrono.timeStamp(gc)); + return urr; + } + + @Override + public void compare(RolePermRequest t1, RolePermRequest t2) { + assertEquals(t1.getRole(),t2.getRole()); + assertEquals(t1.getPerm().getType(),t1.getPerm().getType()); + assertEquals(t1.getPerm().getInstance(),t1.getPerm().getInstance()); + assertEquals(t1.getPerm().getAction(),t1.getPerm().getAction()); + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } - @Override - public RolePermRequest newOne() { - return create(); - } + @Override + public RolePermRequest newOne() { + return create(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RosettaCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RosettaCompare.java index 8935cc9d..43703d29 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RosettaCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/RosettaCompare.java @@ -29,38 +29,38 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; import org.onap.aaf.misc.rosetta.env.RosettaEnv; public abstract class RosettaCompare { - protected Class cls; - private static int count = 0; - - public RosettaCompare(Class cls) { - this.cls = cls; - } - - public void run(RosettaEnv env) throws APIException { - RosettaDF nsrDF = env.newDataFactory(cls); - compare(nsrDF.newData().option(Data.PRETTY),newOne(),this); - } - - private void compare(RosettaData rdt, T t, RosettaCompare comp) throws APIException { - //System.out.println("########### Testing " + cls.getName() + " ##############"); - String s = rdt.load(t).out(TYPE.JSON).asString(); - //System.out.println(s); - T t2 = rdt.in(TYPE.JSON).load(s).asObject(); - comp.compare(t, t2); - - //System.out.println(); - - s = rdt.load(t).out(TYPE.XML).asString(); - //System.out.println(s); - t2 = rdt.in(TYPE.XML).load(s).asObject(); - comp.compare(t, t2); - } - - public synchronized static String instance() { - return "_"+ ++count; - } - - public abstract void compare(T t1, T t2); - public abstract T newOne(); - + protected Class cls; + private static int count = 0; + + public RosettaCompare(Class cls) { + this.cls = cls; + } + + public void run(RosettaEnv env) throws APIException { + RosettaDF nsrDF = env.newDataFactory(cls); + compare(nsrDF.newData().option(Data.PRETTY),newOne(),this); + } + + private void compare(RosettaData rdt, T t, RosettaCompare comp) throws APIException { + //System.out.println("########### Testing " + cls.getName() + " ##############"); + String s = rdt.load(t).out(TYPE.JSON).asString(); + //System.out.println(s); + T t2 = rdt.in(TYPE.JSON).load(s).asObject(); + comp.compare(t, t2); + + //System.out.println(); + + s = rdt.load(t).out(TYPE.XML).asString(); + //System.out.println(s); + t2 = rdt.in(TYPE.XML).load(s).asObject(); + comp.compare(t, t2); + } + + public synchronized static String instance() { + return "_"+ ++count; + } + + public abstract void compare(T t1, T t2); + public abstract T newOne(); + } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/UserRoleCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/UserRoleCompare.java index 542ddeb7..af61e639 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/UserRoleCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/UserRoleCompare.java @@ -30,33 +30,33 @@ import org.onap.aaf.misc.env.util.Chrono; import aaf.v2_0.UserRoleRequest; public class UserRoleCompare extends RosettaCompare { - public UserRoleCompare() { - super(UserRoleRequest.class); - } - - public static UserRoleRequest create() { - UserRoleRequest urr = new UserRoleRequest(); - String in = instance(); - urr.setUser("m125"+in + "@ns.att.com"); - urr.setRole("org.osaaf.ns.role"+in); - GregorianCalendar gc = new GregorianCalendar(); - urr.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 1); - urr.setEnd(Chrono.timeStamp(gc)); - return urr; - } - - @Override - public void compare(UserRoleRequest t1, UserRoleRequest t2) { - assertEquals(t1.getUser(),t2.getUser()); - assertEquals(t1.getRole(),t2.getRole()); - assertEquals(t1.getStart(),t2.getStart()); - assertEquals(t1.getEnd(),t2.getEnd()); - } - - - @Override - public UserRoleRequest newOne() { - return create(); - } + public UserRoleCompare() { + super(UserRoleRequest.class); + } + + public static UserRoleRequest create() { + UserRoleRequest urr = new UserRoleRequest(); + String in = instance(); + urr.setUser("m125"+in + "@ns.att.com"); + urr.setRole("org.osaaf.ns.role"+in); + GregorianCalendar gc = new GregorianCalendar(); + urr.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 1); + urr.setEnd(Chrono.timeStamp(gc)); + return urr; + } + + @Override + public void compare(UserRoleRequest t1, UserRoleRequest t2) { + assertEquals(t1.getUser(),t2.getUser()); + assertEquals(t1.getRole(),t2.getRole()); + assertEquals(t1.getStart(),t2.getStart()); + assertEquals(t1.getEnd(),t2.getEnd()); + } + + + @Override + public UserRoleRequest newOne() { + return create(); + } } \ No newline at end of file diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch.java index 7d3f057a..159c05a2 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch.java @@ -38,136 +38,136 @@ import org.onap.aaf.misc.env.impl.EnvFactory; public class JU_BetterMatch { - @Test - public void test() { - Trans trans = EnvFactory.newTrans(); - // Bad Match - Match bm = new Match("/req/1.0.0/:var"); + @Test + public void test() { + Trans trans = EnvFactory.newTrans(); + // Bad Match + Match bm = new Match("/req/1.0.0/:var"); - assertTrue(bm.match("/req/1.0.0/fred")); - assertTrue(bm.match("/req/1.0.0/wilma")); - assertTrue(bm.match("/req/1.0.0/wilma/")); - assertFalse(bm.match("/req/1.0.0/wilma/bambam")); - assertFalse(bm.match("/not/valid/234")); - assertFalse(bm.match("")); - - TimeTaken tt = trans.start("A", Env.SUB); - TimeTaken tt2; - int i = 0; - try { - bm = new Match(null); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match(null)); - tt2.done(); - } finally { - tt.done(); - } - - - tt = trans.start("B", Env.SUB); - i = 0; - try { - bm = new Match("/req/1.0.0/:urn/:ref"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/x")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/xyx")); - } finally { - tt2.done(); - tt.done(); - } - - tt = trans.start("C", Env.SUB); - i = 0; - try { - String url = "/req/1.0.0/"; - bm = new Match(url+":urn*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - String value = "urn:fsdb,1.0,req,newreq/0x12345"; - - assertTrue(bm.match(url+value)); - assertEquals("urn:fsdb,1.0,req,newreq/0x12345",bm.param(url+value, ":urn")); - } finally { - tt2.done(); - tt.done(); - } + assertTrue(bm.match("/req/1.0.0/fred")); + assertTrue(bm.match("/req/1.0.0/wilma")); + assertTrue(bm.match("/req/1.0.0/wilma/")); + assertFalse(bm.match("/req/1.0.0/wilma/bambam")); + assertFalse(bm.match("/not/valid/234")); + assertFalse(bm.match("")); + + TimeTaken tt = trans.start("A", Env.SUB); + TimeTaken tt2; + int i = 0; + try { + bm = new Match(null); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match(null)); + tt2.done(); + } finally { + tt.done(); + } + + + tt = trans.start("B", Env.SUB); + i = 0; + try { + bm = new Match("/req/1.0.0/:urn/:ref"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/x")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/xyx")); + } finally { + tt2.done(); + tt.done(); + } + + tt = trans.start("C", Env.SUB); + i = 0; + try { + String url = "/req/1.0.0/"; + bm = new Match(url+":urn*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + String value = "urn:fsdb,1.0,req,newreq/0x12345"; + + assertTrue(bm.match(url+value)); + assertEquals("urn:fsdb,1.0,req,newreq/0x12345",bm.param(url+value, ":urn")); + } finally { + tt2.done(); + tt.done(); + } - tt = trans.start("D", Env.SUB); - i = 0; - try { - bm = new Match("/req/1.0.0/:urn/:ref*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/")); - } finally { - tt2.done(); - tt.done(); - } + tt = trans.start("D", Env.SUB); + i = 0; + try { + bm = new Match("/req/1.0.0/:urn/:ref*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/")); + } finally { + tt2.done(); + tt.done(); + } - tt = trans.start("E", Env.SUB); - i = 0; - try { - bm = new Match("this*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("this")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("thisandthat")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("this/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); - } finally { - tt2.done(); - tt.done(); - } + tt = trans.start("E", Env.SUB); + i = 0; + try { + bm = new Match("this*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("this")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("thisandthat")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("this/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); + } finally { + tt2.done(); + tt.done(); + } - tt = trans.start("F", Env.SUB); - i = 0; - try { - bm = new Match("*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("/this")); - } finally { - tt2.done(); - tt.done(); - } - - StringBuilder sb = new StringBuilder(); - trans.auditTrail(0, sb); - //System.out.println(sb); - - } - - @Test - public void specialTest() { - Match match = new Match("/sample"); - assertTrue(match.match("/sample")); - - match = new Match("/lpeer//lpeer/:key/:item*"); - assertTrue(match.match("/lpeer//lpeer/x/y")); - assertFalse(match.match("/lpeer/x/lpeer/x/y")); + tt = trans.start("F", Env.SUB); + i = 0; + try { + bm = new Match("*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("/this")); + } finally { + tt2.done(); + tt.done(); + } + + StringBuilder sb = new StringBuilder(); + trans.auditTrail(0, sb); + //System.out.println(sb); + + } + + @Test + public void specialTest() { + Match match = new Match("/sample"); + assertTrue(match.match("/sample")); + + match = new Match("/lpeer//lpeer/:key/:item*"); + assertTrue(match.match("/lpeer//lpeer/x/y")); + assertFalse(match.match("/lpeer/x/lpeer/x/y")); - } + } - @Test - public void testGetParamNames() { - Match bm = new Match("/req/1.0.0/:var"); - Set s = bm.getParamNames(); - Assert.assertNotNull(s); - } + @Test + public void testGetParamNames() { + Match bm = new Match("/req/1.0.0/:var"); + Set s = bm.getParamNames(); + Assert.assertNotNull(s); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch1.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch1.java index 7fa996d3..2287889b 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch1.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterMatch1.java @@ -35,130 +35,130 @@ import org.onap.aaf.misc.env.impl.EnvFactory; public class JU_BetterMatch1 { - @Test - public void test() { - Trans trans = EnvFactory.newTrans(); - // Bad Match - Match bm = new Match("/req/1.0.0/:var"); + @Test + public void test() { + Trans trans = EnvFactory.newTrans(); + // Bad Match + Match bm = new Match("/req/1.0.0/:var"); - assertTrue(bm.match("/req/1.0.0/fred")); - assertTrue(bm.match("/req/1.0.0/wilma")); - assertTrue(bm.match("/req/1.0.0/wilma/")); - assertFalse(bm.match("/req/1.0.0/wilma/bambam")); - assertFalse(bm.match("/not/valid/234")); - assertFalse(bm.match("")); - - TimeTaken tt = trans.start("A", Env.SUB); - TimeTaken tt2; - int i = 0; - try { - bm = new Match(null); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match(null)); - tt2.done(); - } finally { - tt.done(); - } - - - tt = trans.start("B", Env.SUB); - i = 0; - try { - bm = new Match("/req/1.0.0/:urn/:ref"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/x")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/xyx")); - } finally { - tt2.done(); - tt.done(); - } - - tt = trans.start("C", Env.SUB); - i = 0; - try { - String url = "/req/1.0.0/"; - bm = new Match(url+":urn*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - String value = "urn:fsdb,1.0,req,newreq/0x12345"; - - assertTrue(bm.match(url+value)); - assertEquals("urn:fsdb,1.0,req,newreq/0x12345",bm.param(url+value, ":urn")); - } finally { - tt2.done(); - tt.done(); - } + assertTrue(bm.match("/req/1.0.0/fred")); + assertTrue(bm.match("/req/1.0.0/wilma")); + assertTrue(bm.match("/req/1.0.0/wilma/")); + assertFalse(bm.match("/req/1.0.0/wilma/bambam")); + assertFalse(bm.match("/not/valid/234")); + assertFalse(bm.match("")); + + TimeTaken tt = trans.start("A", Env.SUB); + TimeTaken tt2; + int i = 0; + try { + bm = new Match(null); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match(null)); + tt2.done(); + } finally { + tt.done(); + } + + + tt = trans.start("B", Env.SUB); + i = 0; + try { + bm = new Match("/req/1.0.0/:urn/:ref"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/x")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/xyx")); + } finally { + tt2.done(); + tt.done(); + } + + tt = trans.start("C", Env.SUB); + i = 0; + try { + String url = "/req/1.0.0/"; + bm = new Match(url+":urn*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + String value = "urn:fsdb,1.0,req,newreq/0x12345"; + + assertTrue(bm.match(url+value)); + assertEquals("urn:fsdb,1.0,req,newreq/0x12345",bm.param(url+value, ":urn")); + } finally { + tt2.done(); + tt.done(); + } - tt = trans.start("D", Env.SUB); - i = 0; - try { - bm = new Match("/req/1.0.0/:urn/:ref*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/")); - } finally { - tt2.done(); - tt.done(); - } + tt = trans.start("D", Env.SUB); + i = 0; + try { + bm = new Match("/req/1.0.0/:urn/:ref*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/0x12345")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertFalse(bm.match("/req/1.0.0/urn:fsdb,1.0,req,newreq/")); + } finally { + tt2.done(); + tt.done(); + } - tt = trans.start("E", Env.SUB); - i = 0; - try { - bm = new Match("this*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("this")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("thisandthat")); - tt2.done(); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("this/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); - } finally { - tt2.done(); - tt.done(); - } + tt = trans.start("E", Env.SUB); + i = 0; + try { + bm = new Match("this*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("this")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("thisandthat")); + tt2.done(); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("this/1.0.0/urn:fsdb,1.0,req,newreq/0x12345/")); + } finally { + tt2.done(); + tt.done(); + } - tt = trans.start("F", Env.SUB); - i = 0; - try { - bm = new Match("*"); - tt2 = trans.start(Integer.toString(++i), Env.SUB); - assertTrue(bm.match("whatever/this")); - } finally { - tt2.done(); - tt.done(); - } - - StringBuilder sb = new StringBuilder(); - trans.auditTrail(0, sb); - //System.out.println(sb); - - } - - @Test - public void specialTest() { - Match match = new Match("/sample"); - assertTrue(match.match("/sample")); - - match = new Match("/lpeer//lpeer/:key/:item*"); - assertTrue(match.match("/lpeer//lpeer/x/y")); - assertFalse(match.match("/lpeer/x/lpeer/x/y")); + tt = trans.start("F", Env.SUB); + i = 0; + try { + bm = new Match("*"); + tt2 = trans.start(Integer.toString(++i), Env.SUB); + assertTrue(bm.match("whatever/this")); + } finally { + tt2.done(); + tt.done(); + } + + StringBuilder sb = new StringBuilder(); + trans.auditTrail(0, sb); + //System.out.println(sb); + + } + + @Test + public void specialTest() { + Match match = new Match("/sample"); + assertTrue(match.match("/sample")); + + match = new Match("/lpeer//lpeer/:key/:item*"); + assertTrue(match.match("/lpeer//lpeer/x/y")); + assertFalse(match.match("/lpeer/x/lpeer/x/y")); - } + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterRoute.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterRoute.java index d98cf5ce..2fa6b5f8 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterRoute.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_BetterRoute.java @@ -25,9 +25,9 @@ import org.junit.Test; public class JU_BetterRoute { - @Test - public void test() { - - } + @Test + public void test() { + + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java index 3d1f0062..207afc70 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java @@ -58,122 +58,122 @@ import junit.framework.Assert; @RunWith(PowerMockRunner.class) public class JU_CachingFileAccess { - CachingFileAccess cachingFileAccess; - HttpCode httpCode; - EnvJAXB envJ; - Trans trans; - - - @Before - public void setUp() throws IOException{ - trans = mock(Trans.class); - HttpCode hCode = mock(HttpCode.class); - envJ = mock(EnvJAXB.class); - LogTarget log = mock(LogTarget.class); - Long lng = (long) 1234134; - when(envJ.get(envJ.staticSlot("aaf_cfa_cache_check_interval"),600000L)).thenReturn(lng); - when(envJ.get(envJ.staticSlot("aaf_cfa_max_size"), 512000)).thenReturn(512000); - when(envJ.get(envJ.staticSlot("aaf_cfa_web_path"))).thenReturn("TEST"); - when(envJ.getProperty("aaf_cfa_clear_command",null)).thenReturn("null"); - when(envJ.init()).thenReturn(log); - doNothing().when(log).log((String)any()); - cachingFileAccess = new CachingFileAccess(envJ,"test"); - - - - } - - @Test - public void testSetEnv() { - Store store = mock(Store.class); - Store store1 = mock(Store.class); - Store store2 = mock(Store.class); - String test[] = {"aaf_cfa_web_path","aaf_cfa_cache_check_interval","aaf_cfa_max_size"}; - String test1[] = {"aaf_cfa_cache_check_interval"}; - String test2[] = {"aaf_cfa_max_size"}; - cachingFileAccess.setEnv(store, test); - cachingFileAccess.setEnv(store1, test1); //These don't reach all the branches for some reason - cachingFileAccess.setEnv(store2, test2); - } - - @Test - public void testHandle() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - HttpServletRequest req = mock(HttpServletRequest.class); - Trans trans = mock(Trans.class); - HttpServletResponse resp = mock(HttpServletResponse.class); - when(req.getPathInfo()).thenReturn("path/to/file"); - - Field matchField = HttpCode.class.getDeclaredField("match"); - matchField.setAccessible(true); - Match match = mock(Match.class); - when(match.param(anyString(), anyString())).thenReturn("null/"); - matchField.set(cachingFileAccess, match); - cachingFileAccess.handle(trans, req, resp); - when(match.param(anyString(), anyString())).thenReturn("clear"); - cachingFileAccess.handle(trans, req, resp); - } - - @Test - public void testWebPath() { - EnvJAXB envJ = mock(EnvJAXB.class); - String web_path_test = "TEST"; - Assert.assertEquals(web_path_test, cachingFileAccess.webPath()); - } - - @Test - public void testCleanupParams() { - NavigableMap content = new ConcurrentSkipListMap<>(); - cachingFileAccess.cleanupParams(50, 500); //TODO: find right input - } - - @Test - public void testLoad() throws IOException { - cachingFileAccess.load(null, null, "1220227200L/1220227200L", null, 1320227200L ); - String filePath = "test/output_key"; - File keyfile = new File(filePath); - RandomAccessFile randFile = new RandomAccessFile (keyfile,"rw"); - - String dPath = "test/"; - File directoryPath = new File(dPath); - directoryPath.mkdir(); - cachingFileAccess.load(null, dPath, "-", null, -1); - randFile.setLength(1024 * 1024 * 8); - cachingFileAccess.load(null, filePath, "-", null, -1); - keyfile.delete(); - directoryPath.delete(); - String filePath1 = "test/output_key"; - File keyfile1 = new File(filePath1); - keyfile1.createNewFile(); - cachingFileAccess.load(null, filePath1, "-", "test", -1); - keyfile1.delete(); - } - - @Test - public void testLoadOrDefault() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException, InstantiationException { - String filePath = "test/output_key"; - File keyfile = new File(filePath); - cachingFileAccess.loadOrDefault(trans, filePath, "-", null, null); - keyfile.delete(); - - Trans trans = mock(Trans.class); - - String filePath1 = "test/output_key.txt"; - //File keyfile1 = new File(filePath1); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws FileNotFoundException { - throw new FileNotFoundException(); - } - }).when(trans).info(); - //cachingFileAccess.loadOrDefault(trans, "bs", "also bs", "test", null); //TODO: Needs more testing AAF-111 - //keyfile1.delete(); - } - - @Test - public void testInvalidate() { - //NavigableMap content = new ConcurrentSkipListMap<>(); - //Content con = mock(Content.class); - //content.put("hello", con); - cachingFileAccess.invalidate("hello"); - } + CachingFileAccess cachingFileAccess; + HttpCode httpCode; + EnvJAXB envJ; + Trans trans; + + + @Before + public void setUp() throws IOException{ + trans = mock(Trans.class); + HttpCode hCode = mock(HttpCode.class); + envJ = mock(EnvJAXB.class); + LogTarget log = mock(LogTarget.class); + Long lng = (long) 1234134; + when(envJ.get(envJ.staticSlot("aaf_cfa_cache_check_interval"),600000L)).thenReturn(lng); + when(envJ.get(envJ.staticSlot("aaf_cfa_max_size"), 512000)).thenReturn(512000); + when(envJ.get(envJ.staticSlot("aaf_cfa_web_path"))).thenReturn("TEST"); + when(envJ.getProperty("aaf_cfa_clear_command",null)).thenReturn("null"); + when(envJ.init()).thenReturn(log); + doNothing().when(log).log((String)any()); + cachingFileAccess = new CachingFileAccess(envJ,"test"); + + + + } + + @Test + public void testSetEnv() { + Store store = mock(Store.class); + Store store1 = mock(Store.class); + Store store2 = mock(Store.class); + String test[] = {"aaf_cfa_web_path","aaf_cfa_cache_check_interval","aaf_cfa_max_size"}; + String test1[] = {"aaf_cfa_cache_check_interval"}; + String test2[] = {"aaf_cfa_max_size"}; + cachingFileAccess.setEnv(store, test); + cachingFileAccess.setEnv(store1, test1); //These don't reach all the branches for some reason + cachingFileAccess.setEnv(store2, test2); + } + + @Test + public void testHandle() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + HttpServletRequest req = mock(HttpServletRequest.class); + Trans trans = mock(Trans.class); + HttpServletResponse resp = mock(HttpServletResponse.class); + when(req.getPathInfo()).thenReturn("path/to/file"); + + Field matchField = HttpCode.class.getDeclaredField("match"); + matchField.setAccessible(true); + Match match = mock(Match.class); + when(match.param(anyString(), anyString())).thenReturn("null/"); + matchField.set(cachingFileAccess, match); + cachingFileAccess.handle(trans, req, resp); + when(match.param(anyString(), anyString())).thenReturn("clear"); + cachingFileAccess.handle(trans, req, resp); + } + + @Test + public void testWebPath() { + EnvJAXB envJ = mock(EnvJAXB.class); + String web_path_test = "TEST"; + Assert.assertEquals(web_path_test, cachingFileAccess.webPath()); + } + + @Test + public void testCleanupParams() { + NavigableMap content = new ConcurrentSkipListMap<>(); + cachingFileAccess.cleanupParams(50, 500); //TODO: find right input + } + + @Test + public void testLoad() throws IOException { + cachingFileAccess.load(null, null, "1220227200L/1220227200L", null, 1320227200L ); + String filePath = "test/output_key"; + File keyfile = new File(filePath); + RandomAccessFile randFile = new RandomAccessFile (keyfile,"rw"); + + String dPath = "test/"; + File directoryPath = new File(dPath); + directoryPath.mkdir(); + cachingFileAccess.load(null, dPath, "-", null, -1); + randFile.setLength(1024 * 1024 * 8); + cachingFileAccess.load(null, filePath, "-", null, -1); + keyfile.delete(); + directoryPath.delete(); + String filePath1 = "test/output_key"; + File keyfile1 = new File(filePath1); + keyfile1.createNewFile(); + cachingFileAccess.load(null, filePath1, "-", "test", -1); + keyfile1.delete(); + } + + @Test + public void testLoadOrDefault() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException, InstantiationException { + String filePath = "test/output_key"; + File keyfile = new File(filePath); + cachingFileAccess.loadOrDefault(trans, filePath, "-", null, null); + keyfile.delete(); + + Trans trans = mock(Trans.class); + + String filePath1 = "test/output_key.txt"; + //File keyfile1 = new File(filePath1); + doAnswer(new Answer() { + public Void answer(InvocationOnMock invocation) throws FileNotFoundException { + throw new FileNotFoundException(); + } + }).when(trans).info(); + //cachingFileAccess.loadOrDefault(trans, "bs", "also bs", "test", null); //TODO: Needs more testing AAF-111 + //keyfile1.delete(); + } + + @Test + public void testInvalidate() { + //NavigableMap content = new ConcurrentSkipListMap<>(); + //Content con = mock(Content.class); + //content.put("hello", con); + cachingFileAccess.invalidate("hello"); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content.java index 146473c7..65cf9bc9 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content.java @@ -41,621 +41,621 @@ import org.onap.aaf.misc.env.impl.EnvFactory; * Test the functioning of the "Content" class, which holds, and routes to the right code based on Accept values */ public class JU_Content { - + - @Test - public void test() throws Exception { - final String BOOL = "Boolean"; - final String XML = "XML"; - TransJAXB trans = EnvFactory.newTrans(); - try { - HttpCode cBool = new HttpCode(BOOL,"Standard String") { - @Override - public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { - try { - resp.getOutputStream().write(context.getBytes()); - } catch (IOException e) { - } - } - }; + @Test + public void test() throws Exception { + final String BOOL = "Boolean"; + final String XML = "XML"; + TransJAXB trans = EnvFactory.newTrans(); + try { + HttpCode cBool = new HttpCode(BOOL,"Standard String") { + @Override + public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { + try { + resp.getOutputStream().write(context.getBytes()); + } catch (IOException e) { + } + } + }; - HttpCode cXML = new HttpCode(XML, "Standard String") { - @Override - public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { - try { - resp.getOutputStream().write(context.getBytes()); - } catch (IOException e) { - } - } - }; + HttpCode cXML = new HttpCode(XML, "Standard String") { + @Override + public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { + try { + resp.getOutputStream().write(context.getBytes()); + } catch (IOException e) { + } + } + }; - TypedCode ct = new TypedCode() - .add(cBool,"application/" + Boolean.class.getName()+"+xml;charset=utf8;version=1.1") - .add(cXML,"application/xml;q=.9"); - String expected = "application/java.lang.Boolean+xml;charset=utf8;version=1.1,application/xml;q=0.9"; - assertEquals(expected,ct.toString()); + TypedCode ct = new TypedCode() + .add(cBool,"application/" + Boolean.class.getName()+"+xml;charset=utf8;version=1.1") + .add(cXML,"application/xml;q=.9"); + String expected = "application/java.lang.Boolean+xml;charset=utf8;version=1.1,application/xml;q=0.9"; + assertEquals(expected,ct.toString()); - //BogusReq req = new BogusReq(); - //expected = (expected); - //HttpServletResponse resp = new BogusResp(); - - assertNotNull("Same Content String and Accept String",ct.prep(trans,expected)); + //BogusReq req = new BogusReq(); + //expected = (expected); + //HttpServletResponse resp = new BogusResp(); + + assertNotNull("Same Content String and Accept String",ct.prep(trans,expected)); - //expects Null (not run) - // A Boolean xml that must have charset utf8 and match version 1.2 or greater - expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.2"); - assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); + //expects Null (not run) + // A Boolean xml that must have charset utf8 and match version 1.2 or greater + expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.2"); + assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); - // Same with (too many) spaces - expected = (" application/java.lang.Boolean+xml ; charset = utf8 ; version = 1.2 "); - assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); + // Same with (too many) spaces + expected = (" application/java.lang.Boolean+xml ; charset = utf8 ; version = 1.2 "); + assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); - //expects Null (not run) - expected = ("application/java.lang.Boolean+xml;charset=utf8;version=2.1"); - assertNull("Major Versions not the same",ct.prep(trans,expected)); + //expects Null (not run) + expected = ("application/java.lang.Boolean+xml;charset=utf8;version=2.1"); + assertNull("Major Versions not the same",ct.prep(trans,expected)); - expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.0"); - assertNotNull("Content Minor Version is greater than Accept Minor Version",ct.prep(trans,expected)); + expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.0"); + assertNotNull("Content Minor Version is greater than Accept Minor Version",ct.prep(trans,expected)); - expected = "application/java.lang.Squid+xml;charset=utf8;version=1.0,application/xml;q=.9"; - assertNotNull("2nd one will have to do...",ct.prep(trans,expected)); + expected = "application/java.lang.Squid+xml;charset=utf8;version=1.0,application/xml;q=.9"; + assertNotNull("2nd one will have to do...",ct.prep(trans,expected)); - expected = "application/java.lang.Boolean+xml;charset=UTF8;version=1.0"; - assertNotNull("Minor Charset in Caps acceptable",ct.prep(trans,expected)); + expected = "application/java.lang.Boolean+xml;charset=UTF8;version=1.0"; + assertNotNull("Minor Charset in Caps acceptable",ct.prep(trans,expected)); - // expects no run - expected="application/java.lang.Boolean+xml;charset=MyType;version=1.0"; - assertNull("Unknown Minor Charset",ct.prep(trans,expected)); + // expects no run + expected="application/java.lang.Boolean+xml;charset=MyType;version=1.0"; + assertNull("Unknown Minor Charset",ct.prep(trans,expected)); - expected=""; - assertNotNull("Blank Acceptance",ct.prep(trans,expected)); - - expected=null; - assertNotNull("Null Acceptance",ct.prep(trans,expected)); + expected=""; + assertNotNull("Blank Acceptance",ct.prep(trans,expected)); + + expected=null; + assertNotNull("Null Acceptance",ct.prep(trans,expected)); - expected = ("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); - assertNotNull("Matches application/xml, and other content not known",ct.prep(trans,expected)); - - // No SemiColon - expected = ("i/am/bogus,application/xml"); - assertNotNull("Match second entry, with no Semis",ct.prep(trans,expected)); + expected = ("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + assertNotNull("Matches application/xml, and other content not known",ct.prep(trans,expected)); + + // No SemiColon + expected = ("i/am/bogus,application/xml"); + assertNotNull("Match second entry, with no Semis",ct.prep(trans,expected)); - } finally { - StringBuilder sb = new StringBuilder(); - trans.auditTrail(0, sb); - //System.out.println(sb); - } - } -// -// Original API used HTTPServletRequest and HTTPServletResponse. Due to the fact that sometimes we use Accept, and others Content-TYpe -// I changed it to simply accept a string -// -// Jonathan 3/8/2013 -// -// @SuppressWarnings("rawtypes") -// class BogusReq implements HttpServletRequest { -// private String accept; -// -// public void accept(String accept) { -// this.accept = accept; -// } -// -// @Override -// public Object getAttribute(String name) { -// return accept; -// } -// -// -// @Override -// public Enumeration getAttributeNames() { -// return null; -// } -// -// @Override -// public String getCharacterEncoding() { -// return null; -// } -// -// @Override -// public void setCharacterEncoding(String env) -// throws UnsupportedEncodingException { -// -// -// } -// -// @Override -// public int getContentLength() { -// -// return 0; -// } -// -// @Override -// public String getContentType() { -// -// return null; -// } -// -// @Override -// public ServletInputStream getInputStream() throws IOException { -// -// return null; -// } -// -// @Override -// public String getParameter(String name) { -// -// return null; -// } -// -// @Override -// public Enumeration getParameterNames() { -// -// return null; -// } -// -// @Override -// public String[] getParameterValues(String name) { -// -// return null; -// } -// -// @Override -// public Map getParameterMap() { -// -// return null; -// } -// -// @Override -// public String getProtocol() { -// -// return null; -// } -// -// @Override -// public String getScheme() { -// -// return null; -// } -// -// @Override -// public String getServerName() { -// -// return null; -// } -// -// @Override -// public int getServerPort() { -// -// return 0; -// } -// -// @Override -// public BufferedReader getReader() throws IOException { -// -// return null; -// } -// -// @Override -// public String getRemoteAddr() { -// -// return null; -// } -// -// @Override -// public String getRemoteHost() { -// -// return null; -// } -// -// @Override -// public void setAttribute(String name, Object o) { -// -// -// } -// -// @Override -// public void removeAttribute(String name) { -// -// -// } -// -// @Override -// public Locale getLocale() { -// -// return null; -// } -// -// @Override -// public Enumeration getLocales() { -// -// return null; -// } -// -// @Override -// public boolean isSecure() { -// -// return false; -// } -// -// @Override -// public RequestDispatcher getRequestDispatcher(String path) { -// -// return null; -// } -// -// @Override -// public String getRealPath(String path) { -// -// return null; -// } -// -// @Override -// public int getRemotePort() { -// -// return 0; -// } -// -// @Override -// public String getLocalName() { -// -// return null; -// } -// -// @Override -// public String getLocalAddr() { -// -// return null; -// } -// -// @Override -// public int getLocalPort() { -// -// return 0; -// } -// -// @Override -// public String getAuthType() { -// -// return null; -// } -// -// @Override -// public Cookie[] getCookies() { -// -// return null; -// } -// -// @Override -// public long getDateHeader(String name) { -// -// return 0; -// } -// -// @Override -// public String getHeader(String name) { -// return accept; -// } -// -// @Override -// public Enumeration getHeaders(String name) { -// -// return null; -// } -// -// @Override -// public Enumeration getHeaderNames() { -// -// return null; -// } -// -// @Override -// public int getIntHeader(String name) { -// -// return 0; -// } -// -// @Override -// public String getMethod() { -// -// return null; -// } -// -// @Override -// public String getPathInfo() { -// -// return null; -// } -// -// @Override -// public String getPathTranslated() { -// -// return null; -// } -// -// @Override -// public String getContextPath() { -// -// return null; -// } -// -// @Override -// public String getQueryString() { -// -// return null; -// } -// -// @Override -// public String getRemoteUser() { -// -// return null; -// } -// -// @Override -// public boolean isUserInRole(String role) { -// -// return false; -// } -// -// @Override -// public Principal getUserPrincipal() { -// -// return null; -// } -// -// @Override -// public String getRequestedSessionId() { -// -// return null; -// } -// -// @Override -// public String getRequestURI() { -// -// return null; -// } -// -// @Override -// public StringBuffer getRequestURL() { -// -// return null; -// } -// -// @Override -// public String getServletPath() { -// -// return null; -// } -// -// @Override -// public HttpSession getSession(boolean create) { -// -// return null; -// } -// -// @Override -// public HttpSession getSession() { -// -// return null; -// } -// -// @Override -// public boolean isRequestedSessionIdValid() { -// -// return false; -// } -// -// @Override -// public boolean isRequestedSessionIdFromCookie() { -// -// return false; -// } -// -// @Override -// public boolean isRequestedSessionIdFromURL() { -// -// return false; -// } -// -// @Override -// public boolean isRequestedSessionIdFromUrl() { -// -// return false; -// } -// } -// -// public class BogusResp implements HttpServletResponse { -// public String contentType; -// -// @Override -// public String getCharacterEncoding() { -// -// return null; -// } -// -// @Override -// public String getContentType() { -// return contentType; -// } -// -// @Override -// public ServletOutputStream getOutputStream() throws IOException { -// -// return null; -// } -// -// @Override -// public PrintWriter getWriter() throws IOException { -// -// return null; -// } -// -// @Override -// public void setCharacterEncoding(String charset) { -// -// -// } -// -// @Override -// public void setContentLength(int len) { -// -// -// } -// -// @Override -// public void setContentType(String type) { -// contentType = type; -// } -// -// @Override -// public void setBufferSize(int size) { -// -// -// } -// -// @Override -// public int getBufferSize() { -// -// return 0; -// } -// -// @Override -// public void flushBuffer() throws IOException { -// -// -// } -// -// @Override -// public void resetBuffer() { -// -// -// } -// -// @Override -// public boolean isCommitted() { -// -// return false; -// } -// -// @Override -// public void reset() { -// -// -// } -// -// @Override -// public void setLocale(Locale loc) { -// -// -// } -// -// @Override -// public Locale getLocale() { -// -// return null; -// } -// -// @Override -// public void addCookie(Cookie cookie) { -// -// -// } -// -// @Override -// public boolean containsHeader(String name) { -// -// return false; -// } -// -// @Override -// public String encodeURL(String url) { -// -// return null; -// } -// -// @Override -// public String encodeRedirectURL(String url) { -// -// return null; -// } -// -// @Override -// public String encodeUrl(String url) { -// -// return null; -// } -// -// @Override -// public String encodeRedirectUrl(String url) { -// -// return null; -// } -// -// @Override -// public void sendError(int sc, String msg) throws IOException { -// -// -// } -// -// @Override -// public void sendError(int sc) throws IOException { -// -// -// } -// -// @Override -// public void sendRedirect(String location) throws IOException { -// -// -// } -// -// @Override -// public void setDateHeader(String name, long date) { -// -// -// } -// -// @Override -// public void addDateHeader(String name, long date) { -// -// -// } -// -// @Override -// public void setHeader(String name, String value) { -// -// -// } -// -// @Override -// public void addHeader(String name, String value) { -// -// -// } -// -// @Override -// public void setIntHeader(String name, int value) { -// -// -// } -// -// @Override -// public void addIntHeader(String name, int value) { -// -// -// } -// -// @Override -// public void setStatus(int sc) { -// -// -// } -// -// @Override -// public void setStatus(int sc, String sm) { -// -// -// } -// -// } + } finally { + StringBuilder sb = new StringBuilder(); + trans.auditTrail(0, sb); + //System.out.println(sb); + } + } +// +// Original API used HTTPServletRequest and HTTPServletResponse. Due to the fact that sometimes we use Accept, and others Content-TYpe +// I changed it to simply accept a string +// +// Jonathan 3/8/2013 +// +// @SuppressWarnings("rawtypes") +// class BogusReq implements HttpServletRequest { +// private String accept; +// +// public void accept(String accept) { +// this.accept = accept; +// } +// +// @Override +// public Object getAttribute(String name) { +// return accept; +// } +// +// +// @Override +// public Enumeration getAttributeNames() { +// return null; +// } +// +// @Override +// public String getCharacterEncoding() { +// return null; +// } +// +// @Override +// public void setCharacterEncoding(String env) +// throws UnsupportedEncodingException { +// +// +// } +// +// @Override +// public int getContentLength() { +// +// return 0; +// } +// +// @Override +// public String getContentType() { +// +// return null; +// } +// +// @Override +// public ServletInputStream getInputStream() throws IOException { +// +// return null; +// } +// +// @Override +// public String getParameter(String name) { +// +// return null; +// } +// +// @Override +// public Enumeration getParameterNames() { +// +// return null; +// } +// +// @Override +// public String[] getParameterValues(String name) { +// +// return null; +// } +// +// @Override +// public Map getParameterMap() { +// +// return null; +// } +// +// @Override +// public String getProtocol() { +// +// return null; +// } +// +// @Override +// public String getScheme() { +// +// return null; +// } +// +// @Override +// public String getServerName() { +// +// return null; +// } +// +// @Override +// public int getServerPort() { +// +// return 0; +// } +// +// @Override +// public BufferedReader getReader() throws IOException { +// +// return null; +// } +// +// @Override +// public String getRemoteAddr() { +// +// return null; +// } +// +// @Override +// public String getRemoteHost() { +// +// return null; +// } +// +// @Override +// public void setAttribute(String name, Object o) { +// +// +// } +// +// @Override +// public void removeAttribute(String name) { +// +// +// } +// +// @Override +// public Locale getLocale() { +// +// return null; +// } +// +// @Override +// public Enumeration getLocales() { +// +// return null; +// } +// +// @Override +// public boolean isSecure() { +// +// return false; +// } +// +// @Override +// public RequestDispatcher getRequestDispatcher(String path) { +// +// return null; +// } +// +// @Override +// public String getRealPath(String path) { +// +// return null; +// } +// +// @Override +// public int getRemotePort() { +// +// return 0; +// } +// +// @Override +// public String getLocalName() { +// +// return null; +// } +// +// @Override +// public String getLocalAddr() { +// +// return null; +// } +// +// @Override +// public int getLocalPort() { +// +// return 0; +// } +// +// @Override +// public String getAuthType() { +// +// return null; +// } +// +// @Override +// public Cookie[] getCookies() { +// +// return null; +// } +// +// @Override +// public long getDateHeader(String name) { +// +// return 0; +// } +// +// @Override +// public String getHeader(String name) { +// return accept; +// } +// +// @Override +// public Enumeration getHeaders(String name) { +// +// return null; +// } +// +// @Override +// public Enumeration getHeaderNames() { +// +// return null; +// } +// +// @Override +// public int getIntHeader(String name) { +// +// return 0; +// } +// +// @Override +// public String getMethod() { +// +// return null; +// } +// +// @Override +// public String getPathInfo() { +// +// return null; +// } +// +// @Override +// public String getPathTranslated() { +// +// return null; +// } +// +// @Override +// public String getContextPath() { +// +// return null; +// } +// +// @Override +// public String getQueryString() { +// +// return null; +// } +// +// @Override +// public String getRemoteUser() { +// +// return null; +// } +// +// @Override +// public boolean isUserInRole(String role) { +// +// return false; +// } +// +// @Override +// public Principal getUserPrincipal() { +// +// return null; +// } +// +// @Override +// public String getRequestedSessionId() { +// +// return null; +// } +// +// @Override +// public String getRequestURI() { +// +// return null; +// } +// +// @Override +// public StringBuffer getRequestURL() { +// +// return null; +// } +// +// @Override +// public String getServletPath() { +// +// return null; +// } +// +// @Override +// public HttpSession getSession(boolean create) { +// +// return null; +// } +// +// @Override +// public HttpSession getSession() { +// +// return null; +// } +// +// @Override +// public boolean isRequestedSessionIdValid() { +// +// return false; +// } +// +// @Override +// public boolean isRequestedSessionIdFromCookie() { +// +// return false; +// } +// +// @Override +// public boolean isRequestedSessionIdFromURL() { +// +// return false; +// } +// +// @Override +// public boolean isRequestedSessionIdFromUrl() { +// +// return false; +// } +// } +// +// public class BogusResp implements HttpServletResponse { +// public String contentType; +// +// @Override +// public String getCharacterEncoding() { +// +// return null; +// } +// +// @Override +// public String getContentType() { +// return contentType; +// } +// +// @Override +// public ServletOutputStream getOutputStream() throws IOException { +// +// return null; +// } +// +// @Override +// public PrintWriter getWriter() throws IOException { +// +// return null; +// } +// +// @Override +// public void setCharacterEncoding(String charset) { +// +// +// } +// +// @Override +// public void setContentLength(int len) { +// +// +// } +// +// @Override +// public void setContentType(String type) { +// contentType = type; +// } +// +// @Override +// public void setBufferSize(int size) { +// +// +// } +// +// @Override +// public int getBufferSize() { +// +// return 0; +// } +// +// @Override +// public void flushBuffer() throws IOException { +// +// +// } +// +// @Override +// public void resetBuffer() { +// +// +// } +// +// @Override +// public boolean isCommitted() { +// +// return false; +// } +// +// @Override +// public void reset() { +// +// +// } +// +// @Override +// public void setLocale(Locale loc) { +// +// +// } +// +// @Override +// public Locale getLocale() { +// +// return null; +// } +// +// @Override +// public void addCookie(Cookie cookie) { +// +// +// } +// +// @Override +// public boolean containsHeader(String name) { +// +// return false; +// } +// +// @Override +// public String encodeURL(String url) { +// +// return null; +// } +// +// @Override +// public String encodeRedirectURL(String url) { +// +// return null; +// } +// +// @Override +// public String encodeUrl(String url) { +// +// return null; +// } +// +// @Override +// public String encodeRedirectUrl(String url) { +// +// return null; +// } +// +// @Override +// public void sendError(int sc, String msg) throws IOException { +// +// +// } +// +// @Override +// public void sendError(int sc) throws IOException { +// +// +// } +// +// @Override +// public void sendRedirect(String location) throws IOException { +// +// +// } +// +// @Override +// public void setDateHeader(String name, long date) { +// +// +// } +// +// @Override +// public void addDateHeader(String name, long date) { +// +// +// } +// +// @Override +// public void setHeader(String name, String value) { +// +// +// } +// +// @Override +// public void addHeader(String name, String value) { +// +// +// } +// +// @Override +// public void setIntHeader(String name, int value) { +// +// +// } +// +// @Override +// public void addIntHeader(String name, int value) { +// +// +// } +// +// @Override +// public void setStatus(int sc) { +// +// +// } +// +// @Override +// public void setStatus(int sc, String sm) { +// +// +// } +// +// } // } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content1.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content1.java index 18723962..0c35eaf0 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content1.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Content1.java @@ -41,90 +41,90 @@ import org.onap.aaf.misc.env.impl.EnvFactory; * Test the functioning of the "Content" class, which holds, and routes to the right code based on Accept values */ public class JU_Content1 { - - - @Test - public void test() throws Exception { - final String BOOL = "Boolean"; - final String XML = "XML"; - TransJAXB trans = EnvFactory.newTrans(); - try { - HttpCode cBool = new HttpCode(BOOL,"Standard String") { - @Override - public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { - try { - resp.getOutputStream().write(context.getBytes()); - } catch (IOException e) { - } - } - }; - - HttpCode cXML = new HttpCode(XML, "Standard String") { - @Override - public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { - try { - resp.getOutputStream().write(context.getBytes()); - } catch (IOException e) { - } - } - }; - - TypedCode ct = new TypedCode() - .add(cBool,"application/" + Boolean.class.getName()+"+xml;charset=utf8;version=1.1") - .add(cXML,"application/xml;q=.9"); - String expected = "application/java.lang.Boolean+xml;charset=utf8;version=1.1,application/xml;q=0.9"; - assertEquals(expected,ct.toString()); - - //BogusReq req = new BogusReq(); - //expected = (expected); - //HttpServletResponse resp = new BogusResp(); - - assertNotNull("Same Content String and Accept String",ct.prep(trans,expected)); - - //expects Null (not run) - // A Boolean xml that must have charset utf8 and match version 1.2 or greater - expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.2"); - assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); - - // Same with (too many) spaces - expected = (" application/java.lang.Boolean+xml ; charset = utf8 ; version = 1.2 "); - assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); - - //expects Null (not run) - expected = ("application/java.lang.Boolean+xml;charset=utf8;version=2.1"); - assertNull("Major Versions not the same",ct.prep(trans,expected)); - - expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.0"); - assertNotNull("Content Minor Version is greater than Accept Minor Version",ct.prep(trans,expected)); - - expected = "application/java.lang.Squid+xml;charset=utf8;version=1.0,application/xml;q=.9"; - assertNotNull("2nd one will have to do...",ct.prep(trans,expected)); - - expected = "application/java.lang.Boolean+xml;charset=UTF8;version=1.0"; - assertNotNull("Minor Charset in Caps acceptable",ct.prep(trans,expected)); - - // expects no run - expected="application/java.lang.Boolean+xml;charset=MyType;version=1.0"; - assertNull("Unknown Minor Charset",ct.prep(trans,expected)); - - expected=""; - assertNotNull("Blank Acceptance",ct.prep(trans,expected)); - - expected=null; - assertNotNull("Null Acceptance",ct.prep(trans,expected)); - - expected = ("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); - assertNotNull("Matches application/xml, and other content not known",ct.prep(trans,expected)); - - // No SemiColon - expected = ("i/am/bogus,application/xml"); - assertNotNull("Match second entry, with no Semis",ct.prep(trans,expected)); - - } finally { - StringBuilder sb = new StringBuilder(); - trans.auditTrail(0, sb); - //System.out.println(sb); - } - } + + + @Test + public void test() throws Exception { + final String BOOL = "Boolean"; + final String XML = "XML"; + TransJAXB trans = EnvFactory.newTrans(); + try { + HttpCode cBool = new HttpCode(BOOL,"Standard String") { + @Override + public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { + try { + resp.getOutputStream().write(context.getBytes()); + } catch (IOException e) { + } + } + }; + + HttpCode cXML = new HttpCode(XML, "Standard String") { + @Override + public void handle(TransJAXB trans, HttpServletRequest req, HttpServletResponse resp) { + try { + resp.getOutputStream().write(context.getBytes()); + } catch (IOException e) { + } + } + }; + + TypedCode ct = new TypedCode() + .add(cBool,"application/" + Boolean.class.getName()+"+xml;charset=utf8;version=1.1") + .add(cXML,"application/xml;q=.9"); + String expected = "application/java.lang.Boolean+xml;charset=utf8;version=1.1,application/xml;q=0.9"; + assertEquals(expected,ct.toString()); + + //BogusReq req = new BogusReq(); + //expected = (expected); + //HttpServletResponse resp = new BogusResp(); + + assertNotNull("Same Content String and Accept String",ct.prep(trans,expected)); + + //expects Null (not run) + // A Boolean xml that must have charset utf8 and match version 1.2 or greater + expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.2"); + assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); + + // Same with (too many) spaces + expected = (" application/java.lang.Boolean+xml ; charset = utf8 ; version = 1.2 "); + assertNull("Accept Minor Version greater than Content Minor Version",ct.prep(trans,expected)); + + //expects Null (not run) + expected = ("application/java.lang.Boolean+xml;charset=utf8;version=2.1"); + assertNull("Major Versions not the same",ct.prep(trans,expected)); + + expected = ("application/java.lang.Boolean+xml;charset=utf8;version=1.0"); + assertNotNull("Content Minor Version is greater than Accept Minor Version",ct.prep(trans,expected)); + + expected = "application/java.lang.Squid+xml;charset=utf8;version=1.0,application/xml;q=.9"; + assertNotNull("2nd one will have to do...",ct.prep(trans,expected)); + + expected = "application/java.lang.Boolean+xml;charset=UTF8;version=1.0"; + assertNotNull("Minor Charset in Caps acceptable",ct.prep(trans,expected)); + + // expects no run + expected="application/java.lang.Boolean+xml;charset=MyType;version=1.0"; + assertNull("Unknown Minor Charset",ct.prep(trans,expected)); + + expected=""; + assertNotNull("Blank Acceptance",ct.prep(trans,expected)); + + expected=null; + assertNotNull("Null Acceptance",ct.prep(trans,expected)); + + expected = ("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + assertNotNull("Matches application/xml, and other content not known",ct.prep(trans,expected)); + + // No SemiColon + expected = ("i/am/bogus,application/xml"); + assertNotNull("Match second entry, with no Semis",ct.prep(trans,expected)); + + } finally { + StringBuilder sb = new StringBuilder(); + trans.auditTrail(0, sb); + //System.out.println(sb); + } + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Pair.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Pair.java index 557c7ec5..7b44fd78 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Pair.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Pair.java @@ -30,18 +30,18 @@ import org.onap.aaf.auth.rserv.Pair; import junit.framework.Assert; public class JU_Pair { - Pair pair; - Integer x; - Integer y; - - @Before - public void setUp(){ - pair = new Pair(1, 2); - } + Pair pair; + Integer x; + Integer y; + + @Before + public void setUp(){ + pair = new Pair(1, 2); + } - @Test - public void testToString() { - String result = pair.toString(); - Assert.assertEquals("X: " + pair.x.toString() + "-->" + pair.y.toString(), result); - } + @Test + public void testToString() { + String result = pair.toString(); + Assert.assertEquals("X: " + pair.x.toString() + "-->" + pair.y.toString(), result); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Route.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Route.java index 4448a0bb..c83bf254 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Route.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Route.java @@ -32,28 +32,28 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.auth.rserv.*; public class JU_Route { - Route route; - HttpCode httpCode; - HttpMethods httpMethod; - Trans trans; - - @Before - public void setUp() { //TODO: AAF-111 complete when actual input is provided - //httpMethod = Matchers.any(HttpMethods.class); - //when(httpMethod.name()).thenReturn("test"); - // route = new Route(null,"path/to/place"); - } - - - @Test - public void testAdd() { - // route.add(httpCode, "path/to/place"); - } - - @Test - public void testStart() { - // trans = mock(Trans.class); - // route.start(trans, "test", httpCode, "test"); - } + Route route; + HttpCode httpCode; + HttpMethods httpMethod; + Trans trans; + + @Before + public void setUp() { //TODO: AAF-111 complete when actual input is provided + //httpMethod = Matchers.any(HttpMethods.class); + //when(httpMethod.name()).thenReturn("test"); + // route = new Route(null,"path/to/place"); + } + + + @Test + public void testAdd() { + // route.add(httpCode, "path/to/place"); + } + + @Test + public void testStart() { + // trans = mock(Trans.class); + // route.start(trans, "test", httpCode, "test"); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_RouteReport.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_RouteReport.java index a9fdff60..5c7ca8dd 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_RouteReport.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_RouteReport.java @@ -30,11 +30,11 @@ import org.junit.Test; public class JU_RouteReport { - @Test - public void test() { - RouteReport report; - report = new RouteReport(); - Assert.assertNotNull(report); - } + @Test + public void test() { + RouteReport report; + report = new RouteReport(); + Assert.assertNotNull(report); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Routes.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Routes.java index 2ed08841..c98922b4 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Routes.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Routes.java @@ -42,31 +42,31 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_Routes { - Routes routes; - @Mock - HttpServletRequest reqMock; - //TODO: Gabe [JUnit] Not visible to junit - //CodeSetter codeSetterMock; - Route routeObj; - - @Before - public void setUp(){ - routes = new Routes(); - } - - @Test - public void testRouteReport(){ - List listVal = routes.routeReport(); - assertNotNull(listVal); - } - - @Test - public void testDerive() throws IOException, ServletException{ - routeObj = routes.derive(reqMock, null); - - } - - - + Routes routes; + @Mock + HttpServletRequest reqMock; + //TODO: Gabe [JUnit] Not visible to junit + //CodeSetter codeSetterMock; + Route routeObj; + + @Before + public void setUp(){ + routes = new Routes(); + } + + @Test + public void testRouteReport(){ + List listVal = routes.routeReport(); + assertNotNull(listVal); + } + + @Test + public void testDerive() throws IOException, ServletException{ + routeObj = routes.derive(reqMock, null); + + } + + + } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_TypedCode.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_TypedCode.java index d5b57de0..0c117deb 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_TypedCode.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_TypedCode.java @@ -46,61 +46,61 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_TypedCode { - TypedCode typedCode; - @Mock - RouteReport routeReportMock; - - @Before - public void setUp(){ - typedCode = new TypedCode(); - } - - @Test - public void testFirst(){ - String returnVal = typedCode.first(); - assertNull(returnVal); - } - - @Test - public void testAdd() { - HttpCode code = mock(HttpCode.class); - typedCode.add(code , "test", "test1", "test2"); - } - - @Test - public void testPrep() throws IOException, ServletException, ClassNotFoundException { - Trans trans = mock(Trans.class); - TimeTaken time = new TimeTaken("yell", 2) { - @Override - public void output(StringBuilder sb) { - // TODO Auto-generated method stub - } - }; - when(trans.start(";na=me;,prop", 8)).thenReturn(time); - HttpCode code = mock(HttpCode.class); - code.pathParam(null, null); - code.isAuthorized(null); //Testing httpcode, currently not working - code.no_cache(); - code.toString(); - - typedCode.add(code , ""); - typedCode.prep(null , "q"); - - typedCode.add(code , "t"); - typedCode.prep(trans , null); - - typedCode.add(code , "t"); - typedCode.prep(trans , ""); - - typedCode.add(code, "POST /authn/validate application/CredRequest+json;charset=utf-8;version=2.0,application/json;version=2.0,*/*"); - //typedCode.prep(trans , "POST /authn/validate application/CredRequest+json;charset=utf-8;version=2.0,application/json;version=2.0,*/*"); - } - - @Test - public void testRelatedTo() { - HttpCode code = mock(HttpCode.class); - StringBuilder sb = new StringBuilder(); - typedCode.relatedTo(code, sb); - } + TypedCode typedCode; + @Mock + RouteReport routeReportMock; + + @Before + public void setUp(){ + typedCode = new TypedCode(); + } + + @Test + public void testFirst(){ + String returnVal = typedCode.first(); + assertNull(returnVal); + } + + @Test + public void testAdd() { + HttpCode code = mock(HttpCode.class); + typedCode.add(code , "test", "test1", "test2"); + } + + @Test + public void testPrep() throws IOException, ServletException, ClassNotFoundException { + Trans trans = mock(Trans.class); + TimeTaken time = new TimeTaken("yell", 2) { + @Override + public void output(StringBuilder sb) { + // TODO Auto-generated method stub + } + }; + when(trans.start(";na=me;,prop", 8)).thenReturn(time); + HttpCode code = mock(HttpCode.class); + code.pathParam(null, null); + code.isAuthorized(null); //Testing httpcode, currently not working + code.no_cache(); + code.toString(); + + typedCode.add(code , ""); + typedCode.prep(null , "q"); + + typedCode.add(code , "t"); + typedCode.prep(trans , null); + + typedCode.add(code , "t"); + typedCode.prep(trans , ""); + + typedCode.add(code, "POST /authn/validate application/CredRequest+json;charset=utf-8;version=2.0,application/json;version=2.0,*/*"); + //typedCode.prep(trans , "POST /authn/validate application/CredRequest+json;charset=utf-8;version=2.0,application/json;version=2.0,*/*"); + } + + @Test + public void testRelatedTo() { + HttpCode code = mock(HttpCode.class); + StringBuilder sb = new StringBuilder(); + typedCode.relatedTo(code, sb); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Version.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Version.java index 617fa259..7698e220 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Version.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_Version.java @@ -34,37 +34,37 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_Version { - Version version; - Version versionTest; + Version version; + Version versionTest; - - @Before - public void setUp(){ - version = new Version("first\\.123"); - versionTest = new Version("first\\.124"); - } + + @Before + public void setUp(){ + version = new Version("first\\.123"); + versionTest = new Version("first\\.124"); + } - @Test - public void testEquals(){ - version.equals(versionTest); - versionTest.equals(version); - versionTest = new Version("fail\\.124"); - version.equals(versionTest); - version.equals("This is not an object of version"); - versionTest = new Version("NoVersion\\.number"); - version.equals(versionTest); - - - } - - @Test - public void testToString(){ - String strVal = version.toString(); - assertNotNull(strVal); - } - - @Test - public void testHashCode() { - Assert.assertNotNull(version.hashCode()); - } + @Test + public void testEquals(){ + version.equals(versionTest); + versionTest.equals(version); + versionTest = new Version("fail\\.124"); + version.equals(versionTest); + version.equals("This is not an object of version"); + versionTest = new Version("NoVersion\\.number"); + version.equals(versionTest); + + + } + + @Test + public void testToString(){ + String strVal = version.toString(); + assertNotNull(strVal); + } + + @Test + public void testHashCode() { + Assert.assertNotNull(version.hashCode()); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsService.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsService.java index cd73e862..3373acab 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsService.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsService.java @@ -62,51 +62,51 @@ import java.security.Principal; import javax.servlet.Filter; public class JU_AbsService { - - ByteArrayOutputStream outStream; - - private class AbsServiceStub extends AbsService { + + ByteArrayOutputStream outStream; + + private class AbsServiceStub extends AbsService { - public AbsServiceStub(Access access, BasicEnv env) throws CadiException { - super(access, env); - // TODO Auto-generated constructor stub - } + public AbsServiceStub(Access access, BasicEnv env) throws CadiException { + super(access, env); + // TODO Auto-generated constructor stub + } - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - // TODO Auto-generated method stub - return null; - } + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + // TODO Auto-generated method stub + return null; + } - @Override - public Registrant[] registrants(int port) throws CadiException, LocatorException { - // TODO Auto-generated method stub - return null; - } - - } - - @Before - public void setUp() { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - } - - @After - public void tearDown() { - System.setOut(System.out); - } - - @Test - public void testStub() throws CadiException { - BasicEnv bEnv = new BasicEnv(); - PropAccess prop = new PropAccess(); - - prop.setProperty(Config.AAF_COMPONENT, "te.st:te.st"); - prop.setLogLevel(Level.DEBUG); - AbsServiceStub absServiceStub = new AbsServiceStub(prop, bEnv); //Testing other branches requires "fails" due to exception handling, will leave that off for now. - } - + @Override + public Registrant[] registrants(int port) throws CadiException, LocatorException { + // TODO Auto-generated method stub + return null; + } + + } + + @Before + public void setUp() { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void testStub() throws CadiException { + BasicEnv bEnv = new BasicEnv(); + PropAccess prop = new PropAccess(); + + prop.setProperty(Config.AAF_COMPONENT, "te.st:te.st"); + prop.setLogLevel(Level.DEBUG); + AbsServiceStub absServiceStub = new AbsServiceStub(prop, bEnv); //Testing other branches requires "fails" due to exception handling, will leave that off for now. + } + } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsServiceStarter.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsServiceStarter.java index 1a3f4417..7ba49dfa 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsServiceStarter.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_AbsServiceStarter.java @@ -67,82 +67,82 @@ import java.security.Principal; import javax.servlet.Filter; public class JU_AbsServiceStarter { - - ByteArrayOutputStream outStream; - AbsServiceStub absServiceStub; - AbsServiceStarterStub absServiceStarterStub; - - private class AbsServiceStarterStub extends AbsServiceStarter { - - public AbsServiceStarterStub(AbsService service) { - super(service); - // TODO Auto-generated constructor stub - } - - @Override - public void _start(RServlet rserv) throws Exception { - // TODO Auto-generated method stub - - } - - @Override - public void _propertyAdjustment() { - // TODO Auto-generated method stub - - } - } - - private class AbsServiceStub extends AbsService { - - public AbsServiceStub(Access access, BasicEnv env) throws CadiException { - super(access, env); - // TODO Auto-generated constructor stub - } - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - // TODO Auto-generated method stub - return null; - } - - @Override - public Registrant[] registrants(int port) throws CadiException, LocatorException { - // TODO Auto-generated method stub - return null; - } - - } - - @Before - public void setUp() { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - } - - @After - public void tearDown() { - System.setOut(System.out); - } - - - @Test - public void testStub() throws CadiException { - BasicEnv bEnv = new BasicEnv(); - PropAccess prop = new PropAccess(); - - prop.setProperty(Config.AAF_COMPONENT, "te.st:te.st"); - prop.setLogLevel(Level.DEBUG); - absServiceStub = new AbsServiceStub(prop, bEnv); - - absServiceStarterStub = new AbsServiceStarterStub(absServiceStub); - } - -// @Test -// public void testStart() throws Exception { -// absServiceStarterStub.env(); -// absServiceStarterStub.start(); -// } - + + ByteArrayOutputStream outStream; + AbsServiceStub absServiceStub; + AbsServiceStarterStub absServiceStarterStub; + + private class AbsServiceStarterStub extends AbsServiceStarter { + + public AbsServiceStarterStub(AbsService service) { + super(service); + // TODO Auto-generated constructor stub + } + + @Override + public void _start(RServlet rserv) throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public void _propertyAdjustment() { + // TODO Auto-generated method stub + + } + } + + private class AbsServiceStub extends AbsService { + + public AbsServiceStub(Access access, BasicEnv env) throws CadiException { + super(access, env); + // TODO Auto-generated constructor stub + } + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Registrant[] registrants(int port) throws CadiException, LocatorException { + // TODO Auto-generated method stub + return null; + } + + } + + @Before + public void setUp() { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + + @Test + public void testStub() throws CadiException { + BasicEnv bEnv = new BasicEnv(); + PropAccess prop = new PropAccess(); + + prop.setProperty(Config.AAF_COMPONENT, "te.st:te.st"); + prop.setLogLevel(Level.DEBUG); + absServiceStub = new AbsServiceStub(prop, bEnv); + + absServiceStarterStub = new AbsServiceStarterStub(absServiceStub); + } + +// @Test +// public void testStart() throws Exception { +// absServiceStarterStub.env(); +// absServiceStarterStub.start(); +// } + } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_JettyServiceStarter.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_JettyServiceStarter.java index 13bac174..ae7fd9d7 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_JettyServiceStarter.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/server/test/JU_JettyServiceStarter.java @@ -49,47 +49,47 @@ import org.junit.runner.RunWith; import org.mockito.Mock; public class JU_JettyServiceStarter { - private PropAccess propAccess = new PropAccess(); - private JettyServiceStarter jss; - class TestService extends AbsService{ + private PropAccess propAccess = new PropAccess(); + private JettyServiceStarter jss; + class TestService extends AbsService{ - public TestService(Access access, AuthzEnv env) throws CadiException { - super(access, env); - // TODO Auto-generated constructor stub - } + public TestService(Access access, AuthzEnv env) throws CadiException { + super(access, env); + // TODO Auto-generated constructor stub + } - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - // TODO Auto-generated method stub - return null; - } + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + // TODO Auto-generated method stub + return null; + } - @Override - public Registrant[] registrants(int port) throws CadiException, LocatorException { - // TODO Auto-generated method stub - return null; - } + @Override + public Registrant[] registrants(int port) throws CadiException, LocatorException { + // TODO Auto-generated method stub + return null; + } - } - @SuppressWarnings("unchecked") - @Before - public void setUp() throws OrganizationException, CadiException { - Access access = mock(Access.class); - - BasicEnv bEnv = mock(BasicEnv.class); - Trans trans = mock(Trans.class); //TODO: Fix this once Gabe has services running to see correct output without mock - //TestService testService = new TestService(access, bEnv); - //jss = new JettyServiceStarter(testService); - } - -// @Test -// public void netYetTested() { -// fail("Tests not yet implemented"); -// } - - @Test - public void testPropertyAdjustment() { - //jss._propertyAdjustment(); - } + } + @SuppressWarnings("unchecked") + @Before + public void setUp() throws OrganizationException, CadiException { + Access access = mock(Access.class); + + BasicEnv bEnv = mock(BasicEnv.class); + Trans trans = mock(Trans.class); //TODO: Fix this once Gabe has services running to see correct output without mock + //TestService testService = new TestService(access, bEnv); + //jss = new JettyServiceStarter(testService); + } + +// @Test +// public void netYetTested() { +// fail("Tests not yet implemented"); +// } + + @Test + public void testPropertyAdjustment() { + //jss._propertyAdjustment(); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/JU_Mask.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/JU_Mask.java index e276f8db..5bc1b68d 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/JU_Mask.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/JU_Mask.java @@ -34,39 +34,39 @@ import junit.framework.Assert; public class JU_Mask { - @Test - public void test() throws Exception { -// InetAddress ia = InetAddress.getLocalHost(); - InetAddress ia = InetAddress.getByName("192.168.0.0"); - NetMask mask = new NetMask(ia.getAddress()); - assertTrue(mask.isInNet(ia.getAddress())); - - mask = new NetMask("192.168.1/24"); - assertTrue(mask.isInNet("192.168.1.20")); - assertTrue(mask.isInNet("192.168.1.255")); - assertFalse(mask.isInNet("192.168.2.20")); - - mask = new NetMask("192.168.1/31"); - assertFalse(mask.isInNet("192.168.2.20")); - assertFalse(mask.isInNet("192.168.1.20")); - assertTrue(mask.isInNet("192.168.1.1")); - assertFalse(mask.isInNet("192.168.1.2")); + @Test + public void test() throws Exception { +// InetAddress ia = InetAddress.getLocalHost(); + InetAddress ia = InetAddress.getByName("192.168.0.0"); + NetMask mask = new NetMask(ia.getAddress()); + assertTrue(mask.isInNet(ia.getAddress())); + + mask = new NetMask("192.168.1/24"); + assertTrue(mask.isInNet("192.168.1.20")); + assertTrue(mask.isInNet("192.168.1.255")); + assertFalse(mask.isInNet("192.168.2.20")); + + mask = new NetMask("192.168.1/31"); + assertFalse(mask.isInNet("192.168.2.20")); + assertFalse(mask.isInNet("192.168.1.20")); + assertTrue(mask.isInNet("192.168.1.1")); + assertFalse(mask.isInNet("192.168.1.2")); - mask = new NetMask("192/8"); - assertTrue(mask.isInNet("192.168.1.1")); - assertTrue(mask.isInNet("192.1.1.1")); - assertFalse(mask.isInNet("193.168.1.1")); - - mask = new NetMask("/0"); - assertTrue(mask.isInNet("193.168.1.1")); - - String msg = "Should throw " + MaskFormatException.class.getSimpleName(); - try { - mask = new NetMask("256.256.256.256"); - Assert.assertTrue(msg,false); - } catch (MaskFormatException e) { - Assert.assertTrue(msg,true); - } - } + mask = new NetMask("192/8"); + assertTrue(mask.isInNet("192.168.1.1")); + assertTrue(mask.isInNet("192.1.1.1")); + assertFalse(mask.isInNet("193.168.1.1")); + + mask = new NetMask("/0"); + assertTrue(mask.isInNet("193.168.1.1")); + + String msg = "Should throw " + MaskFormatException.class.getSimpleName(); + try { + mask = new NetMask("256.256.256.256"); + Assert.assertTrue(msg,false); + } catch (MaskFormatException e) { + Assert.assertTrue(msg,true); + } + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java index 11aaa424..20e8f72f 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java @@ -44,280 +44,280 @@ import junit.framework.Assert; public class JU_Validator { - Validator validator; - String base = "\\x25\\x28\\x29\\x2C-\\x2E\\x30-\\x39\\x3D\\x40-\\x5A\\x5F\\x61-\\x7A"; - - @Before - public void setUp() { - validator = new Validator(); - } - - @Test - public void testNullOrBlank() { - validator.nullOrBlank(null, "str"); - validator.nullOrBlank("test", ""); - validator.nullOrBlank("test", null); - } - - @Test - public void testIsNull() { - Object o = new Object(); - validator.isNull(null, null); - validator.isNull(null, o); - } - - @Test - public void testDescription() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class c = validator.getClass(); - Class[] cArg = new Class[2]; - cArg[0] = String.class; - cArg[1] = String.class; //Steps to test a protected method - Method descriptionMethod = c.getDeclaredMethod("description", cArg); - descriptionMethod.setAccessible(true); - descriptionMethod.invoke(validator,"test", "test1"); - descriptionMethod.invoke(validator,null, null); - descriptionMethod.invoke(validator,null, "[\\\\x25\\\\x28\\\\x29\\\\x2C-\\\\x2E\\\\x30-\\\\x39\\\\x3D\\\\x40-\\\\x5A\\\\x5F\\\\x61-\\\\x7A\\\\x20]+"); - - - } - - @Test - public void testPermType() { - Assert.assertNotNull(validator.permType("[\\\\w.-]+")); - Assert.assertNotNull(validator.permType(null)); - Assert.assertNotNull(validator.permType("")); - Assert.assertNotNull(validator.permType("aewfew")); - } - - @Test - public void testPermType1() { - Assert.assertNotNull(validator.permType("[\\\\w.-]+",null)); - Assert.assertNotNull(validator.permType(null,null)); - Assert.assertNotNull(validator.permType("","test")); - Assert.assertNotNull(validator.permType("aewfew","test")); - } - - @Test - public void testPermInstance() { - - String middle = "]+[\\\\*]*|\\\\*|(([:/]\\\\*)|([:/][!]{0,1}["; - Assert.assertNotNull(validator.permInstance("[" + base + middle + base + "]+[\\\\*]*[:/]*))+")); - Assert.assertNotNull(validator.permInstance(null)); - Assert.assertNotNull(validator.permInstance("")); - Assert.assertNotNull(validator.permInstance("test")); - } - - @Test - public void testErr() { - Assert.assertFalse(validator.err()); - validator.isNull("test", null); - Assert.assertTrue(validator.err()); - } - - @Test - public void testErrs() { - validator.isNull("test", null); - Assert.assertNotNull(validator.errs()); - } - - @Test - public void testPermAction() { - Assert.assertNotNull(validator.permAction("[" + base + "]+" + "|\\\\*")); - Assert.assertNotNull(validator.permAction("test")); - } - - @Test - public void testRole() { - Assert.assertNotNull(validator.role("[\\\\w.-]+")); - Assert.assertNotNull(validator.role(null)); - Assert.assertNotNull(validator.role("")); - Assert.assertNotNull(validator.role("aewfew")); - } - - @Test - public void testNs() { - Assert.assertNotNull(validator.ns("[\\\\w.-]+")); - Assert.assertNotNull(validator.ns("")); - Assert.assertNotNull(validator.ns(".access")); - } - - @Test - public void testKey() { - Assert.assertNotNull(validator.key("[\\\\w.-]+")); - Assert.assertNotNull(validator.key("")); - Assert.assertNotNull(validator.key(".access")); - } - - @Test - public void testValue() { - Assert.assertNotNull(validator.value(base)); - Assert.assertNotNull(validator.value("")); - Assert.assertNotNull(validator.value(".access")); - } - - @Test - public void testNotOK() { - Result test = mock(Result.class); - validator.isNull("test", null); - when(test.notOK()).thenReturn(true); - Assert.assertNotNull(validator.notOK(null)); - Assert.assertNotNull(validator.notOK(test)); - } - - @Test - public void testIntRange() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class c = validator.getClass(); - Class[] cArg = new Class[4]; - cArg[0] = String.class; - cArg[1] = int.class; - cArg[2] = int.class; - cArg[3] = int.class; //Steps to test a protected method - Method intRangeMethod = c.getDeclaredMethod("intRange", cArg); - intRangeMethod.setAccessible(true); - intRangeMethod.invoke(validator,"Test",5,1,10); - intRangeMethod.invoke(validator,"Test",1,5,10); - intRangeMethod.invoke(validator,"Test",11,5,10); - intRangeMethod.invoke(validator,"Test",5,6,4); - } - - @Test - public void testFloatRange() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class c = validator.getClass(); - Class[] cArg = new Class[4]; - cArg[0] = String.class; - cArg[1] = float.class; - cArg[2] = float.class; - cArg[3] = float.class; //Steps to test a protected method - Method floatRangeMethod = c.getDeclaredMethod("floatRange", cArg); - floatRangeMethod.setAccessible(true); - floatRangeMethod.invoke(validator,"Test",5f,1f,10f); - floatRangeMethod.invoke(validator,"Test",1f,5f,10f); - floatRangeMethod.invoke(validator,"Test",11f,5f,10f); - floatRangeMethod.invoke(validator,"Test",5f,6f,4f); - } - - @Test - public void test() { - assertTrue(Validator.ACTION_CHARS.matcher("HowdyDoody").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("Howd?yDoody").matches()); - assertTrue(Validator.ACTION_CHARS.matcher("_HowdyDoody").matches()); - assertTrue(Validator.INST_CHARS.matcher("HowdyDoody").matches()); - assertFalse(Validator.INST_CHARS.matcher("Howd?yDoody").matches()); - assertTrue(Validator.INST_CHARS.matcher("_HowdyDoody").matches()); - - // - assertTrue(Validator.ACTION_CHARS.matcher("*").matches()); - assertTrue(Validator.INST_CHARS.matcher("*").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(":*").matches()); - assertTrue(Validator.INST_CHARS.matcher(":*").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(":*:*").matches()); - assertTrue(Validator.INST_CHARS.matcher(":*:*").matches()); - - assertFalse(Validator.ACTION_CHARS.matcher(":hello").matches()); - assertTrue(Validator.INST_CHARS.matcher(":hello").matches()); - assertFalse(Validator.INST_CHARS.matcher("hello:").matches()); - assertFalse(Validator.INST_CHARS.matcher("hello:d").matches()); - - assertFalse(Validator.ACTION_CHARS.matcher(":hello:*").matches()); - assertTrue(Validator.INST_CHARS.matcher(":hello:*").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(":hello:d*:*").matches()); - assertFalse(Validator.INST_CHARS.matcher(":hello:d*d:*").matches()); - assertTrue(Validator.INST_CHARS.matcher(":hello:d*:*").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("HowdyDoody*").matches()); - assertFalse(Validator.INST_CHARS.matcher("Howdy*Doody").matches()); - assertTrue(Validator.INST_CHARS.matcher("HowdyDoody*").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("*HowdyDoody").matches()); - assertFalse(Validator.INST_CHARS.matcher("*HowdyDoody").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(":h*").matches()); - assertFalse(Validator.INST_CHARS.matcher(":h*h*").matches()); - assertTrue(Validator.INST_CHARS.matcher(":h*").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(":h:h*:*").matches()); - assertTrue(Validator.INST_CHARS.matcher(":h:h*:*").matches()); - assertFalse(Validator.INST_CHARS.matcher(":h:h*h:*").matches()); - assertFalse(Validator.INST_CHARS.matcher(":h:h*h*:*").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(":h:*:*h").matches()); - assertFalse(Validator.INST_CHARS.matcher(":h:*:*h").matches()); - assertTrue(Validator.INST_CHARS.matcher(":com.test.*:ns:*").matches()); - - - assertFalse(Validator.ACTION_CHARS.matcher("1234+235gd").matches()); - assertTrue(Validator.ACTION_CHARS.matcher("1234-235gd").matches()); - assertTrue(Validator.ACTION_CHARS.matcher("1234-23_5gd").matches()); - assertTrue(Validator.ACTION_CHARS.matcher("1234-235g,d").matches()); - assertTrue(Validator.ACTION_CHARS.matcher("1234-235gd(Version12)").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("123#4-23@5g:d").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("123#4-23@5g:d").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("1234-23 5gd").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("1234-235gd ").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(" 1234-235gd").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(" ").matches()); - - // Allow % and = (Needed for Escaping & Base64 usages) jg - assertTrue(Validator.ACTION_CHARS.matcher("1234%235g=d").matches()); - assertFalse(Validator.ACTION_CHARS.matcher(":1234%235g=d").matches()); - assertTrue(Validator.INST_CHARS.matcher("1234%235g=d").matches()); - assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d").matches()); - assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:%20==").matches()); - assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:==%20:=%23").matches()); - assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:*:=%23").matches()); - assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:==%20:*").matches()); - assertTrue(Validator.INST_CHARS.matcher(":*:==%20:*").matches()); - - // Allow / instead of : (more natural instance expression) jg - assertFalse(Validator.INST_CHARS.matcher("1234/a").matches()); - assertTrue(Validator.INST_CHARS.matcher("/1234/a").matches()); - assertTrue(Validator.INST_CHARS.matcher("/1234/*/a/").matches()); - assertTrue(Validator.INST_CHARS.matcher("/1234//a").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("1234/a").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("/1234/*/a/").matches()); - assertFalse(Validator.ACTION_CHARS.matcher("1234//a").matches()); - - - assertFalse(Validator.INST_CHARS.matcher("1234+235gd").matches()); - assertTrue(Validator.INST_CHARS.matcher("1234-235gd").matches()); - assertTrue(Validator.INST_CHARS.matcher("1234-23_5gd").matches()); - assertTrue(Validator.INST_CHARS.matcher("1234-235g,d").matches()); - assertTrue(Validator.INST_CHARS.matcher("m1234@shb.dd.com").matches()); - assertTrue(Validator.INST_CHARS.matcher("1234-235gd(Version12)").matches()); - assertFalse(Validator.INST_CHARS.matcher("123#4-23@5g:d").matches()); - assertFalse(Validator.INST_CHARS.matcher("123#4-23@5g:d").matches()); - assertFalse(Validator.INST_CHARS.matcher("").matches()); - - - for( char c=0x20;c<0x7F;++c) { - boolean b; - switch(c) { - case '?': - case '|': - case '*': - continue; // test separately - case '~': - case ',': - b = false; - break; - default: - b=true; - } - } - - assertFalse(Validator.ID_CHARS.matcher("abc").matches()); - assertFalse(Validator.ID_CHARS.matcher("").matches()); - assertTrue(Validator.ID_CHARS.matcher("abc@att.com").matches()); - assertTrue(Validator.ID_CHARS.matcher("ab-me@att.com").matches()); - assertTrue(Validator.ID_CHARS.matcher("ab-me_.x@att._-com").matches()); - - assertFalse(Validator.NAME_CHARS.matcher("ab-me_.x@att._-com").matches()); - assertTrue(Validator.NAME_CHARS.matcher("ab-me").matches()); - assertTrue(Validator.NAME_CHARS.matcher("ab-me_.xatt._-com").matches()); - - - // 7/22/2016 - assertTrue(Validator.INST_CHARS.matcher( - "/!com.att.*/role/write").matches()); - assertTrue(Validator.INST_CHARS.matcher( - ":!com.att.*:role:write").matches()); - - } + Validator validator; + String base = "\\x25\\x28\\x29\\x2C-\\x2E\\x30-\\x39\\x3D\\x40-\\x5A\\x5F\\x61-\\x7A"; + + @Before + public void setUp() { + validator = new Validator(); + } + + @Test + public void testNullOrBlank() { + validator.nullOrBlank(null, "str"); + validator.nullOrBlank("test", ""); + validator.nullOrBlank("test", null); + } + + @Test + public void testIsNull() { + Object o = new Object(); + validator.isNull(null, null); + validator.isNull(null, o); + } + + @Test + public void testDescription() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class c = validator.getClass(); + Class[] cArg = new Class[2]; + cArg[0] = String.class; + cArg[1] = String.class; //Steps to test a protected method + Method descriptionMethod = c.getDeclaredMethod("description", cArg); + descriptionMethod.setAccessible(true); + descriptionMethod.invoke(validator,"test", "test1"); + descriptionMethod.invoke(validator,null, null); + descriptionMethod.invoke(validator,null, "[\\\\x25\\\\x28\\\\x29\\\\x2C-\\\\x2E\\\\x30-\\\\x39\\\\x3D\\\\x40-\\\\x5A\\\\x5F\\\\x61-\\\\x7A\\\\x20]+"); + + + } + + @Test + public void testPermType() { + Assert.assertNotNull(validator.permType("[\\\\w.-]+")); + Assert.assertNotNull(validator.permType(null)); + Assert.assertNotNull(validator.permType("")); + Assert.assertNotNull(validator.permType("aewfew")); + } + + @Test + public void testPermType1() { + Assert.assertNotNull(validator.permType("[\\\\w.-]+",null)); + Assert.assertNotNull(validator.permType(null,null)); + Assert.assertNotNull(validator.permType("","test")); + Assert.assertNotNull(validator.permType("aewfew","test")); + } + + @Test + public void testPermInstance() { + + String middle = "]+[\\\\*]*|\\\\*|(([:/]\\\\*)|([:/][!]{0,1}["; + Assert.assertNotNull(validator.permInstance("[" + base + middle + base + "]+[\\\\*]*[:/]*))+")); + Assert.assertNotNull(validator.permInstance(null)); + Assert.assertNotNull(validator.permInstance("")); + Assert.assertNotNull(validator.permInstance("test")); + } + + @Test + public void testErr() { + Assert.assertFalse(validator.err()); + validator.isNull("test", null); + Assert.assertTrue(validator.err()); + } + + @Test + public void testErrs() { + validator.isNull("test", null); + Assert.assertNotNull(validator.errs()); + } + + @Test + public void testPermAction() { + Assert.assertNotNull(validator.permAction("[" + base + "]+" + "|\\\\*")); + Assert.assertNotNull(validator.permAction("test")); + } + + @Test + public void testRole() { + Assert.assertNotNull(validator.role("[\\\\w.-]+")); + Assert.assertNotNull(validator.role(null)); + Assert.assertNotNull(validator.role("")); + Assert.assertNotNull(validator.role("aewfew")); + } + + @Test + public void testNs() { + Assert.assertNotNull(validator.ns("[\\\\w.-]+")); + Assert.assertNotNull(validator.ns("")); + Assert.assertNotNull(validator.ns(".access")); + } + + @Test + public void testKey() { + Assert.assertNotNull(validator.key("[\\\\w.-]+")); + Assert.assertNotNull(validator.key("")); + Assert.assertNotNull(validator.key(".access")); + } + + @Test + public void testValue() { + Assert.assertNotNull(validator.value(base)); + Assert.assertNotNull(validator.value("")); + Assert.assertNotNull(validator.value(".access")); + } + + @Test + public void testNotOK() { + Result test = mock(Result.class); + validator.isNull("test", null); + when(test.notOK()).thenReturn(true); + Assert.assertNotNull(validator.notOK(null)); + Assert.assertNotNull(validator.notOK(test)); + } + + @Test + public void testIntRange() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class c = validator.getClass(); + Class[] cArg = new Class[4]; + cArg[0] = String.class; + cArg[1] = int.class; + cArg[2] = int.class; + cArg[3] = int.class; //Steps to test a protected method + Method intRangeMethod = c.getDeclaredMethod("intRange", cArg); + intRangeMethod.setAccessible(true); + intRangeMethod.invoke(validator,"Test",5,1,10); + intRangeMethod.invoke(validator,"Test",1,5,10); + intRangeMethod.invoke(validator,"Test",11,5,10); + intRangeMethod.invoke(validator,"Test",5,6,4); + } + + @Test + public void testFloatRange() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class c = validator.getClass(); + Class[] cArg = new Class[4]; + cArg[0] = String.class; + cArg[1] = float.class; + cArg[2] = float.class; + cArg[3] = float.class; //Steps to test a protected method + Method floatRangeMethod = c.getDeclaredMethod("floatRange", cArg); + floatRangeMethod.setAccessible(true); + floatRangeMethod.invoke(validator,"Test",5f,1f,10f); + floatRangeMethod.invoke(validator,"Test",1f,5f,10f); + floatRangeMethod.invoke(validator,"Test",11f,5f,10f); + floatRangeMethod.invoke(validator,"Test",5f,6f,4f); + } + + @Test + public void test() { + assertTrue(Validator.ACTION_CHARS.matcher("HowdyDoody").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("Howd?yDoody").matches()); + assertTrue(Validator.ACTION_CHARS.matcher("_HowdyDoody").matches()); + assertTrue(Validator.INST_CHARS.matcher("HowdyDoody").matches()); + assertFalse(Validator.INST_CHARS.matcher("Howd?yDoody").matches()); + assertTrue(Validator.INST_CHARS.matcher("_HowdyDoody").matches()); + + // + assertTrue(Validator.ACTION_CHARS.matcher("*").matches()); + assertTrue(Validator.INST_CHARS.matcher("*").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(":*").matches()); + assertTrue(Validator.INST_CHARS.matcher(":*").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(":*:*").matches()); + assertTrue(Validator.INST_CHARS.matcher(":*:*").matches()); + + assertFalse(Validator.ACTION_CHARS.matcher(":hello").matches()); + assertTrue(Validator.INST_CHARS.matcher(":hello").matches()); + assertFalse(Validator.INST_CHARS.matcher("hello:").matches()); + assertFalse(Validator.INST_CHARS.matcher("hello:d").matches()); + + assertFalse(Validator.ACTION_CHARS.matcher(":hello:*").matches()); + assertTrue(Validator.INST_CHARS.matcher(":hello:*").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(":hello:d*:*").matches()); + assertFalse(Validator.INST_CHARS.matcher(":hello:d*d:*").matches()); + assertTrue(Validator.INST_CHARS.matcher(":hello:d*:*").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("HowdyDoody*").matches()); + assertFalse(Validator.INST_CHARS.matcher("Howdy*Doody").matches()); + assertTrue(Validator.INST_CHARS.matcher("HowdyDoody*").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("*HowdyDoody").matches()); + assertFalse(Validator.INST_CHARS.matcher("*HowdyDoody").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(":h*").matches()); + assertFalse(Validator.INST_CHARS.matcher(":h*h*").matches()); + assertTrue(Validator.INST_CHARS.matcher(":h*").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(":h:h*:*").matches()); + assertTrue(Validator.INST_CHARS.matcher(":h:h*:*").matches()); + assertFalse(Validator.INST_CHARS.matcher(":h:h*h:*").matches()); + assertFalse(Validator.INST_CHARS.matcher(":h:h*h*:*").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(":h:*:*h").matches()); + assertFalse(Validator.INST_CHARS.matcher(":h:*:*h").matches()); + assertTrue(Validator.INST_CHARS.matcher(":com.test.*:ns:*").matches()); + + + assertFalse(Validator.ACTION_CHARS.matcher("1234+235gd").matches()); + assertTrue(Validator.ACTION_CHARS.matcher("1234-235gd").matches()); + assertTrue(Validator.ACTION_CHARS.matcher("1234-23_5gd").matches()); + assertTrue(Validator.ACTION_CHARS.matcher("1234-235g,d").matches()); + assertTrue(Validator.ACTION_CHARS.matcher("1234-235gd(Version12)").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("123#4-23@5g:d").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("123#4-23@5g:d").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("1234-23 5gd").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("1234-235gd ").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(" 1234-235gd").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(" ").matches()); + + // Allow % and = (Needed for Escaping & Base64 usages) jg + assertTrue(Validator.ACTION_CHARS.matcher("1234%235g=d").matches()); + assertFalse(Validator.ACTION_CHARS.matcher(":1234%235g=d").matches()); + assertTrue(Validator.INST_CHARS.matcher("1234%235g=d").matches()); + assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d").matches()); + assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:%20==").matches()); + assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:==%20:=%23").matches()); + assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:*:=%23").matches()); + assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:==%20:*").matches()); + assertTrue(Validator.INST_CHARS.matcher(":*:==%20:*").matches()); + + // Allow / instead of : (more natural instance expression) jg + assertFalse(Validator.INST_CHARS.matcher("1234/a").matches()); + assertTrue(Validator.INST_CHARS.matcher("/1234/a").matches()); + assertTrue(Validator.INST_CHARS.matcher("/1234/*/a/").matches()); + assertTrue(Validator.INST_CHARS.matcher("/1234//a").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("1234/a").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("/1234/*/a/").matches()); + assertFalse(Validator.ACTION_CHARS.matcher("1234//a").matches()); + + + assertFalse(Validator.INST_CHARS.matcher("1234+235gd").matches()); + assertTrue(Validator.INST_CHARS.matcher("1234-235gd").matches()); + assertTrue(Validator.INST_CHARS.matcher("1234-23_5gd").matches()); + assertTrue(Validator.INST_CHARS.matcher("1234-235g,d").matches()); + assertTrue(Validator.INST_CHARS.matcher("m1234@shb.dd.com").matches()); + assertTrue(Validator.INST_CHARS.matcher("1234-235gd(Version12)").matches()); + assertFalse(Validator.INST_CHARS.matcher("123#4-23@5g:d").matches()); + assertFalse(Validator.INST_CHARS.matcher("123#4-23@5g:d").matches()); + assertFalse(Validator.INST_CHARS.matcher("").matches()); + + + for( char c=0x20;c<0x7F;++c) { + boolean b; + switch(c) { + case '?': + case '|': + case '*': + continue; // test separately + case '~': + case ',': + b = false; + break; + default: + b=true; + } + } + + assertFalse(Validator.ID_CHARS.matcher("abc").matches()); + assertFalse(Validator.ID_CHARS.matcher("").matches()); + assertTrue(Validator.ID_CHARS.matcher("abc@att.com").matches()); + assertTrue(Validator.ID_CHARS.matcher("ab-me@att.com").matches()); + assertTrue(Validator.ID_CHARS.matcher("ab-me_.x@att._-com").matches()); + + assertFalse(Validator.NAME_CHARS.matcher("ab-me_.x@att._-com").matches()); + assertTrue(Validator.NAME_CHARS.matcher("ab-me").matches()); + assertTrue(Validator.NAME_CHARS.matcher("ab-me_.xatt._-com").matches()); + + + // 7/22/2016 + assertTrue(Validator.INST_CHARS.matcher( + "/!com.att.*/role/write").matches()); + assertTrue(Validator.INST_CHARS.matcher( + ":!com.att.*:role:write").matches()); + + } } diff --git a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java index 0bfe7e2d..d9336d4e 100644 --- a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java +++ b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java @@ -41,583 +41,583 @@ import org.onap.aaf.cadi.util.FQI; import org.onap.aaf.misc.env.Env; public class DefaultOrg implements Organization { - private static final String AAF_DATA_DIR = "aaf_data_dir"; - private static final String PROPERTY_IS_REQUIRED = " property is Required"; - // Package on Purpose - final String domain; - final String atDomain; - final String realm; - - private final String NAME,mailHost,mailFrom; - private final Set supportedRealms; - - - public DefaultOrg(Env env, String realm) throws OrganizationException { - - this.realm = realm; - supportedRealms=new HashSet<>(); - supportedRealms.add(realm); - domain=FQI.reverseDomain(realm); - atDomain = '@'+domain; - String s; - NAME=env.getProperty(realm + ".name","Default Organization"); - mailHost = env.getProperty(s=(realm + ".mailHost"), null); - if(mailHost==null) { - throw new OrganizationException(s + PROPERTY_IS_REQUIRED); - } - mailFrom = env.getProperty(s=(realm + ".mailFrom"), null); - if(mailFrom==null) { - throw new OrganizationException(s + PROPERTY_IS_REQUIRED); - } - - // Note: This code is to avoid including javax.mail into ONAP, because there are security/licence - // exceptions - try { - Class.forName("javax.mail.Session"); // ensure package is loaded - @SuppressWarnings("unchecked") - Class minst = (Class)Class.forName("org.onap.aaf.org.JavaxMailer"); - mailer = minst.newInstance(); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e1) { - env.warn().log("JavaxMailer not loaded. Mailing disabled"); - } - - System.getProperties().setProperty("mail.smtp.host",mailHost); - System.getProperties().setProperty("mail.user", mailFrom); - - try { - String defFile; - String temp=env.getProperty(defFile = (getClass().getName()+".file")); - File fIdentities=null; - if(temp==null) { - temp = env.getProperty(AAF_DATA_DIR); - if(temp!=null) { - env.warn().log(defFile, " is not defined. Using default: ",temp+"/identities.dat"); - File dir = new File(temp); - fIdentities=new File(dir,"identities.dat"); - - if(!fIdentities.exists()) { - env.warn().log("No",fIdentities.getCanonicalPath(),"exists. Creating."); - if(!dir.exists()) { - dir.mkdirs(); - } - fIdentities.createNewFile(); - } - } - } else { - fIdentities = new File(temp); - if(!fIdentities.exists()) { - String dataDir = env.getProperty(AAF_DATA_DIR); - if(dataDir!=null) { - fIdentities = new File(dataDir,temp); - } - } - } - - if(fIdentities!=null && fIdentities.exists()) { - identities = new Identities(fIdentities); - } else { - if(fIdentities==null) { - throw new OrganizationException("No Identities"); - } else { - throw new OrganizationException(fIdentities.getCanonicalPath() + " does not exist."); - } - } - } catch (IOException e) { - throw new OrganizationException(e); - } - } - - // Implement your own Delegation System - static final List NULL_DELEGATES = new ArrayList<>(); - - public Identities identities; - private boolean dryRun; - private Mailer mailer; - public enum Types {Employee, Contractor, Application, NotActive}; - private final static Set typeSet; - - static { - typeSet = new HashSet<>(); - for(Types t : Types.values()) { - typeSet.add(t.name()); - } - } - - private static final EmailWarnings emailWarnings = new DefaultOrgWarnings(); - - @Override - public String getName() { - return NAME; - } - - @Override - public String getRealm() { - return realm; - } - - @Override - public String getDomain() { - return domain; - } - - @Override - public DefaultOrgIdentity getIdentity(AuthzTrans trans, String id) throws OrganizationException { - int at = id.indexOf('@'); - return new DefaultOrgIdentity(trans,at<0?id:id.substring(0, at),this); - } - - // Note: Return a null if found; return a String Message explaining why not found. - @Override - public String isValidID(final AuthzTrans trans, final String id) { - try { - DefaultOrgIdentity u = getIdentity(trans,id); - return (u==null||!u.isFound())?id + "is not an Identity in " + getName():null; - } catch (OrganizationException e) { - return getName() + " could not lookup " + id + ": " + e.getLocalizedMessage(); - } - } - // Possible ID Pattern - // private static final Pattern ID_PATTERN=Pattern.compile("([\\w.-]+@[\\w.-]+).{4-13}"); - // Another one: ID_PATTERN = "(a-z[a-z0-9]{5-8}@.*).{4-13}"; - - @Override - public boolean isValidCred(final AuthzTrans trans, final String id) { - // have domain? - int at = id.indexOf('@'); - String sid; - if(at > 0) { - // Use this to prevent passwords to any but THIS domain. -// if(!id.regionMatches(at+1, domain, 0, id.length()-at-1)) { -// return false; -// } - sid = id.substring(0,at); - } else { - sid = id; - } - // We'll validate that it exists, rather than check patterns. - - return isValidID(trans, sid)==null; - // Check Pattern (if checking existing is too long) - // if(id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) { - // return true; - // } - // return false; - } - - private static final String SPEC_CHARS = "!@#$%^*-+?/,:;."; - private static final Pattern PASS_PATTERN=Pattern.compile("(((?=.*[a-z,A-Z])(((?=.*\\d))|(?=.*[" + SPEC_CHARS +"]))).{6,20})"); - /** - * ( # Start of group - * (?=.*[a-z,A-Z]) # must contain one character - * - * (?=.*\d) # must contain one digit from 0-9 - * OR - * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS - * - * . # match anything with previous condition checking - * {6,20} # length at least 6 characters and maximum of 20 - * ) # End of group - * - * Another example, more stringent pattern - private static final Pattern PASS_PATTERN=Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[" + SPEC_CHARS +"]).{6,20})"); - * Attribution: from mkyong.com - * ( # Start of group - * (?=.*\d) # must contain one digit from 0-9 - * (?=.*[a-z]) # must contain one lowercase characters - * (?=.*[A-Z]) # must contain one uppercase characters - * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS - * . # match anything with previous condition checking - * {6,20} # length at least 6 characters and maximum of 20 - * ) # End of group - */ - @Override - public String isValidPassword(final AuthzTrans trans, final String user, final String password, final String... prev) { - for(String p : prev) { - if(password.contains(p)) { // A more sophisticated algorithm might be better. - return "Password too similar to previous passwords"; - } - } - // If you have an Organization user/Password scheme, replace the following - if(PASS_PATTERN.matcher(password).matches()) { - return ""; - } - return "Password does not match " + NAME + " Password Standards"; - } - - private static final String[] rules = new String[] { - "Passwords must contain letters", - "Passwords must contain one of the following:", - " Number", - " One special symbols in the list \""+ SPEC_CHARS + '"', - "Passwords must be between 6 and 20 chars in length", - }; - - @Override - public String[] getPasswordRules() { - return rules; - } - - @Override - public Set getIdentityTypes() { - return typeSet; - } - - @Override - public Response notify(AuthzTrans trans, Notify type, String url, String[] identities, String[] ccs, String summary, Boolean urgent) { - String system = trans.getProperty("CASS_ENV", ""); - - ArrayList toList = new ArrayList<>(); - Identity identity; - if (identities != null) { - for (String user : identities) { - try { - identity = getIdentity(trans, user); - if (identity == null) { - trans.error().log( - "Failure to obtain User " + user + " for " - + getName()); - } else { - toList.add(identity.email()); - } - } catch (Exception e) { - trans.error().log( - e, - "Failure to obtain User " + user + " for " - + getName()); - } - } - } - - if (toList.isEmpty()) { - trans.error().log("No Users listed to email"); - return Response.ERR_NotificationFailure; - } - - ArrayList ccList = new ArrayList<>(); - - // If we're sending an urgent email, CC the user's supervisor - // - if (urgent) { - trans.info().log("urgent msg for: " + identities[0]); - try { - List supervisors = getApprovers(trans, identities[0]); - for (Identity us : supervisors) { - trans.info().log("supervisor: " + us.email()); - ccList.add(us.email()); - } - } catch (Exception e) { - trans.error().log(e, - "Failed to find supervisor for " + identities[0]); - } - } - - if (ccs != null) { - for (String user : ccs) { - try { - identity = getIdentity(trans, user); - ccList.add(identity.email()); - } catch (Exception e) { - trans.error().log( - e, - "Failure to obtain User " + user + " for " - + getName()); - } - } - } - - if (summary == null) { - summary = ""; - } - - switch (type) { - case Approval: - try { - sendEmail(trans, toList, ccList, - "AAF Approval Notification " - + (system.length() == 0 ? "" : "(ENV: " - + system + ")"), - "AAF is the " - + NAME - + "System for Fine-Grained Authorizations. You are being asked to Approve" - + (system.length() == 0 ? "" : " in the " - + system + " environment") - + " before AAF Actions can be taken.\n\n" - + "Please follow this link: \n\n\t" + url - + "\n\n" + summary, urgent); - } catch (Exception e) { - - trans.error().log(e, "Failure to send Email"); - return Response.ERR_NotificationFailure; - } - break; - case PasswordExpiration: - try { - sendEmail(trans, - toList, - ccList, - "AAF Password Expiration Warning " - + (system.length() == 0 ? "" : "(ENV: " - + system + ")"), - "AAF is the " - + NAME - + " System for Authorizations.\n\nOne or more passwords will expire soon or have expired" - + (system.length() == 0 ? "" : " in the " - + system + " environment") - + ".\n\nPasswords expired for more than 30 days without action are subject to deletion.\n\n" - + "Please follow each link to add a New Password with Expiration Date. Either are valid until expiration. " - + "Use this time to change the passwords on your system. If issues, reply to this email.\n\n" - + summary, urgent); - } catch (Exception e) { - trans.error().log(e, "Failure to send Email"); - return Response.ERR_NotificationFailure; - } - break; - - case RoleExpiration: - try { - sendEmail( - trans, - toList, - ccList, - "AAF Role Expiration Warning " - + (system.length() == 0 ? "" : "(ENV: " - + system + ")"), - "AAF is the " - + NAME - + " System for Authorizations. One or more roles will expire soon" - + (system.length() == 0 ? "" : " in the " - + system + " environment") - + ".\n\nRoles expired for more than 30 days are subject to deletion." - + "Please follow this link the GUI Command line, and either 'extend' or 'del' the user in the role.\n" - + "If issues, reply to this email.\n\n\t" + url - + "\n\n" + summary, urgent); - } catch (Exception e) { - trans.error().log(e, "Failure to send Email"); - return Response.ERR_NotificationFailure; - } - break; - default: - return Response.ERR_NotImplemented; - } - return Response.OK; - } - - - /** - * Default Policy is to set to 6 Months for Notification Types. - * add others/change as required - */ - @Override - public Date whenToValidate(Notify type, Date lastValidated) { - switch(type) { - case Approval: - case PasswordExpiration: - return null; - default: - GregorianCalendar gc = new GregorianCalendar(); - gc.setTime(lastValidated); - gc.add(GregorianCalendar.MONTH, 6); // 6 month policy - return gc.getTime(); - } - } - - @Override - public GregorianCalendar expiration(GregorianCalendar gc, Expiration exp, String... extra) { - GregorianCalendar now = new GregorianCalendar(); - GregorianCalendar rv = gc==null?now:(GregorianCalendar)gc.clone(); - switch (exp) { - case ExtendPassword: - // Extending Password give 5 extra days, max 8 days from now - rv.add(GregorianCalendar.DATE, 5); - now.add(GregorianCalendar.DATE, 8); - if(rv.after(now)) { - rv = now; - } - break; - case Future: - // Future requests last 15 days. - now.add(GregorianCalendar.DATE, 15); - rv = now; - break; - case Password: - // Passwords expire in 90 days - now.add(GregorianCalendar.DATE, 90); - rv = now; - break; - case TempPassword: - // Temporary Passwords last for 12 hours. - now.add(GregorianCalendar.DATE, 90); - rv = now; - break; - case UserDelegate: - // Delegations expire max in 2 months, renewable to 3 - rv.add(GregorianCalendar.MONTH, 2); - now.add(GregorianCalendar.MONTH, 3); - if(rv.after(now)) { - rv = now; - } - break; - case UserInRole: - // Roles expire in 6 months - now.add(GregorianCalendar.MONTH, 6); - rv = now; - break; - default: - // Unless other wise set, 6 months is default - now.add(GregorianCalendar.MONTH, 6); - rv = now; - break; - } - return rv; - } - - @Override - public EmailWarnings emailWarningPolicy() { - return emailWarnings; - } - - /** - * Assume the Supervisor is the Approver. - */ - @Override - public List getApprovers(AuthzTrans trans, String user) throws OrganizationException { - Identity orgIdentity = getIdentity(trans, user); - List orgIdentitys = new ArrayList<>(); - if(orgIdentity!=null) { - Identity supervisor = orgIdentity.responsibleTo(); - if(supervisor!=null) { - orgIdentitys.add(supervisor); - } - } - return orgIdentitys; - } - - @Override - public String getApproverType() { - return "supervisor"; - } - - @Override - public int startOfDay() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public boolean canHaveMultipleCreds(String id) { - // External entities are likely mono-password... if you change it, it is a global change. - // This is great for people, but horrible for Applications. - // - // AAF's Password can have multiple Passwords, each with their own Expiration Date. - // For Default Org, we'll assume true for all, but when you add your external - // Identity stores, you need to return "false" if they cannot support multiple Passwords like AAF - return true; - } - - @Override - public String validate(AuthzTrans trans, Policy policy, Executor executor, String... vars) throws OrganizationException { - switch(policy) { - case OWNS_MECHID: - case CREATE_MECHID: - if(vars.length>0) { - DefaultOrgIdentity thisID = getIdentity(trans,vars[0]); - if("a".equals(thisID.identity.status)) { // MechID - DefaultOrgIdentity requestor = getIdentity(trans, trans.user()); - if(requestor!=null) { - Identity mechid = getIdentity(trans, vars[0]); - if(mechid!=null) { - Identity sponsor = mechid.responsibleTo(); - if(sponsor!=null && requestor.fullID().equals(sponsor.fullID())) { - return null; - } else { - return trans.user() + " is not the Sponsor of MechID " + vars[0]; - } - } - } - } - } - return null; - - case CREATE_MECHID_BY_PERM_ONLY: - return getName() + " only allows sponsors to create MechIDs"; - - default: - return policy.name() + " is unsupported at " + getName(); - } - } - - @Override - public boolean isTestEnv() { - return false; - } - - @Override - public void setTestMode(boolean dryRun) { - this.dryRun = dryRun; - } - - private String extractRealm(final String r) { - int at; - if((at=r.indexOf('@'))>=0) { - return FQI.reverseDomain(r.substring(at+1)); - } - return r; - } - @Override - public boolean supportsRealm(final String r) { - if(r.endsWith(realm)) { - return true; - } else { - String erealm = extractRealm(r); - for(String sr : supportedRealms) { - if(erealm.startsWith(sr)) { - return true; - } - } - } - return false; - } - - @Override - public synchronized void addSupportedRealm(final String r) { - supportedRealms.add(extractRealm(r)); - } - - @Override - public int sendEmail(AuthzTrans trans, List toList, List ccList, String subject, String body, - Boolean urgent) throws OrganizationException { - if (mailer!=null) { - List to = new ArrayList<>(); - for(String em : toList) { - if(em.indexOf('@')<0) { - to.add(new DefaultOrgIdentity(trans, em, this).email()); - } else { - to.add(em); - } - } - - List cc = new ArrayList<>(); - if(ccList!=null) { - if(!ccList.isEmpty()) { - - for(String em : ccList) { - if(em.indexOf('@')<0) { - cc.add(new DefaultOrgIdentity(trans, em, this).email()); - } else { - cc.add(em); - } - } - } - - // for now, I want all emails so we can see what goes out. Remove later - if (!ccList.contains(mailFrom)) { - ccList.add(mailFrom); - } - } - - return mailer.sendEmail(trans,dryRun,mailFrom,to,cc,subject,body,urgent); - } else { - return 0; - } - } + private static final String AAF_DATA_DIR = "aaf_data_dir"; + private static final String PROPERTY_IS_REQUIRED = " property is Required"; + // Package on Purpose + final String domain; + final String atDomain; + final String realm; + + private final String NAME,mailHost,mailFrom; + private final Set supportedRealms; + + + public DefaultOrg(Env env, String realm) throws OrganizationException { + + this.realm = realm; + supportedRealms=new HashSet<>(); + supportedRealms.add(realm); + domain=FQI.reverseDomain(realm); + atDomain = '@'+domain; + String s; + NAME=env.getProperty(realm + ".name","Default Organization"); + mailHost = env.getProperty(s=(realm + ".mailHost"), null); + if(mailHost==null) { + throw new OrganizationException(s + PROPERTY_IS_REQUIRED); + } + mailFrom = env.getProperty(s=(realm + ".mailFrom"), null); + if(mailFrom==null) { + throw new OrganizationException(s + PROPERTY_IS_REQUIRED); + } + + // Note: This code is to avoid including javax.mail into ONAP, because there are security/licence + // exceptions + try { + Class.forName("javax.mail.Session"); // ensure package is loaded + @SuppressWarnings("unchecked") + Class minst = (Class)Class.forName("org.onap.aaf.org.JavaxMailer"); + mailer = minst.newInstance(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e1) { + env.warn().log("JavaxMailer not loaded. Mailing disabled"); + } + + System.getProperties().setProperty("mail.smtp.host",mailHost); + System.getProperties().setProperty("mail.user", mailFrom); + + try { + String defFile; + String temp=env.getProperty(defFile = (getClass().getName()+".file")); + File fIdentities=null; + if(temp==null) { + temp = env.getProperty(AAF_DATA_DIR); + if(temp!=null) { + env.warn().log(defFile, " is not defined. Using default: ",temp+"/identities.dat"); + File dir = new File(temp); + fIdentities=new File(dir,"identities.dat"); + + if(!fIdentities.exists()) { + env.warn().log("No",fIdentities.getCanonicalPath(),"exists. Creating."); + if(!dir.exists()) { + dir.mkdirs(); + } + fIdentities.createNewFile(); + } + } + } else { + fIdentities = new File(temp); + if(!fIdentities.exists()) { + String dataDir = env.getProperty(AAF_DATA_DIR); + if(dataDir!=null) { + fIdentities = new File(dataDir,temp); + } + } + } + + if(fIdentities!=null && fIdentities.exists()) { + identities = new Identities(fIdentities); + } else { + if(fIdentities==null) { + throw new OrganizationException("No Identities"); + } else { + throw new OrganizationException(fIdentities.getCanonicalPath() + " does not exist."); + } + } + } catch (IOException e) { + throw new OrganizationException(e); + } + } + + // Implement your own Delegation System + static final List NULL_DELEGATES = new ArrayList<>(); + + public Identities identities; + private boolean dryRun; + private Mailer mailer; + public enum Types {Employee, Contractor, Application, NotActive}; + private final static Set typeSet; + + static { + typeSet = new HashSet<>(); + for(Types t : Types.values()) { + typeSet.add(t.name()); + } + } + + private static final EmailWarnings emailWarnings = new DefaultOrgWarnings(); + + @Override + public String getName() { + return NAME; + } + + @Override + public String getRealm() { + return realm; + } + + @Override + public String getDomain() { + return domain; + } + + @Override + public DefaultOrgIdentity getIdentity(AuthzTrans trans, String id) throws OrganizationException { + int at = id.indexOf('@'); + return new DefaultOrgIdentity(trans,at<0?id:id.substring(0, at),this); + } + + // Note: Return a null if found; return a String Message explaining why not found. + @Override + public String isValidID(final AuthzTrans trans, final String id) { + try { + DefaultOrgIdentity u = getIdentity(trans,id); + return (u==null||!u.isFound())?id + "is not an Identity in " + getName():null; + } catch (OrganizationException e) { + return getName() + " could not lookup " + id + ": " + e.getLocalizedMessage(); + } + } + // Possible ID Pattern + // private static final Pattern ID_PATTERN=Pattern.compile("([\\w.-]+@[\\w.-]+).{4-13}"); + // Another one: ID_PATTERN = "(a-z[a-z0-9]{5-8}@.*).{4-13}"; + + @Override + public boolean isValidCred(final AuthzTrans trans, final String id) { + // have domain? + int at = id.indexOf('@'); + String sid; + if(at > 0) { + // Use this to prevent passwords to any but THIS domain. +// if(!id.regionMatches(at+1, domain, 0, id.length()-at-1)) { +// return false; +// } + sid = id.substring(0,at); + } else { + sid = id; + } + // We'll validate that it exists, rather than check patterns. + + return isValidID(trans, sid)==null; + // Check Pattern (if checking existing is too long) + // if(id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) { + // return true; + // } + // return false; + } + + private static final String SPEC_CHARS = "!@#$%^*-+?/,:;."; + private static final Pattern PASS_PATTERN=Pattern.compile("(((?=.*[a-z,A-Z])(((?=.*\\d))|(?=.*[" + SPEC_CHARS +"]))).{6,20})"); + /** + * ( # Start of group + * (?=.*[a-z,A-Z]) # must contain one character + * + * (?=.*\d) # must contain one digit from 0-9 + * OR + * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS + * + * . # match anything with previous condition checking + * {6,20} # length at least 6 characters and maximum of 20 + * ) # End of group + * + * Another example, more stringent pattern + private static final Pattern PASS_PATTERN=Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[" + SPEC_CHARS +"]).{6,20})"); + * Attribution: from mkyong.com + * ( # Start of group + * (?=.*\d) # must contain one digit from 0-9 + * (?=.*[a-z]) # must contain one lowercase characters + * (?=.*[A-Z]) # must contain one uppercase characters + * (?=.*[@#$%]) # must contain one special symbols in the list SPEC_CHARS + * . # match anything with previous condition checking + * {6,20} # length at least 6 characters and maximum of 20 + * ) # End of group + */ + @Override + public String isValidPassword(final AuthzTrans trans, final String user, final String password, final String... prev) { + for(String p : prev) { + if(password.contains(p)) { // A more sophisticated algorithm might be better. + return "Password too similar to previous passwords"; + } + } + // If you have an Organization user/Password scheme, replace the following + if(PASS_PATTERN.matcher(password).matches()) { + return ""; + } + return "Password does not match " + NAME + " Password Standards"; + } + + private static final String[] rules = new String[] { + "Passwords must contain letters", + "Passwords must contain one of the following:", + " Number", + " One special symbols in the list \""+ SPEC_CHARS + '"', + "Passwords must be between 6 and 20 chars in length", + }; + + @Override + public String[] getPasswordRules() { + return rules; + } + + @Override + public Set getIdentityTypes() { + return typeSet; + } + + @Override + public Response notify(AuthzTrans trans, Notify type, String url, String[] identities, String[] ccs, String summary, Boolean urgent) { + String system = trans.getProperty("CASS_ENV", ""); + + ArrayList toList = new ArrayList<>(); + Identity identity; + if (identities != null) { + for (String user : identities) { + try { + identity = getIdentity(trans, user); + if (identity == null) { + trans.error().log( + "Failure to obtain User " + user + " for " + + getName()); + } else { + toList.add(identity.email()); + } + } catch (Exception e) { + trans.error().log( + e, + "Failure to obtain User " + user + " for " + + getName()); + } + } + } + + if (toList.isEmpty()) { + trans.error().log("No Users listed to email"); + return Response.ERR_NotificationFailure; + } + + ArrayList ccList = new ArrayList<>(); + + // If we're sending an urgent email, CC the user's supervisor + // + if (urgent) { + trans.info().log("urgent msg for: " + identities[0]); + try { + List supervisors = getApprovers(trans, identities[0]); + for (Identity us : supervisors) { + trans.info().log("supervisor: " + us.email()); + ccList.add(us.email()); + } + } catch (Exception e) { + trans.error().log(e, + "Failed to find supervisor for " + identities[0]); + } + } + + if (ccs != null) { + for (String user : ccs) { + try { + identity = getIdentity(trans, user); + ccList.add(identity.email()); + } catch (Exception e) { + trans.error().log( + e, + "Failure to obtain User " + user + " for " + + getName()); + } + } + } + + if (summary == null) { + summary = ""; + } + + switch (type) { + case Approval: + try { + sendEmail(trans, toList, ccList, + "AAF Approval Notification " + + (system.length() == 0 ? "" : "(ENV: " + + system + ")"), + "AAF is the " + + NAME + + "System for Fine-Grained Authorizations. You are being asked to Approve" + + (system.length() == 0 ? "" : " in the " + + system + " environment") + + " before AAF Actions can be taken.\n\n" + + "Please follow this link: \n\n\t" + url + + "\n\n" + summary, urgent); + } catch (Exception e) { + + trans.error().log(e, "Failure to send Email"); + return Response.ERR_NotificationFailure; + } + break; + case PasswordExpiration: + try { + sendEmail(trans, + toList, + ccList, + "AAF Password Expiration Warning " + + (system.length() == 0 ? "" : "(ENV: " + + system + ")"), + "AAF is the " + + NAME + + " System for Authorizations.\n\nOne or more passwords will expire soon or have expired" + + (system.length() == 0 ? "" : " in the " + + system + " environment") + + ".\n\nPasswords expired for more than 30 days without action are subject to deletion.\n\n" + + "Please follow each link to add a New Password with Expiration Date. Either are valid until expiration. " + + "Use this time to change the passwords on your system. If issues, reply to this email.\n\n" + + summary, urgent); + } catch (Exception e) { + trans.error().log(e, "Failure to send Email"); + return Response.ERR_NotificationFailure; + } + break; + + case RoleExpiration: + try { + sendEmail( + trans, + toList, + ccList, + "AAF Role Expiration Warning " + + (system.length() == 0 ? "" : "(ENV: " + + system + ")"), + "AAF is the " + + NAME + + " System for Authorizations. One or more roles will expire soon" + + (system.length() == 0 ? "" : " in the " + + system + " environment") + + ".\n\nRoles expired for more than 30 days are subject to deletion." + + "Please follow this link the GUI Command line, and either 'extend' or 'del' the user in the role.\n" + + "If issues, reply to this email.\n\n\t" + url + + "\n\n" + summary, urgent); + } catch (Exception e) { + trans.error().log(e, "Failure to send Email"); + return Response.ERR_NotificationFailure; + } + break; + default: + return Response.ERR_NotImplemented; + } + return Response.OK; + } + + + /** + * Default Policy is to set to 6 Months for Notification Types. + * add others/change as required + */ + @Override + public Date whenToValidate(Notify type, Date lastValidated) { + switch(type) { + case Approval: + case PasswordExpiration: + return null; + default: + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(lastValidated); + gc.add(GregorianCalendar.MONTH, 6); // 6 month policy + return gc.getTime(); + } + } + + @Override + public GregorianCalendar expiration(GregorianCalendar gc, Expiration exp, String... extra) { + GregorianCalendar now = new GregorianCalendar(); + GregorianCalendar rv = gc==null?now:(GregorianCalendar)gc.clone(); + switch (exp) { + case ExtendPassword: + // Extending Password give 5 extra days, max 8 days from now + rv.add(GregorianCalendar.DATE, 5); + now.add(GregorianCalendar.DATE, 8); + if(rv.after(now)) { + rv = now; + } + break; + case Future: + // Future requests last 15 days. + now.add(GregorianCalendar.DATE, 15); + rv = now; + break; + case Password: + // Passwords expire in 90 days + now.add(GregorianCalendar.DATE, 90); + rv = now; + break; + case TempPassword: + // Temporary Passwords last for 12 hours. + now.add(GregorianCalendar.DATE, 90); + rv = now; + break; + case UserDelegate: + // Delegations expire max in 2 months, renewable to 3 + rv.add(GregorianCalendar.MONTH, 2); + now.add(GregorianCalendar.MONTH, 3); + if(rv.after(now)) { + rv = now; + } + break; + case UserInRole: + // Roles expire in 6 months + now.add(GregorianCalendar.MONTH, 6); + rv = now; + break; + default: + // Unless other wise set, 6 months is default + now.add(GregorianCalendar.MONTH, 6); + rv = now; + break; + } + return rv; + } + + @Override + public EmailWarnings emailWarningPolicy() { + return emailWarnings; + } + + /** + * Assume the Supervisor is the Approver. + */ + @Override + public List getApprovers(AuthzTrans trans, String user) throws OrganizationException { + Identity orgIdentity = getIdentity(trans, user); + List orgIdentitys = new ArrayList<>(); + if(orgIdentity!=null) { + Identity supervisor = orgIdentity.responsibleTo(); + if(supervisor!=null) { + orgIdentitys.add(supervisor); + } + } + return orgIdentitys; + } + + @Override + public String getApproverType() { + return "supervisor"; + } + + @Override + public int startOfDay() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean canHaveMultipleCreds(String id) { + // External entities are likely mono-password... if you change it, it is a global change. + // This is great for people, but horrible for Applications. + // + // AAF's Password can have multiple Passwords, each with their own Expiration Date. + // For Default Org, we'll assume true for all, but when you add your external + // Identity stores, you need to return "false" if they cannot support multiple Passwords like AAF + return true; + } + + @Override + public String validate(AuthzTrans trans, Policy policy, Executor executor, String... vars) throws OrganizationException { + switch(policy) { + case OWNS_MECHID: + case CREATE_MECHID: + if(vars.length>0) { + DefaultOrgIdentity thisID = getIdentity(trans,vars[0]); + if("a".equals(thisID.identity.status)) { // MechID + DefaultOrgIdentity requestor = getIdentity(trans, trans.user()); + if(requestor!=null) { + Identity mechid = getIdentity(trans, vars[0]); + if(mechid!=null) { + Identity sponsor = mechid.responsibleTo(); + if(sponsor!=null && requestor.fullID().equals(sponsor.fullID())) { + return null; + } else { + return trans.user() + " is not the Sponsor of MechID " + vars[0]; + } + } + } + } + } + return null; + + case CREATE_MECHID_BY_PERM_ONLY: + return getName() + " only allows sponsors to create MechIDs"; + + default: + return policy.name() + " is unsupported at " + getName(); + } + } + + @Override + public boolean isTestEnv() { + return false; + } + + @Override + public void setTestMode(boolean dryRun) { + this.dryRun = dryRun; + } + + private String extractRealm(final String r) { + int at; + if((at=r.indexOf('@'))>=0) { + return FQI.reverseDomain(r.substring(at+1)); + } + return r; + } + @Override + public boolean supportsRealm(final String r) { + if(r.endsWith(realm)) { + return true; + } else { + String erealm = extractRealm(r); + for(String sr : supportedRealms) { + if(erealm.startsWith(sr)) { + return true; + } + } + } + return false; + } + + @Override + public synchronized void addSupportedRealm(final String r) { + supportedRealms.add(extractRealm(r)); + } + + @Override + public int sendEmail(AuthzTrans trans, List toList, List ccList, String subject, String body, + Boolean urgent) throws OrganizationException { + if (mailer!=null) { + List to = new ArrayList<>(); + for(String em : toList) { + if(em.indexOf('@')<0) { + to.add(new DefaultOrgIdentity(trans, em, this).email()); + } else { + to.add(em); + } + } + + List cc = new ArrayList<>(); + if(ccList!=null) { + if(!ccList.isEmpty()) { + + for(String em : ccList) { + if(em.indexOf('@')<0) { + cc.add(new DefaultOrgIdentity(trans, em, this).email()); + } else { + cc.add(em); + } + } + } + + // for now, I want all emails so we can see what goes out. Remove later + if (!ccList.contains(mailFrom)) { + ccList.add(mailFrom); + } + } + + return mailer.sendEmail(trans,dryRun,mailFrom,to,cc,subject,body,urgent); + } else { + return 0; + } + } } diff --git a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java index 7aa57fd7..25832620 100644 --- a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java +++ b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java @@ -40,140 +40,140 @@ import org.onap.aaf.org.Identities.Data; * */ public class DefaultOrgIdentity implements Identity { - private static final String CONTRACTOR = "c"; - private static final String EMPLOYEE = "e"; - private static final String APPLICATION = "a"; - private static final String NON_ACTIVE = "n"; - - private final static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); - - private DefaultOrg org; - //package on purpose - Data identity; - private AuthzTrans trans; - - public DefaultOrgIdentity(AuthzTrans trans, String key, DefaultOrg dorg) throws OrganizationException { - this.trans = trans; - org = dorg; - identity=null; - try { - org.identities.open(trans, TIMEOUT); - try { - Reuse r = org.identities.reuse(); - int at = key.indexOf(dorg.getDomain()); - String search; - if(at>=0) { - search = key.substring(0,at); - } else { - search = key; - } - identity = org.identities.find(search, r); - - - - if(identity==null) { - identity = Identities.NO_DATA; - } - } finally { - org.identities.close(trans); - } - } catch (IOException e) { - throw new OrganizationException(e); - } - } - - @Override - public boolean equals(Object b) { - if(b instanceof DefaultOrgIdentity) { - return identity.id.equals(((DefaultOrgIdentity)b).identity.id); - } - return false; - } - - - @Override - public int hashCode() { - return identity.hashCode(); - } - - @Override - public String id() { - return identity.id; - } - - @Override - public String fullID() { - return identity.id+'@'+org.getDomain(); - } - - @Override - public String type() { - switch(identity.status) { - case EMPLOYEE: return DefaultOrg.Types.Employee.name(); - case CONTRACTOR: return DefaultOrg.Types.Contractor.name(); - case APPLICATION: return DefaultOrg.Types.Application.name(); - case NON_ACTIVE: return DefaultOrg.Types.NotActive.name(); - default: - return "Unknown"; - } - } - - @Override - public Identity responsibleTo() throws OrganizationException { - if("".equals(identity.responsibleTo) && isFound()) { // cover the situation of Top Dog... reports to no-one. - return this; - } else { - return org.getIdentity(trans, identity.responsibleTo); - } - } - - @Override - public List delegate() { - //NOTE: implement Delegate system, if desired - return DefaultOrg.NULL_DELEGATES; - } - - @Override - public String email() { - return identity.email; - } - - @Override - public String fullName() { - return identity.name; - } - - @Override - public String firstName() { - return identity.fname; - } - - @Override - public String mayOwn() { - // Assume only Employees are responsible for Resources. - if(identity.status==null|| identity.status.length()==0) { - return "Identity must have valid status"; - } else if(EMPLOYEE.equals(identity.status)) { - return null; // This is "Yes, is Responsible" - } else { - return "Reponsible Party must be an Employee"; - } - } - - @Override - public boolean isFound() { - return identity!=Identities.NO_DATA; // yes, object comparison intended - } - - @Override - public boolean isPerson() { - return !identity.status.equals(APPLICATION); - } - - @Override - public Organization org() { - return org; - } + private static final String CONTRACTOR = "c"; + private static final String EMPLOYEE = "e"; + private static final String APPLICATION = "a"; + private static final String NON_ACTIVE = "n"; + + private final static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); + + private DefaultOrg org; + //package on purpose + Data identity; + private AuthzTrans trans; + + public DefaultOrgIdentity(AuthzTrans trans, String key, DefaultOrg dorg) throws OrganizationException { + this.trans = trans; + org = dorg; + identity=null; + try { + org.identities.open(trans, TIMEOUT); + try { + Reuse r = org.identities.reuse(); + int at = key.indexOf(dorg.getDomain()); + String search; + if(at>=0) { + search = key.substring(0,at); + } else { + search = key; + } + identity = org.identities.find(search, r); + + + + if(identity==null) { + identity = Identities.NO_DATA; + } + } finally { + org.identities.close(trans); + } + } catch (IOException e) { + throw new OrganizationException(e); + } + } + + @Override + public boolean equals(Object b) { + if(b instanceof DefaultOrgIdentity) { + return identity.id.equals(((DefaultOrgIdentity)b).identity.id); + } + return false; + } + + + @Override + public int hashCode() { + return identity.hashCode(); + } + + @Override + public String id() { + return identity.id; + } + + @Override + public String fullID() { + return identity.id+'@'+org.getDomain(); + } + + @Override + public String type() { + switch(identity.status) { + case EMPLOYEE: return DefaultOrg.Types.Employee.name(); + case CONTRACTOR: return DefaultOrg.Types.Contractor.name(); + case APPLICATION: return DefaultOrg.Types.Application.name(); + case NON_ACTIVE: return DefaultOrg.Types.NotActive.name(); + default: + return "Unknown"; + } + } + + @Override + public Identity responsibleTo() throws OrganizationException { + if("".equals(identity.responsibleTo) && isFound()) { // cover the situation of Top Dog... reports to no-one. + return this; + } else { + return org.getIdentity(trans, identity.responsibleTo); + } + } + + @Override + public List delegate() { + //NOTE: implement Delegate system, if desired + return DefaultOrg.NULL_DELEGATES; + } + + @Override + public String email() { + return identity.email; + } + + @Override + public String fullName() { + return identity.name; + } + + @Override + public String firstName() { + return identity.fname; + } + + @Override + public String mayOwn() { + // Assume only Employees are responsible for Resources. + if(identity.status==null|| identity.status.length()==0) { + return "Identity must have valid status"; + } else if(EMPLOYEE.equals(identity.status)) { + return null; // This is "Yes, is Responsible" + } else { + return "Reponsible Party must be an Employee"; + } + } + + @Override + public boolean isFound() { + return identity!=Identities.NO_DATA; // yes, object comparison intended + } + + @Override + public boolean isPerson() { + return !identity.status.equals(APPLICATION); + } + + @Override + public Organization org() { + return org; + } } diff --git a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgWarnings.java b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgWarnings.java index 97d0cef2..d544b709 100644 --- a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgWarnings.java +++ b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgWarnings.java @@ -25,39 +25,39 @@ import org.onap.aaf.auth.org.EmailWarnings; public class DefaultOrgWarnings implements EmailWarnings { - @Override - public long credEmailInterval() - { - return 604800000L; // 7 days in millis 1000 * 86400 * 7 - } - - @Override - public long roleEmailInterval() - { - return 604800000L; // 7 days in millis 1000 * 86400 * 7 - } - - @Override - public long apprEmailInterval() { - return 259200000L; // 3 days in millis 1000 * 86400 * 3 - } - - @Override - public long credExpirationWarning() - { - return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds - } - - @Override - public long roleExpirationWarning() - { - return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds - } - - @Override - public long emailUrgentWarning() - { - return( 1209600000L ); // Two weeks, in milliseconds 1000 * 86400 * 14 in milliseconds - } + @Override + public long credEmailInterval() + { + return 604800000L; // 7 days in millis 1000 * 86400 * 7 + } + + @Override + public long roleEmailInterval() + { + return 604800000L; // 7 days in millis 1000 * 86400 * 7 + } + + @Override + public long apprEmailInterval() { + return 259200000L; // 3 days in millis 1000 * 86400 * 3 + } + + @Override + public long credExpirationWarning() + { + return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds + } + + @Override + public long roleExpirationWarning() + { + return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds + } + + @Override + public long emailUrgentWarning() + { + return( 1209600000L ); // Two weeks, in milliseconds 1000 * 86400 * 14 in milliseconds + } } diff --git a/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java b/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java index 344d0552..345e6e82 100644 --- a/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java +++ b/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java @@ -31,113 +31,113 @@ import org.onap.aaf.auth.local.DataFile.Token.Field; * Example User Data file, which can be modified for many different kinds of Data Feeds. * * Note: This has shown to be extremely effective in AT&T, an acknowledged very large organizations, - * because there is no need to synchronize records. AAF simply receives a Data Feed in Organization - * defined intervals. (You might want to check for validity, such as size, etc), then is copied into - * Data Directory. You will want to do so first creating a "lock" file. Assuming the File name is "users.dat", - * the Lock File is "users.lock". + * because there is no need to synchronize records. AAF simply receives a Data Feed in Organization + * defined intervals. (You might want to check for validity, such as size, etc), then is copied into + * Data Directory. You will want to do so first creating a "lock" file. Assuming the File name is "users.dat", + * the Lock File is "users.lock". * - * After the movement of the Datafile into place, it is best to remove the Index File, then remove the lock file. + * After the movement of the Datafile into place, it is best to remove the Index File, then remove the lock file. * - * Note, Any AAF Programs needing this data WILL wait on the Lock file, so you should get fresh Data files + * Note, Any AAF Programs needing this data WILL wait on the Lock file, so you should get fresh Data files * in a "stage" directory, from WEB, or wherever, and then, after it is correct, do the following as fast as feasible. * - * a) lock + * a) lock * b) copy from stage * c) remove idx * d) unlock * - * If the Index File is either non-existent or out of date from the Data File, it will be reindexed, which - * has proven to be a very quick function, even with large numbers of entries. + * If the Index File is either non-existent or out of date from the Data File, it will be reindexed, which + * has proven to be a very quick function, even with large numbers of entries. * * This Sample Feed is set for a file with delimiter of "|". 512 is maximum expected line length. The "0" is the * field offset for the "key" to the record, which, for user, should be the unique Organization Identity. * */ public class Identities extends AbsData { - public final static Data NO_DATA = new Data(); + public final static Data NO_DATA = new Data(); - public Identities(File users) throws IOException { - super(users,'|',512,0); - } + public Identities(File users) throws IOException { + super(users,'|',512,0); + } - /* - * Example Field Layout. note, in this example, Application IDs and People IDs are mixed. You may want to split - * out AppIDs, choose your own status indicators, or whatever you use. - * 0 - unique ID - * 1 - full name - * 2 - first name - * 3 - last name - * 4 - phone - * 5 - official email - * 6 - employment status e=employee, c=contractor, a=application, n=no longer with company - * 7 - responsible to (i.e Supervisor for People, or AppOwner, if it's an App ID) - */ - public static class Data { - public final String id; - public final String name; - public final String fname; - public final String lname; - public final String phone; - public final String email; - public final String status; - public final String responsibleTo; + /* + * Example Field Layout. note, in this example, Application IDs and People IDs are mixed. You may want to split + * out AppIDs, choose your own status indicators, or whatever you use. + * 0 - unique ID + * 1 - full name + * 2 - first name + * 3 - last name + * 4 - phone + * 5 - official email + * 6 - employment status e=employee, c=contractor, a=application, n=no longer with company + * 7 - responsible to (i.e Supervisor for People, or AppOwner, if it's an App ID) + */ + public static class Data { + public final String id; + public final String name; + public final String fname; + public final String lname; + public final String phone; + public final String email; + public final String status; + public final String responsibleTo; - private Data(Field f) { - f.reset(); - id=f.next(); - name=f.next(); - fname=f.next(); - lname=f.next(); - phone=f.next(); - email=f.next(); - status=f.next(); - responsibleTo =f.next(); - } + private Data(Field f) { + f.reset(); + id=f.next(); + name=f.next(); + fname=f.next(); + lname=f.next(); + phone=f.next(); + email=f.next(); + status=f.next(); + responsibleTo =f.next(); + } - private Data() { - id = name = fname = lname = - phone = email = status = responsibleTo - = ""; - } + private Data() { + id = name = fname = lname = + phone = email = status = responsibleTo + = ""; + } - public String toString() { - return id + '|' + - name + '|' + - lname + '|' + - fname + '|' + - phone + '|' + - email + '|' + - status + '|' + - responsibleTo; - } + public String toString() { + return id + '|' + + name + '|' + + lname + '|' + + fname + '|' + + phone + '|' + + email + '|' + + status + '|' + + responsibleTo; + } - // Here, make up your own Methods which help you easily determine your Organization's structure - // in your Organization Object - public boolean hasStatus(String possible) { - return possible.contains(status); - } + // Here, make up your own Methods which help you easily determine your Organization's structure + // in your Organization Object + public boolean hasStatus(String possible) { + return possible.contains(status); + } - public boolean isEmployee() { - return "e".equals(status); - } + public boolean isEmployee() { + return "e".equals(status); + } - public boolean isContractor() { - return "c".equals(status); - } + public boolean isContractor() { + return "c".equals(status); + } - public boolean isApplication() { - return "a".equals(status); - } - } + public boolean isApplication() { + return "a".equals(status); + } + } - public Data find(Object key,Reuse r) throws IOException { - r.reset(); - // These are new, to allow for Thread Safety - int rec = ti.find(key,r,0); - if(rec<0) { - return null; - } - r.pos(rec); - return new Data(r.getFieldData()); - } + public Data find(Object key,Reuse r) throws IOException { + r.reset(); + // These are new, to allow for Thread Safety + int rec = ti.find(key,r,0); + if(rec<0) { + return null; + } + r.pos(rec); + return new Data(r.getFieldData()); + } } diff --git a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrg.java b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrg.java index b0ade8c0..e52f3cca 100644 --- a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrg.java +++ b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrg.java @@ -53,219 +53,219 @@ import org.powermock.modules.junit4.PowerMockRunner; public class JU_DefaultOrg { - private DefaultOrg defaultOrg; + private DefaultOrg defaultOrg; - Identities.Data data; + Identities.Data data; - @Mock - Env envMock; + @Mock + Env envMock; - @Mock - AuthzTrans authzTransMock; + @Mock + AuthzTrans authzTransMock; - @Mock - TimeTaken ttMock; + @Mock + TimeTaken ttMock; - @Mock - LogTarget logTargetMock; + @Mock + LogTarget logTargetMock; - private static final String PROPERTY_IS_REQUIRED = " property is Required"; - private static final String DOMAIN = "osaaf.com"; - private static final String REALM = "com.osaaf"; - private static final String NAME = "Default Organization"; - private static final String NO_PASS = NAME + " does not support Passwords. Use AAF"; + private static final String PROPERTY_IS_REQUIRED = " property is Required"; + private static final String DOMAIN = "osaaf.com"; + private static final String REALM = "com.osaaf"; + private static final String NAME = "Default Organization"; + private static final String NO_PASS = NAME + " does not support Passwords. Use AAF"; - private static final String URL = "www.deforg.com"; - private static final String IDENT = "ccontra|iowna"; - private static final String CCS = "mmanager|bdevl"; - String mailHost,mailFromUserId,summary,supportAddress; + private static final String URL = "www.deforg.com"; + private static final String IDENT = "ccontra|iowna"; + private static final String CCS = "mmanager|bdevl"; + String mailHost,mailFromUserId,summary,supportAddress; - private final static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); + private final static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF); - @Before - public void setUp() throws OrganizationException{ + @Before + public void setUp() throws OrganizationException{ - mailFromUserId = "frommail"; - mailHost = "hostmail"; - File file = new File("src/test/resources/"); - when(envMock.getProperty(REALM + ".name","Default Organization")).thenReturn(NAME); - when(envMock.getProperty(REALM + ".mailHost",null)).thenReturn(mailHost); - when(envMock.getProperty(REALM + ".mailFrom",null)).thenReturn(mailFromUserId); - when(envMock.getProperty("aaf_data_dir")).thenReturn(file.getAbsolutePath()); - when(envMock.warn()).thenReturn(logTargetMock); - when(authzTransMock.warn()).thenReturn(logTargetMock); - when(authzTransMock.start(any(String.class),any(Integer.class))).thenReturn(ttMock); - when(authzTransMock.error()).thenReturn(logTargetMock); - when(authzTransMock.getProperty("CASS_ENV", "")).thenReturn("Cassandra env"); + mailFromUserId = "frommail"; + mailHost = "hostmail"; + File file = new File("src/test/resources/"); + when(envMock.getProperty(REALM + ".name","Default Organization")).thenReturn(NAME); + when(envMock.getProperty(REALM + ".mailHost",null)).thenReturn(mailHost); + when(envMock.getProperty(REALM + ".mailFrom",null)).thenReturn(mailFromUserId); + when(envMock.getProperty("aaf_data_dir")).thenReturn(file.getAbsolutePath()); + when(envMock.warn()).thenReturn(logTargetMock); + when(authzTransMock.warn()).thenReturn(logTargetMock); + when(authzTransMock.start(any(String.class),any(Integer.class))).thenReturn(ttMock); + when(authzTransMock.error()).thenReturn(logTargetMock); + when(authzTransMock.getProperty("CASS_ENV", "")).thenReturn("Cassandra env"); - defaultOrg = new DefaultOrg(envMock, REALM); + defaultOrg = new DefaultOrg(envMock, REALM); - } + } - @Test - public void testDefOrg_returnDataIdentityNotNull() throws OrganizationException { + @Test + public void testDefOrg_returnDataIdentityNotNull() throws OrganizationException { - try { - defaultOrg.identities.open(authzTransMock, TIMEOUT); - try { - Reuse r = defaultOrg.identities.reuse(); - data = defaultOrg.identities.find("iowna", defaultOrg.identities.reuse()); - System.out.println("here is identities data: "+ data.toString()); + try { + defaultOrg.identities.open(authzTransMock, TIMEOUT); + try { + Reuse r = defaultOrg.identities.reuse(); + data = defaultOrg.identities.find("iowna", defaultOrg.identities.reuse()); + System.out.println("here is identities data: "+ data.toString()); - } finally { - defaultOrg.identities.close(authzTransMock); - } - } catch (IOException e) { - throw new OrganizationException(e); - } + } finally { + defaultOrg.identities.close(authzTransMock); + } + } catch (IOException e) { + throw new OrganizationException(e); + } - assertTrue(data.toString() != null); + assertTrue(data.toString() != null); - } + } - @Test - public void testDefOrg_returnDefOrgEntity() { + @Test + public void testDefOrg_returnDefOrgEntity() { - assertTrue(defaultOrg != null); + assertTrue(defaultOrg != null); - } + } - @Test - public void testDefOrgNotifyApproval_returnResponseOK() { + @Test + public void testDefOrgNotifyApproval_returnResponseOK() { - summary = "Approval"; - Boolean urgent = false; - DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.Approval, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); - assertEquals(response.name(), "OK"); + summary = "Approval"; + Boolean urgent = false; + DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.Approval, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); + assertEquals(response.name(), "OK"); - } - - @Test - public void testDefOrgPasswords() { - assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "new2You!", "Pilgrim"),""); - assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "new2you!", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "newtoyou", "Pilgrim"),""); - } + } + + @Test + public void testDefOrgPasswords() { + assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "new2You!", "Pilgrim"),""); + assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "new2you!", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "newtoyou", "Pilgrim"),""); + } - @Test - public void testDefOrgNotifyPasswordExpiration_returnResponseOK() { + @Test + public void testDefOrgNotifyPasswordExpiration_returnResponseOK() { - summary = "PasswordExpiration"; - Boolean urgent = false; - DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.PasswordExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); - assertEquals(response.name(), "OK"); + summary = "PasswordExpiration"; + Boolean urgent = false; + DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.PasswordExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); + assertEquals(response.name(), "OK"); - } + } - @Test - public void testDefOrgNotifyRoleExpiration_returnResponseOK() { + @Test + public void testDefOrgNotifyRoleExpiration_returnResponseOK() { - summary = "RoleExpiration"; - Boolean urgent = false; - DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); - assertEquals(response.name(), "OK"); - } + summary = "RoleExpiration"; + Boolean urgent = false; + DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); + assertEquals(response.name(), "OK"); + } - @Test - public void testDefOrgNotifyRoleExpirationUrgent_returnResponseOK() { + @Test + public void testDefOrgNotifyRoleExpirationUrgent_returnResponseOK() { - summary = "RoleExpirationUrgent"; - Boolean urgent = true; - when(authzTransMock.info()).thenReturn(logTargetMock); - DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); - assertEquals(response.name(), "OK"); + summary = "RoleExpirationUrgent"; + Boolean urgent = true; + when(authzTransMock.info()).thenReturn(logTargetMock); + DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); + assertEquals(response.name(), "OK"); - } - - @Test - public void testDefOrgNotifyModeTest_returnResponseOK() { - - summary = "ModeTest"; - Boolean urgent = false; - when(authzTransMock.info()).thenReturn(logTargetMock); - defaultOrg.setTestMode(true); - DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); - assertEquals(response.name(), "OK"); + } + + @Test + public void testDefOrgNotifyModeTest_returnResponseOK() { + + summary = "ModeTest"; + Boolean urgent = false; + when(authzTransMock.info()).thenReturn(logTargetMock); + defaultOrg.setTestMode(true); + DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent); + assertEquals(response.name(), "OK"); - } + } - //@Test //(expected=OrganizationException.class) - public void testMultipleCreds() throws OrganizationException{ - String id = "test"; - boolean canHaveMultipleCreds; - canHaveMultipleCreds = defaultOrg.canHaveMultipleCreds(id ); - System.out.println("value of canHaveMultipleCreds: " + canHaveMultipleCreds); - assertTrue(canHaveMultipleCreds); - } - + //@Test //(expected=OrganizationException.class) + public void testMultipleCreds() throws OrganizationException{ + String id = "test"; + boolean canHaveMultipleCreds; + canHaveMultipleCreds = defaultOrg.canHaveMultipleCreds(id ); + System.out.println("value of canHaveMultipleCreds: " + canHaveMultipleCreds); + assertTrue(canHaveMultipleCreds); + } + - //@Test - public void testGetIdentityTypes() throws OrganizationException{ - Set identityTypes = defaultOrg.getIdentityTypes(); - System.out.println("value of IdentityTypes: " + identityTypes); - assertTrue(identityTypes.size() == 4); - } + //@Test + public void testGetIdentityTypes() throws OrganizationException{ + Set identityTypes = defaultOrg.getIdentityTypes(); + System.out.println("value of IdentityTypes: " + identityTypes); + assertTrue(identityTypes.size() == 4); + } - //@Test - public void testGetRealm() throws OrganizationException{ - String realmTest = defaultOrg.getRealm(); - System.out.println("value of realm: " + realmTest); - assertTrue(realmTest == REALM); - } - - public void supportsRealm() { - String otherRealm = "org.ossaf.something"; - defaultOrg.addSupportedRealm(otherRealm); - assertTrue(defaultOrg.supportsRealm(otherRealm)); - } - //@Test - public void testGetName() throws OrganizationException{ - String testName = defaultOrg.getName(); - System.out.println("value of name: " + testName); - assertTrue(testName == NAME); - } - - - //@Test - public void testGetDomain() throws OrganizationException{ - String testDomain = defaultOrg.getDomain(); - System.out.println("value of domain: " + testDomain); - assertTrue(testDomain == DOMAIN); - } - - // @Test - // public void testIsValidID(){ - // String Result = defaultOrg.isValidID(Matchers.anyString()); - // System.out.println("value of res " +Result); - // assertNotNull(Result); - // } - - @Test - public void testResponsible() throws OrganizationException { - Identity id = defaultOrg.getIdentity(authzTransMock, "osaaf"); - Identity rt = id.responsibleTo(); - assertTrue(rt.id().equals("bdevl")); - - } - - //@Test - public void notYetImplemented() { - fail("Tests in this file should not be trusted"); - } + //@Test + public void testGetRealm() throws OrganizationException{ + String realmTest = defaultOrg.getRealm(); + System.out.println("value of realm: " + realmTest); + assertTrue(realmTest == REALM); + } + + public void supportsRealm() { + String otherRealm = "org.ossaf.something"; + defaultOrg.addSupportedRealm(otherRealm); + assertTrue(defaultOrg.supportsRealm(otherRealm)); + } + //@Test + public void testGetName() throws OrganizationException{ + String testName = defaultOrg.getName(); + System.out.println("value of name: " + testName); + assertTrue(testName == NAME); + } + + + //@Test + public void testGetDomain() throws OrganizationException{ + String testDomain = defaultOrg.getDomain(); + System.out.println("value of domain: " + testDomain); + assertTrue(testDomain == DOMAIN); + } + + // @Test + // public void testIsValidID(){ + // String Result = defaultOrg.isValidID(Matchers.anyString()); + // System.out.println("value of res " +Result); + // assertNotNull(Result); + // } + + @Test + public void testResponsible() throws OrganizationException { + Identity id = defaultOrg.getIdentity(authzTransMock, "osaaf"); + Identity rt = id.responsibleTo(); + assertTrue(rt.id().equals("bdevl")); + + } + + //@Test + public void notYetImplemented() { + fail("Tests in this file should not be trusted"); + } } diff --git a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgIdentity.java b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgIdentity.java index 3e5c74b5..d0d08075 100644 --- a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgIdentity.java +++ b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgIdentity.java @@ -44,120 +44,120 @@ import java.io.IOException; @RunWith(PowerMockRunner.class) public class JU_DefaultOrgIdentity { - private DefaultOrg defaultOrgMock; + private DefaultOrg defaultOrgMock; - @Mock - private Reuse rMock; + @Mock + private Reuse rMock; - @Mock - AuthzTrans authzTransMock; + @Mock + AuthzTrans authzTransMock; - @Mock - private Data dataMock; + @Mock + private Data dataMock; - @Mock - private DefaultOrgIdentity defaultOrgIdentity; + @Mock + private DefaultOrgIdentity defaultOrgIdentity; - static String key = "iowna@deforg"; - static String orgDomain = "@deforg"; + static String key = "iowna@deforg"; + static String orgDomain = "@deforg"; - @Before - public void setUp() throws IOException, OrganizationException { - MockitoAnnotations.initMocks(this); - defaultOrgMock = PowerMockito.mock(DefaultOrg.class); - defaultOrgMock.identities = mock(Identities.class); + @Before + public void setUp() throws IOException, OrganizationException { + MockitoAnnotations.initMocks(this); + defaultOrgMock = PowerMockito.mock(DefaultOrg.class); + defaultOrgMock.identities = mock(Identities.class); - authzTransMock = PowerMockito.mock(AuthzTrans.class); + authzTransMock = PowerMockito.mock(AuthzTrans.class); - when(defaultOrgMock.getDomain()).thenReturn(orgDomain); - when(defaultOrgMock.identities.reuse()).thenReturn(rMock); - when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(dataMock); + when(defaultOrgMock.getDomain()).thenReturn(orgDomain); + when(defaultOrgMock.identities.reuse()).thenReturn(rMock); + when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(dataMock); - defaultOrgIdentity = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); + defaultOrgIdentity = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); - } + } - @Test - public void testIdentify_returnIdentifiedEntity() { + @Test + public void testIdentify_returnIdentifiedEntity() { - assertTrue(defaultOrgIdentity.id() != null); + assertTrue(defaultOrgIdentity.id() != null); - } + } - @Test - public void testIdentify_returnIdentifiedEntityWithDataNull() throws IOException, OrganizationException { + @Test + public void testIdentify_returnIdentifiedEntityWithDataNull() throws IOException, OrganizationException { - when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(null); + when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(null); - DefaultOrgIdentity defaultOrgIdentityDataNull = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); - assertTrue(defaultOrgIdentityDataNull.id() != null); + DefaultOrgIdentity defaultOrgIdentityDataNull = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); + assertTrue(defaultOrgIdentityDataNull.id() != null); - } + } - @Test(expected = OrganizationException.class) - public void testIdentify_returnThrowIOException() throws OrganizationException { + @Test(expected = OrganizationException.class) + public void testIdentify_returnThrowIOException() throws OrganizationException { - when(defaultOrgMock.getDomain()).thenReturn(orgDomain); - when(defaultOrgMock.identities.reuse()).thenThrow(IOException.class); - DefaultOrgIdentity defaultOrgIdentityException = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); + when(defaultOrgMock.getDomain()).thenReturn(orgDomain); + when(defaultOrgMock.identities.reuse()).thenThrow(IOException.class); + DefaultOrgIdentity defaultOrgIdentityException = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); - } + } - @Test - public void testEquals_returnTrue() { + @Test + public void testEquals_returnTrue() { - Object b = defaultOrgIdentity; - assertTrue(defaultOrgIdentity.equals(b) == true ); - } + Object b = defaultOrgIdentity; + assertTrue(defaultOrgIdentity.equals(b) == true ); + } - @Test - public void testStatus_returnUnknown() { + @Test + public void testStatus_returnUnknown() { - assertEquals(defaultOrgIdentity.type(), "Unknown"); + assertEquals(defaultOrgIdentity.type(), "Unknown"); - } + } - @Test - public void testHash_returnHashCode() { + @Test + public void testHash_returnHashCode() { - assertTrue(defaultOrgIdentity.hashCode() != 0 ); + assertTrue(defaultOrgIdentity.hashCode() != 0 ); - } + } - @Test - public void testFullId_returnFullId() throws IOException, OrganizationException{ - String key="toto@deforg"; - String orgDomain="@deforg"; - when(defaultOrgMock.getDomain()).thenReturn(orgDomain); - when(defaultOrgMock.identities.reuse()).thenReturn(rMock); - when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(dataMock); - defaultOrgIdentity = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); + @Test + public void testFullId_returnFullId() throws IOException, OrganizationException{ + String key="toto@deforg"; + String orgDomain="@deforg"; + when(defaultOrgMock.getDomain()).thenReturn(orgDomain); + when(defaultOrgMock.identities.reuse()).thenReturn(rMock); + when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(dataMock); + defaultOrgIdentity = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock); - assertTrue(defaultOrgIdentity.fullID().contains("@") ); - } + assertTrue(defaultOrgIdentity.fullID().contains("@") ); + } - @Test - public void testEmail_returnEmail() { + @Test + public void testEmail_returnEmail() { - assertTrue(defaultOrgIdentity.email() != null ); - } + assertTrue(defaultOrgIdentity.email() != null ); + } - @Test - public void testFullName_returnFullName() { + @Test + public void testFullName_returnFullName() { - assertTrue(defaultOrgIdentity.fullName() != null ); - } + assertTrue(defaultOrgIdentity.fullName() != null ); + } - @Test - public void testFirstName_returnFirstName() { + @Test + public void testFirstName_returnFirstName() { - assertTrue(defaultOrgIdentity.firstName() != null ); - } + assertTrue(defaultOrgIdentity.firstName() != null ); + } diff --git a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgWarnings.java b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgWarnings.java index 2692d608..ad92c3e1 100644 --- a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgWarnings.java +++ b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_DefaultOrgWarnings.java @@ -34,50 +34,50 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_DefaultOrgWarnings { - private DefaultOrgWarnings defaultOrgWarningsMock; - private DefaultOrgWarnings defaultOrgWarnings; + private DefaultOrgWarnings defaultOrgWarningsMock; + private DefaultOrgWarnings defaultOrgWarnings; - @Before - public void setUp(){ - MockitoAnnotations.initMocks(this); + @Before + public void setUp(){ + MockitoAnnotations.initMocks(this); - defaultOrgWarningsMock = PowerMockito.mock(DefaultOrgWarnings.class); + defaultOrgWarningsMock = PowerMockito.mock(DefaultOrgWarnings.class); - defaultOrgWarnings = new DefaultOrgWarnings(); - } + defaultOrgWarnings = new DefaultOrgWarnings(); + } - @Test - public void testApprEmailInterval() { + @Test + public void testApprEmailInterval() { - assertEquals(259200000, defaultOrgWarnings.apprEmailInterval() ); - } + assertEquals(259200000, defaultOrgWarnings.apprEmailInterval() ); + } - @Test - public void testCredEmailInterval() { - assertEquals(604800000, defaultOrgWarnings.credEmailInterval()); + @Test + public void testCredEmailInterval() { + assertEquals(604800000, defaultOrgWarnings.credEmailInterval()); - } + } - @Test - public void testCredExpirationWarning() { - assertEquals(2592000000L, defaultOrgWarnings.credExpirationWarning()); - } + @Test + public void testCredExpirationWarning() { + assertEquals(2592000000L, defaultOrgWarnings.credExpirationWarning()); + } - @Test - public void testEmailUrgentWarning() { - assertEquals(1209600000L, defaultOrgWarnings.emailUrgentWarning()); - } + @Test + public void testEmailUrgentWarning() { + assertEquals(1209600000L, defaultOrgWarnings.emailUrgentWarning()); + } - @Test - public void testRoleEmailInterval() { - assertEquals(604800000L, defaultOrgWarnings.roleEmailInterval()); - } + @Test + public void testRoleEmailInterval() { + assertEquals(604800000L, defaultOrgWarnings.roleEmailInterval()); + } - @Test - public void testRoleExpirationWarning() { - assertEquals(2592000000L, defaultOrgWarnings.roleExpirationWarning()); - } + @Test + public void testRoleExpirationWarning() { + assertEquals(2592000000L, defaultOrgWarnings.roleExpirationWarning()); + } } diff --git a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java index 458d3b25..6fa7a347 100644 --- a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java +++ b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java @@ -44,67 +44,67 @@ import org.onap.aaf.org.Identities.Data; */ public class JU_Identities { // -// private static final String DATA_IDENTITIES = "/opt/app/onap/data/identities.dat"; -// private static File fids; -// private static Identities ids; -// private static AuthzEnv env; +// private static final String DATA_IDENTITIES = "/opt/app/onap/data/identities.dat"; +// private static File fids; +// private static Identities ids; +// private static AuthzEnv env; // -// /** -// * @throws java.lang.Exception -// */ -// @BeforeClass -// public static void setUpBeforeClass() throws Exception { -// env = new AuthzEnv(); -// AuthzTrans trans = env.newTransNoAvg(); -// // Note: utilize TimeTaken, from trans.start if you want to time. -// fids = new File(DATA_IDENTITIES); -// if(fids.exists()) { -// ids = new Identities(fids); -// ids.open(trans, 5000); -// } else { -// -// throw new Exception("Data File for Tests, \"" + DATA_IDENTITIES -// + "\" must exist before test can run. (Current dir is " + System.getProperty("user.dir") + ")"); -// } -// } +// /** +// * @throws java.lang.Exception +// */ +// @BeforeClass +// public static void setUpBeforeClass() throws Exception { +// env = new AuthzEnv(); +// AuthzTrans trans = env.newTransNoAvg(); +// // Note: utilize TimeTaken, from trans.start if you want to time. +// fids = new File(DATA_IDENTITIES); +// if(fids.exists()) { +// ids = new Identities(fids); +// ids.open(trans, 5000); +// } else { +// +// throw new Exception("Data File for Tests, \"" + DATA_IDENTITIES +// + "\" must exist before test can run. (Current dir is " + System.getProperty("user.dir") + ")"); +// } +// } // -// /** -// * @throws java.lang.Exception -// */ -// @AfterClass -// public static void tearDownAfterClass() throws Exception { -// AuthzTrans trans = env.newTransNoAvg(); -// if(ids!=null) { -// ids.close(trans); -// } -// } +// /** +// * @throws java.lang.Exception +// */ +// @AfterClass +// public static void tearDownAfterClass() throws Exception { +// AuthzTrans trans = env.newTransNoAvg(); +// if(ids!=null) { +// ids.close(trans); +// } +// } // -// /** -// * @throws java.lang.Exception -// */ -// @Before -// public void setUp() throws Exception { -// } +// /** +// * @throws java.lang.Exception +// */ +// @Before +// public void setUp() throws Exception { +// } // -// /** -// * @throws java.lang.Exception -// */ -// @After -// public void tearDown() throws Exception { -// } +// /** +// * @throws java.lang.Exception +// */ +// @After +// public void tearDown() throws Exception { +// } // -// @Test -// public void test() throws IOException { -// Reuse reuse = ids.reuse(); // this object can be reused within the same thread. -// Data id = ids.find("osaaf",reuse); -// Assert.assertNotNull(id); -// System.out.println(id); +// @Test +// public void test() throws IOException { +// Reuse reuse = ids.reuse(); // this object can be reused within the same thread. +// Data id = ids.find("osaaf",reuse); +// Assert.assertNotNull(id); +// System.out.println(id); // -// id = ids.find("mmanager",reuse); -// Assert.assertNotNull(id); -// System.out.println(id); +// id = ids.find("mmanager",reuse); +// Assert.assertNotNull(id); +// System.out.println(id); // -// //TODO Fill out JUnit with Tests of all Methods in "Data id" -// } +// //TODO Fill out JUnit with Tests of all Methods in "Data id" +// } } diff --git a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Passwords.java b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Passwords.java index 72e4ff87..847e59f1 100644 --- a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Passwords.java +++ b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Passwords.java @@ -46,80 +46,80 @@ import org.powermock.modules.junit4.PowerMockRunner; public class JU_Passwords { - private DefaultOrg defaultOrg; + private DefaultOrg defaultOrg; - Identities.Data data; + Identities.Data data; - @Mock - Env envMock; + @Mock + Env envMock; - @Mock - AuthzTrans authzTransMock; + @Mock + AuthzTrans authzTransMock; - @Mock - TimeTaken ttMock; + @Mock + TimeTaken ttMock; - @Mock - LogTarget logTargetMock; + @Mock + LogTarget logTargetMock; - private static final String REALM = "org.osaaf"; - private static final String NAME = "Default Organization"; + private static final String REALM = "org.osaaf"; + private static final String NAME = "Default Organization"; - String mailHost,mailFromUserId,summary,supportAddress; + String mailHost,mailFromUserId,summary,supportAddress; - @Before - public void setUp() throws OrganizationException{ + @Before + public void setUp() throws OrganizationException{ - mailFromUserId = "frommail"; - mailHost = "hostmail"; - File file = new File("src/test/resources/"); - when(envMock.getProperty(REALM + ".name","Default Organization")).thenReturn(NAME); - when(envMock.getProperty(REALM + ".mailHost",null)).thenReturn(mailHost); - when(envMock.getProperty(REALM + ".mailFrom",null)).thenReturn(mailFromUserId); - when(envMock.getProperty("aaf_data_dir")).thenReturn(file.getAbsolutePath()); - when(envMock.warn()).thenReturn(logTargetMock); - when(authzTransMock.warn()).thenReturn(logTargetMock); - when(authzTransMock.start(any(String.class),any(Integer.class))).thenReturn(ttMock); - when(authzTransMock.error()).thenReturn(logTargetMock); - when(authzTransMock.getProperty("CASS_ENV", "")).thenReturn("Cassandra env"); + mailFromUserId = "frommail"; + mailHost = "hostmail"; + File file = new File("src/test/resources/"); + when(envMock.getProperty(REALM + ".name","Default Organization")).thenReturn(NAME); + when(envMock.getProperty(REALM + ".mailHost",null)).thenReturn(mailHost); + when(envMock.getProperty(REALM + ".mailFrom",null)).thenReturn(mailFromUserId); + when(envMock.getProperty("aaf_data_dir")).thenReturn(file.getAbsolutePath()); + when(envMock.warn()).thenReturn(logTargetMock); + when(authzTransMock.warn()).thenReturn(logTargetMock); + when(authzTransMock.start(any(String.class),any(Integer.class))).thenReturn(ttMock); + when(authzTransMock.error()).thenReturn(logTargetMock); + when(authzTransMock.getProperty("CASS_ENV", "")).thenReturn("Cassandra env"); - defaultOrg = new DefaultOrg(envMock, REALM); + defaultOrg = new DefaultOrg(envMock, REALM); - } + } - @Test - public void testDefOrgPasswords() { - // Accepts letters and one of (number, Special Char, Upper) - assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "newyou2", "Pilgrim"),""); - assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "newyou!", "Pilgrim"),""); - assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "newyou!", "Pilgrim"),""); - - // Don't accept just letters, Numbers or Special Chars, or without ANY letters - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "newyouA", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "NEWYOU", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "newyou", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "125343", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "#$@*^#", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "#$3333", "Pilgrim"),""); + @Test + public void testDefOrgPasswords() { + // Accepts letters and one of (number, Special Char, Upper) + assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "newyou2", "Pilgrim"),""); + assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "newyou!", "Pilgrim"),""); + assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "newyou!", "Pilgrim"),""); + + // Don't accept just letters, Numbers or Special Chars, or without ANY letters + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "newyouA", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "NEWYOU", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "newyou", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "125343", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "#$@*^#", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "#$3333", "Pilgrim"),""); - // Length - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "w2Yu!", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "moreThan20somethingCharacters, even though good", "Pilgrim"),""); + // Length + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "w2Yu!", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "moreThan20somethingCharacters, even though good", "Pilgrim"),""); - // May not contain ID - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "Pilgrim", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "Pilgrim1", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "Pilgrim#", "Pilgrim"),""); - assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "aPilgrim1", "Pilgrim"),""); + // May not contain ID + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "Pilgrim", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "Pilgrim1", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "Pilgrim#", "Pilgrim"),""); + assertNotSame(defaultOrg.isValidPassword(authzTransMock, null, "aPilgrim1", "Pilgrim"),""); - // Solid - assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "new2You!", "Pilgrim"),""); + // Solid + assertEquals(defaultOrg.isValidPassword(authzTransMock, null, "new2You!", "Pilgrim"),""); - - } + + } } diff --git a/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java b/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java index ec507338..128c1f9b 100644 --- a/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java +++ b/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java @@ -49,70 +49,70 @@ import org.onap.aaf.misc.env.APIException; public class AAF_FS extends AbsService { - public AAF_FS(final AuthzEnv env) throws APIException, IOException, CadiException { - super(env.access(),env); - try { - /////////////////////// - // File Server - /////////////////////// - // creates StaticSlot, needed for CachingFileAccess, and sets to public Dir - env.staticSlot(CachingFileAccess.CFA_WEB_PATH,"aaf_public_dir"); + public AAF_FS(final AuthzEnv env) throws APIException, IOException, CadiException { + super(env.access(),env); + try { + /////////////////////// + // File Server + /////////////////////// + // creates StaticSlot, needed for CachingFileAccess, and sets to public Dir + env.staticSlot(CachingFileAccess.CFA_WEB_PATH,"aaf_public_dir"); - CachingFileAccess cfa = new CachingFileAccess(env); - route(env,GET,"/:key", cfa); - route(env,GET,"/:key/:cmd", cfa); - final String aaf_locate_url = access.getProperty(Config.AAF_LOCATE_URL, null); - if(aaf_locate_url == null) { - access.printf(Level.WARN, "Redirection requires property %s",Config.AAF_LOCATE_URL); - } else { - route(env,GET,"/", new Redirect(this,aaf_locate_url)); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private static class Redirect extends HttpCode { - private final String url; + CachingFileAccess cfa = new CachingFileAccess(env); + route(env,GET,"/:key", cfa); + route(env,GET,"/:key/:cmd", cfa); + final String aaf_locate_url = access.getProperty(Config.AAF_LOCATE_URL, null); + if(aaf_locate_url == null) { + access.printf(Level.WARN, "Redirection requires property %s",Config.AAF_LOCATE_URL); + } else { + route(env,GET,"/", new Redirect(this,aaf_locate_url)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static class Redirect extends HttpCode { + private final String url; - public Redirect(AAF_FS context,String url) { - super(context, "Redirect to HTTP/S"); - this.url = url; - } + public Redirect(AAF_FS context,String url) { + super(context, "Redirect to HTTP/S"); + this.url = url; + } - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - trans.info().printf("Redirecting %s to HTTP/S %s", req.getRemoteAddr(), req.getLocalAddr()); - resp.sendRedirect(url); - } - }; - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - // Note: No TAFs and Lurs on FileServer - return new Filter[] { - new AuthzTransOnlyFilter(env) - }; - } + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + trans.info().printf("Redirecting %s to HTTP/S %s", req.getRemoteAddr(), req.getLocalAddr()); + resp.sendRedirect(url); + } + }; + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + // Note: No TAFs and Lurs on FileServer + return new Filter[] { + new AuthzTransOnlyFilter(env) + }; + } - @SuppressWarnings("unchecked") - @Override - public Registrant[] registrants(final int port) throws CadiException, LocatorException { - return new Registrant[] { - new RemoteRegistrant(aafCon(),app_name,app_version,port) - }; - } - - public static void main(final String[] args) { - try { - Log4JLogIt logIt = new Log4JLogIt(args, "fs"); - PropAccess propAccess = new PropAccess(logIt,args); + @SuppressWarnings("unchecked") + @Override + public Registrant[] registrants(final int port) throws CadiException, LocatorException { + return new Registrant[] { + new RemoteRegistrant(aafCon(),app_name,app_version,port) + }; + } + + public static void main(final String[] args) { + try { + Log4JLogIt logIt = new Log4JLogIt(args, "fs"); + PropAccess propAccess = new PropAccess(logIt,args); - AAF_FS service = new AAF_FS(new AuthzEnv(propAccess)); - JettyServiceStarter jss = new JettyServiceStarter(service); - jss.insecure().start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + AAF_FS service = new AAF_FS(new AuthzEnv(propAccess)); + JettyServiceStarter jss = new JettyServiceStarter(service); + jss.insecure().start(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java b/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java index 3c68f61d..9915082b 100644 --- a/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java +++ b/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java @@ -49,82 +49,82 @@ import java.io.IOException; import java.io.PrintStream; public class JU_AAF_FS { - AuthzEnv aEnv; - AAF_FS aafFs; - File fService; - File fEtc; - String value; - File d; - private static final String testDir = "src/test/resources/logs"; - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream errStream; - - - @Before - public void setUp() throws APIException, IOException, CadiException { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - value = System.setProperty(Config.CADI_LOGDIR, testDir); - System.setProperty(Config.CADI_ETCDIR, testDir); - System.out.println(ClassLoader.getSystemResource("org.osaaf.aaf.log4j.props")); - d = new File(testDir); - d.mkdirs(); - fService = new File(d +"/fs-serviceTEST.log"); - fService.createNewFile(); - fEtc = new File(d + "/org.osaaf.aaf.log4j.props"); - fEtc.createNewFile(); - - aEnv = new AuthzEnv(); - aEnv.staticSlot("test"); - aEnv.access().setProperty("aaf_public_dir", "test"); - aEnv.access().setProperty(Config.AAF_COMPONENT, "aaf_com:1.1"); - Server serverMock = mock(Server.class); - JettyServiceStarter jssMock = mock(JettyServiceStarter.class); - aafFs = new AAF_FS(aEnv); - aEnv.access().setProperty(Config.AAF_LOCATE_URL, "aaf_loc:ate.url"); - aafFs = new AAF_FS(aEnv); - } - - @Test - public void testRegistrants() throws CadiException, LocatorException { - int port = 8008; - aEnv.access().setProperty(Config.AAF_URL, "www.google.com"); - aEnv.access().setProperty(Config.CADI_LATITUDE, "38.550674"); - aEnv.access().setProperty(Config.CADI_LONGITUDE, "-90.146942"); - aEnv.access().setProperty(Config.AAF_LOCATE_URL, "testLocateUrl"); - aEnv.access().setProperty(Config.HOSTNAME, "testHost"); - - // Doesn't work within Jenkins - // aafFs.registrants(port); - } - - @Test - public void testFilters() throws CadiException, LocatorException { - aafFs.filters(); - } - - @Test - public void testMain() { - System.setProperty("cadi_exitOnFailure", "false"); + AuthzEnv aEnv; + AAF_FS aafFs; + File fService; + File fEtc; + String value; + File d; + private static final String testDir = "src/test/resources/logs"; + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + + + @Before + public void setUp() throws APIException, IOException, CadiException { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + value = System.setProperty(Config.CADI_LOGDIR, testDir); + System.setProperty(Config.CADI_ETCDIR, testDir); + System.out.println(ClassLoader.getSystemResource("org.osaaf.aaf.log4j.props")); + d = new File(testDir); + d.mkdirs(); + fService = new File(d +"/fs-serviceTEST.log"); + fService.createNewFile(); + fEtc = new File(d + "/org.osaaf.aaf.log4j.props"); + fEtc.createNewFile(); + + aEnv = new AuthzEnv(); + aEnv.staticSlot("test"); + aEnv.access().setProperty("aaf_public_dir", "test"); + aEnv.access().setProperty(Config.AAF_COMPONENT, "aaf_com:1.1"); + Server serverMock = mock(Server.class); + JettyServiceStarter jssMock = mock(JettyServiceStarter.class); + aafFs = new AAF_FS(aEnv); + aEnv.access().setProperty(Config.AAF_LOCATE_URL, "aaf_loc:ate.url"); + aafFs = new AAF_FS(aEnv); + } + + @Test + public void testRegistrants() throws CadiException, LocatorException { + int port = 8008; + aEnv.access().setProperty(Config.AAF_URL, "www.google.com"); + aEnv.access().setProperty(Config.CADI_LATITUDE, "38.550674"); + aEnv.access().setProperty(Config.CADI_LONGITUDE, "-90.146942"); + aEnv.access().setProperty(Config.AAF_LOCATE_URL, "testLocateUrl"); + aEnv.access().setProperty(Config.HOSTNAME, "testHost"); + + // Doesn't work within Jenkins + // aafFs.registrants(port); + } + + @Test + public void testFilters() throws CadiException, LocatorException { + aafFs.filters(); + } + + @Test + public void testMain() { + System.setProperty("cadi_exitOnFailure", "false"); - String[] strArr = {"aaf_component=aaf_com:po.nent"}; - try { - //AAF_FS.main(strArr); //Timeout caused in Jenkins but not in local - } catch(Exception e) { - //Failure expected until we understand how code is. - } - } - - @After - public void cleanUp() { - for(File f : d.listFiles()) { - f.delete(); - } - d.delete(); - System.setErr(System.err); - System.setOut(System.out); - } + String[] strArr = {"aaf_component=aaf_com:po.nent"}; + try { + //AAF_FS.main(strArr); //Timeout caused in Jenkins but not in local + } catch(Exception e) { + //Failure expected until we understand how code is. + } + } + + @After + public void cleanUp() { + for(File f : d.listFiles()) { + f.delete(); + } + d.delete(); + System.setErr(System.err); + System.setOut(System.out); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java index 29e36505..ecbd0a25 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java @@ -38,56 +38,56 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.TimeTaken; public class CUI extends HttpCode { - private final AAF_GUI gui; - public CUI(AAF_GUI gui) { - super(null,"Command Line"); - this.gui = gui; - } + private final AAF_GUI gui; + public CUI(AAF_GUI gui) { + super(null,"Command Line"); + this.gui = gui; + } - @Override - public void handle(AuthzTrans trans, HttpServletRequest req,HttpServletResponse resp) throws Exception { - ServletInputStream isr = req.getInputStream(); - PrintWriter pw = resp.getWriter(); - int c; - StringBuilder cmd = new StringBuilder(); + @Override + public void handle(AuthzTrans trans, HttpServletRequest req,HttpServletResponse resp) throws Exception { + ServletInputStream isr = req.getInputStream(); + PrintWriter pw = resp.getWriter(); + int c; + StringBuilder cmd = new StringBuilder(); - while((c=isr.read())>=0) { - cmd.append((char)c); - } + while((c=isr.read())>=0) { + cmd.append((char)c); + } - TimeTaken tt = trans.start("Execute AAFCLI", Env.REMOTE); - try { - TaggedPrincipal p = trans.getUserPrincipal(); - // Access needs to be set after overall construction. Thus, the lazy create. - AAFcli aafcli; - AAFConHttp aafcon = gui.aafCon(); - aafcli= new AAFcli(gui.access,gui.env, pw, - aafcon.hman(), - aafcon.securityInfo(), - new HTransferSS(p,AAF_GUI.app, - aafcon.securityInfo())); - aafcli.verbose(false); - aafcli.gui(true); + TimeTaken tt = trans.start("Execute AAFCLI", Env.REMOTE); + try { + TaggedPrincipal p = trans.getUserPrincipal(); + // Access needs to be set after overall construction. Thus, the lazy create. + AAFcli aafcli; + AAFConHttp aafcon = gui.aafCon(); + aafcli= new AAFcli(gui.access,gui.env, pw, + aafcon.hman(), + aafcon.securityInfo(), + new HTransferSS(p,AAF_GUI.app, + aafcon.securityInfo())); + aafcli.verbose(false); + aafcli.gui(true); - String cmdStr = cmd.toString(); - if (!cmdStr.contains("--help")) { - cmdStr = cmdStr.replaceAll("help", "--help"); - } - if (!cmdStr.contains("--version")) { - cmdStr = cmdStr.replaceAll("version", "--version"); - } - try { - aafcli.eval(cmdStr); - pw.flush(); - } catch (Exception e) { - pw.flush(); - pw.println(e.getMessage()); - } finally { - aafcli.close(); - } - } finally { - tt.done(); - } - - } + String cmdStr = cmd.toString(); + if (!cmdStr.contains("--help")) { + cmdStr = cmdStr.replaceAll("help", "--help"); + } + if (!cmdStr.contains("--version")) { + cmdStr = cmdStr.replaceAll("version", "--version"); + } + try { + aafcli.eval(cmdStr); + pw.flush(); + } catch (Exception e) { + pw.flush(); + pw.println(e.getMessage()); + } finally { + aafcli.close(); + } + } finally { + tt.done(); + } + + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java index 3f26badb..84ad1b1f 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java @@ -95,175 +95,175 @@ import certman.v1_0.Artifacts; import certman.v1_0.CertInfo; public class AAF_GUI extends AbsService implements State{ - private static final String AAF_GUI_THEME = "aaf_gui_theme"; - public static final String AAF_GUI_COPYRIGHT = "aaf_gui_copyright"; - public static final String HTTP_SERVLET_REQUEST = "HTTP_SERVLET_REQUEST"; - public static final int TIMEOUT = 60000; - public static final String app = "AAF GUI"; - - // AAF API - - // Certificate manager API - public RosettaDF artifactsDF; - public RosettaDF certInfoDF; + private static final String AAF_GUI_THEME = "aaf_gui_theme"; + public static final String AAF_GUI_COPYRIGHT = "aaf_gui_copyright"; + public static final String HTTP_SERVLET_REQUEST = "HTTP_SERVLET_REQUEST"; + public static final int TIMEOUT = 60000; + public static final String app = "AAF GUI"; + + // AAF API + + // Certificate manager API + public RosettaDF artifactsDF; + public RosettaDF certInfoDF; - private final AAFConHttp cmCon; - public final AAFConHttp aafCon; - public final AAFLurPerm lur; - - public final Slot slot_httpServletRequest; - protected final String deployedVersion; - private StaticSlot sTheme; - public final String theme; + private final AAFConHttp cmCon; + public final AAFConHttp aafCon; + public final AAFLurPerm lur; + + public final Slot slot_httpServletRequest; + protected final String deployedVersion; + private StaticSlot sTheme; + public final String theme; - public AAF_GUI(final AuthzEnv env) throws Exception { - super(env.access(), env); - sTheme = env.staticSlot(CachingFileAccess.CFA_WEB_PATH,access.getProperty(CachingFileAccess.CFA_WEB_PATH,null)==null?AAF_GUI_THEME:CachingFileAccess.CFA_WEB_PATH); - theme = env.getProperty(AAF_GUI_THEME); + public AAF_GUI(final AuthzEnv env) throws Exception { + super(env.access(), env); + sTheme = env.staticSlot(CachingFileAccess.CFA_WEB_PATH,access.getProperty(CachingFileAccess.CFA_WEB_PATH,null)==null?AAF_GUI_THEME:CachingFileAccess.CFA_WEB_PATH); + theme = env.getProperty(AAF_GUI_THEME); - slot_httpServletRequest = env.slot(HTTP_SERVLET_REQUEST); - String[] component = Split.split(':', access.getProperty(Config.AAF_COMPONENT, "N/A:2.x")); - if(component.length>1) { - deployedVersion =component[1]; - } else { - deployedVersion = "2.x"; - } + slot_httpServletRequest = env.slot(HTTP_SERVLET_REQUEST); + String[] component = Split.split(':', access.getProperty(Config.AAF_COMPONENT, "N/A:2.x")); + if(component.length>1) { + deployedVersion =component[1]; + } else { + deployedVersion = "2.x"; + } - // Certificate Manager - cmCon = new AAFConHttp(env.access(),Config.CM_URL); - artifactsDF = env.newDataFactory(Artifacts.class); - certInfoDF = env.newDataFactory(CertInfo.class); - + // Certificate Manager + cmCon = new AAFConHttp(env.access(),Config.CM_URL); + artifactsDF = env.newDataFactory(Artifacts.class); + certInfoDF = env.newDataFactory(CertInfo.class); + - ///////////////////////// - // Screens - ///////////////////////// - // Start Screen - final Page start = new Display(this, GET, new Home(this)).page(); + ///////////////////////// + // Screens + ///////////////////////// + // Start Screen + final Page start = new Display(this, GET, new Home(this)).page(); - // MyPerms Screens - final Page myPerms = new Display(this, GET, new PermsShow(this, start)).page(); - Page permDetail = new Display(this, GET, new PermDetail(this, start, myPerms)).page(); - new Display(this, GET, new PermHistory(this,start,myPerms,permDetail)); + // MyPerms Screens + final Page myPerms = new Display(this, GET, new PermsShow(this, start)).page(); + Page permDetail = new Display(this, GET, new PermDetail(this, start, myPerms)).page(); + new Display(this, GET, new PermHistory(this,start,myPerms,permDetail)); - // MyRoles Screens - final Page myRoles = new Display(this, GET, new RolesShow(this, start)).page(); - Page roleDetail = new Display(this, GET, new RoleDetail(this, start, myRoles)).page(); - new Display(this, POST, new RoleDetailAction(this,start,myRoles,roleDetail)); - new Display(this, GET, new RoleHistory(this,start,myRoles,roleDetail)); - - // MyNameSpace - final Page myNamespaces = new Display(this, GET, new NssShow(this, start)).page(); - Page nsDetail = new Display(this, GET, new NsDetail(this, start, myNamespaces)).page(); - new Display(this, GET, new NsHistory(this, start,myNamespaces,nsDetail)); - Page crdDetail = new Display(this, GET, new CredDetail(this, start, myNamespaces, nsDetail)).page(); - Page artiShow = new Display(this, GET, new CMArtifactShow(this, start, myNamespaces, nsDetail, crdDetail)).page(); - Page artiCForm = new Display(this, GET, new CMArtiChangeForm(this, start, myNamespaces, nsDetail, crdDetail,artiShow)).page(); - new Display(this, POST, new CMArtiChangeAction(this, start,artiShow,artiCForm)); - - // Password Change Screens - final Page pwc = new Display(this, GET, new PassChangeForm(this, start,crdDetail)).page(); - new Display(this, POST, new PassChangeAction(this, start, pwc)); - - // Password Delete Screen - new Display(this, GET, new PassDeleteAction(this, start,crdDetail)); + // MyRoles Screens + final Page myRoles = new Display(this, GET, new RolesShow(this, start)).page(); + Page roleDetail = new Display(this, GET, new RoleDetail(this, start, myRoles)).page(); + new Display(this, POST, new RoleDetailAction(this,start,myRoles,roleDetail)); + new Display(this, GET, new RoleHistory(this,start,myRoles,roleDetail)); + + // MyNameSpace + final Page myNamespaces = new Display(this, GET, new NssShow(this, start)).page(); + Page nsDetail = new Display(this, GET, new NsDetail(this, start, myNamespaces)).page(); + new Display(this, GET, new NsHistory(this, start,myNamespaces,nsDetail)); + Page crdDetail = new Display(this, GET, new CredDetail(this, start, myNamespaces, nsDetail)).page(); + Page artiShow = new Display(this, GET, new CMArtifactShow(this, start, myNamespaces, nsDetail, crdDetail)).page(); + Page artiCForm = new Display(this, GET, new CMArtiChangeForm(this, start, myNamespaces, nsDetail, crdDetail,artiShow)).page(); + new Display(this, POST, new CMArtiChangeAction(this, start,artiShow,artiCForm)); + + // Password Change Screens + final Page pwc = new Display(this, GET, new PassChangeForm(this, start,crdDetail)).page(); + new Display(this, POST, new PassChangeAction(this, start, pwc)); + + // Password Delete Screen + new Display(this, GET, new PassDeleteAction(this, start,crdDetail)); - // Validation Change Screens - final Page validate = new Display(this, GET, new ApprovalForm(this, start)).page(); - new Display(this, POST, new ApprovalAction(this, start, validate)); - - // Onboard, Detailed Edit Screens - final Page onb = new Display(this, GET, new NsInfoForm(this, start)).page(); - new Display(this, POST, new NsInfoAction(this, start, onb)); + // Validation Change Screens + final Page validate = new Display(this, GET, new ApprovalForm(this, start)).page(); + new Display(this, POST, new ApprovalAction(this, start, validate)); + + // Onboard, Detailed Edit Screens + final Page onb = new Display(this, GET, new NsInfoForm(this, start)).page(); + new Display(this, POST, new NsInfoAction(this, start, onb)); - // Web Command Screens - /* final Page webCommand =*/ new Display(this, GET, new WebCommand(this, start)).page(); - - // API Docs - final Page apidocs = new Display(this, GET, new ApiDocs(this, start)).page(); - new Display(this, GET, new ApiExample(this,start, apidocs)).page(); - - // Permission Grant Page - final Page permGrant = new Display(this, GET, new PermGrantForm(this, start)).page(); - new Display(this, POST, new PermGrantAction(this, start, permGrant)).page(); - - // Login Landing if no credentials detected - final Page loginLanding = new Display(this, GET, new LoginLanding(this, start)).page(); - new Display(this, POST, new LoginLandingAction(this, start, loginLanding)); - - // User Role Request Extend and Remove - new Display(this, GET, new UserRoleExtend(this, start,myRoles)).page(); - new Display(this, GET, new UserRoleRemove(this, start,myRoles)).page(); - - // See my Pending Requests - final Page requestsShow = new Display(this, GET, new PendingRequestsShow(this, start)).page(); - new Display(this, GET, new RequestDetail(this, start, requestsShow)); - - // Command line Mechanism - route(env, PUT, "/gui/cui", new CUI(this),"text/plain;charset=utf-8","*/*"); - - /////////////////////// - // WebContent Handler - /////////////////////// - route(env,GET,"/"+env.get(sTheme)+"/:key", new CachingFileAccess(env)); - /////////////////////// - aafCon = aafCon(); - lur = aafCon.newLur(); - } - - public RosettaDF getDF(Class cls) throws APIException { - return Cmd.getDF(env,cls); - } - - public void writeError(AuthzTrans trans, Future fp, HTMLGen hgen, int indent) { - if(hgen!=null) { - String msg = aafCon.readableErrMsg(fp); - hgen.incr(HTMLGen.P,"style=text-indent:"+indent*10+"px") - .text("Error: ") - .text(msg) - .end(); - trans.checkpoint(msg); - } - } + // Web Command Screens + /* final Page webCommand =*/ new Display(this, GET, new WebCommand(this, start)).page(); + + // API Docs + final Page apidocs = new Display(this, GET, new ApiDocs(this, start)).page(); + new Display(this, GET, new ApiExample(this,start, apidocs)).page(); + + // Permission Grant Page + final Page permGrant = new Display(this, GET, new PermGrantForm(this, start)).page(); + new Display(this, POST, new PermGrantAction(this, start, permGrant)).page(); + + // Login Landing if no credentials detected + final Page loginLanding = new Display(this, GET, new LoginLanding(this, start)).page(); + new Display(this, POST, new LoginLandingAction(this, start, loginLanding)); + + // User Role Request Extend and Remove + new Display(this, GET, new UserRoleExtend(this, start,myRoles)).page(); + new Display(this, GET, new UserRoleRemove(this, start,myRoles)).page(); + + // See my Pending Requests + final Page requestsShow = new Display(this, GET, new PendingRequestsShow(this, start)).page(); + new Display(this, GET, new RequestDetail(this, start, requestsShow)); + + // Command line Mechanism + route(env, PUT, "/gui/cui", new CUI(this),"text/plain;charset=utf-8","*/*"); + + /////////////////////// + // WebContent Handler + /////////////////////// + route(env,GET,"/"+env.get(sTheme)+"/:key", new CachingFileAccess(env)); + /////////////////////// + aafCon = aafCon(); + lur = aafCon.newLur(); + } + + public RosettaDF getDF(Class cls) throws APIException { + return Cmd.getDF(env,cls); + } + + public void writeError(AuthzTrans trans, Future fp, HTMLGen hgen, int indent) { + if(hgen!=null) { + String msg = aafCon.readableErrMsg(fp); + hgen.incr(HTMLGen.P,"style=text-indent:"+indent*10+"px") + .text("Error: ") + .text(msg) + .end(); + trans.checkpoint(msg); + } + } - public RET cmClientAsUser(TaggedPrincipal p,Retryable retryable) throws APIException, LocatorException, CadiException { - return cmCon.hman().best(new HTransferSS(p,app, aafCon.securityInfo()), retryable); - } - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - try { - return new Filter[] { - new XFrameFilter(XFrameFilter.TYPE.none), - new AuthzTransFilter(env,aafCon(), - new AAFTrustChecker((Env)env), - additionalTafLurs), - new OrgLookupFilter() - }; - } catch (NumberFormatException e) { - throw new CadiException("Invalid Property information", e); - } - } + public RET cmClientAsUser(TaggedPrincipal p,Retryable retryable) throws APIException, LocatorException, CadiException { + return cmCon.hman().best(new HTransferSS(p,app, aafCon.securityInfo()), retryable); + } + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + try { + return new Filter[] { + new XFrameFilter(XFrameFilter.TYPE.none), + new AuthzTransFilter(env,aafCon(), + new AAFTrustChecker((Env)env), + additionalTafLurs), + new OrgLookupFilter() + }; + } catch (NumberFormatException e) { + throw new CadiException("Invalid Property information", e); + } + } - @SuppressWarnings("unchecked") - @Override - public Registrant[] registrants(final int port) throws CadiException, LocatorException { - return new Registrant[] { - new RemoteRegistrant(aafCon(),app_name,app_version,port) - }; - } + @SuppressWarnings("unchecked") + @Override + public Registrant[] registrants(final int port) throws CadiException, LocatorException { + return new Registrant[] { + new RemoteRegistrant(aafCon(),app_name,app_version,port) + }; + } - public static void main(final String[] args) { - try { - Log4JLogIt logIt = new Log4JLogIt(args, "gui"); - PropAccess propAccess = new PropAccess(logIt,args); + public static void main(final String[] args) { + try { + Log4JLogIt logIt = new Log4JLogIt(args, "gui"); + PropAccess propAccess = new PropAccess(logIt,args); - AAF_GUI service = new AAF_GUI(new AuthzEnv(propAccess)); - JettyServiceStarter jss = new JettyServiceStarter(service); - jss.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + AAF_GUI service = new AAF_GUI(new AuthzEnv(propAccess)); + JettyServiceStarter jss = new JettyServiceStarter(service); + jss.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java index 4602184f..c5c14d3f 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java @@ -37,54 +37,54 @@ import org.onap.aaf.misc.xgen.Mark; import org.onap.aaf.misc.xgen.html.HTMLGen; public class BreadCrumbs extends NamedCode { - private Page[] breadcrumbs; + private Page[] breadcrumbs; - public BreadCrumbs(Page ... pages) { - super(false,"breadcrumbs"); - breadcrumbs = pages; - } - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - // BreadCrumbs - Mark mark = new Mark(); - hgen.incr(mark, UL); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI gui, TransStore trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - HttpServletRequest req = trans.get(gui.slot_httpServletRequest, null); - StringBuilder key = new StringBuilder(); - String value, hidden; - for(Page p : breadcrumbs) { - hidden=""; - // Add keys for page from commandline, where possible. - if(p.fields().length>0) { - boolean first = true; - key.setLength(0); - for(String field : p.fields()) { - if((value=req.getParameter(field))==null) { - hidden="style=display:none;"; - break; - } - if(first) { - first = false; - key.append('?'); - } else { - key.append("&"); - } - key.append(field); - key.append('='); - key.append(value); - } - hgen.incr(LI,true,hidden); - hgen.leaf(A,"href="+p.url()+key.toString(),hidden).text(p.name()).end(2); - } else { - hgen.incr(LI,true); - hgen.leaf(A,"href="+p.url(),hidden).text(p.name()).end(2); - } - } - } - }); - hgen.end(mark); - } + public BreadCrumbs(Page ... pages) { + super(false,"breadcrumbs"); + breadcrumbs = pages; + } + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + // BreadCrumbs + Mark mark = new Mark(); + hgen.incr(mark, UL); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI gui, TransStore trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + HttpServletRequest req = trans.get(gui.slot_httpServletRequest, null); + StringBuilder key = new StringBuilder(); + String value, hidden; + for(Page p : breadcrumbs) { + hidden=""; + // Add keys for page from commandline, where possible. + if(p.fields().length>0) { + boolean first = true; + key.setLength(0); + for(String field : p.fields()) { + if((value=req.getParameter(field))==null) { + hidden="style=display:none;"; + break; + } + if(first) { + first = false; + key.append('?'); + } else { + key.append("&"); + } + key.append(field); + key.append('='); + key.append(value); + } + hgen.incr(LI,true,hidden); + hgen.leaf(A,"href="+p.url()+key.toString(),hidden).text(p.name()).end(2); + } else { + hgen.incr(LI,true); + hgen.leaf(A,"href="+p.url(),hidden).text(p.name()).end(2); + } + } + } + }); + hgen.end(mark); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/ContentCode.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/ContentCode.java index d3c24dc2..175236df 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/ContentCode.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/ContentCode.java @@ -30,7 +30,7 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; * */ public interface ContentCode extends Code { - public String[] idattrs(); - public void addAttr(boolean first, String attr); - public boolean no_cache(); + public String[] idattrs(); + public void addAttr(boolean first, String attr); + public boolean no_cache(); } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Controls.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Controls.java index 5b582f38..76cb18ac 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Controls.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Controls.java @@ -28,18 +28,18 @@ import org.onap.aaf.misc.xgen.Cache; import org.onap.aaf.misc.xgen.html.HTMLGen; public class Controls extends NamedCode { - public Controls() { - super(false,"controls"); - } - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - hgen.incr("form","method=post") - .incr("input", true, "type=checkbox", "name=vehicle", "value=Bike").text("I have a bike").end() - .text("Password: ") - .incr("input", true, "type=password", "id=password1").end() - .tagOnly("input", "type=submit", "value=Submit") - .end(); - } + public Controls() { + super(false,"controls"); + } + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + hgen.incr("form","method=post") + .incr("input", true, "type=checkbox", "name=vehicle", "value=Bike").text("I have a bike").end() + .text("Password: ") + .incr("input", true, "type=password", "id=password1").end() + .tagOnly("input", "type=submit", "value=Submit") + .end(); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java index ad43d3fb..d1817531 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java @@ -32,109 +32,109 @@ import org.onap.aaf.auth.rserv.HttpMethods; import org.onap.aaf.misc.env.Slot; public class Display { - private final Page get; - public Display(final AAF_GUI gui, final HttpMethods meth, final Page page) { - get = page; - final String[] fields = page.fields(); - final Slot slots[] = new Slot[fields.length]; - String prefix = page.name() + '.'; - for(int i=0;i(gui,page.name()) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - trans.put(gui.slot_httpServletRequest, req); - for(int i=0; i" corresponding to an array of types - String field=fields[i].substring(0, idx)+'.'; - String[] array = new String[16]; - for(Enumeration names = req.getParameterNames(); names.hasMoreElements();) { - String key = names.nextElement(); - if(key.startsWith(field)) { - try { - int x = Integer.parseInt(key.substring(field.length())); - if(x>=array.length) { - String[] temp = new String[x+10]; - System.arraycopy(temp, 0, temp, 0, array.length); - array = temp; - } - array[x]=req.getParameter(key); - } catch (NumberFormatException e) { - trans.debug().log(e); - } - } - } - trans.put(slots[i], array); - } - } - page.replay(context,trans,resp.getOutputStream(),"general"); - } - }, "application/x-www-form-urlencoded","*/*"); + /* + * We handle all the "Form POST" calls here with a naming convention that allows us to create arrays from strings. + * + * On the HTTP side, elements concatenate their name with their Index number (if multiple). In this code, + * we turn such names into arrays with same index number. Then, we place them in the Transaction "Properties" so that + * it can be transferred to subclasses easily. + */ + if(meth.equals(HttpMethods.POST)) { + // Here, we'll expect FORM URL Encoded Data, which we need to get from the body + gui.route(gui.env, meth, page.url(), + new HttpCode(gui,page.name()) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + trans.put(gui.slot_httpServletRequest, req); + for(int i=0; i" corresponding to an array of types + String field=fields[i].substring(0, idx)+'.'; + String[] array = new String[16]; + for(Enumeration names = req.getParameterNames(); names.hasMoreElements();) { + String key = names.nextElement(); + if(key.startsWith(field)) { + try { + int x = Integer.parseInt(key.substring(field.length())); + if(x>=array.length) { + String[] temp = new String[x+10]; + System.arraycopy(temp, 0, temp, 0, array.length); + array = temp; + } + array[x]=req.getParameter(key); + } catch (NumberFormatException e) { + trans.debug().log(e); + } + } + } + trans.put(slots[i], array); + } + } + page.replay(context,trans,resp.getOutputStream(),"general"); + } + }, "application/x-www-form-urlencoded","*/*"); - } else { - // Transfer whether Page shouldn't be cached to local Final var. - final boolean no_cache = page.no_cache; - - gui.route(gui.env, meth, page.url(), - new HttpCode(gui,page.name()) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - trans.put(gui.slot_httpServletRequest, req); - for(int i=0; i mm = req.getParameterNames();mm.hasMoreElements();) { - String key = mm.nextElement(); - if(key.startsWith(field)) { - try { - int x = Integer.parseInt(key.substring(field.length())); - if(x>=array.length) { - String[] temp = new String[x+10]; - System.arraycopy(temp, 0, temp, 0, array.length); - array = temp; - } - array[x]=req.getParameter(key); - } catch (NumberFormatException e) { - trans.debug().log(e); - } - } - } - trans.put(slots[i], array); - } - } - page.replay(context,trans,resp.getOutputStream(),"general"); - } - - @Override - public boolean no_cache() { - return no_cache; - } - }, "text/html","*/*"); - } + } else { + // Transfer whether Page shouldn't be cached to local Final var. + final boolean no_cache = page.no_cache; + + gui.route(gui.env, meth, page.url(), + new HttpCode(gui,page.name()) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + trans.put(gui.slot_httpServletRequest, req); + for(int i=0; i mm = req.getParameterNames();mm.hasMoreElements();) { + String key = mm.nextElement(); + if(key.startsWith(field)) { + try { + int x = Integer.parseInt(key.substring(field.length())); + if(x>=array.length) { + String[] temp = new String[x+10]; + System.arraycopy(temp, 0, temp, 0, array.length); + array = temp; + } + array[x]=req.getParameter(key); + } catch (NumberFormatException e) { + trans.debug().log(e); + } + } + } + trans.put(slots[i], array); + } + } + page.replay(context,trans,resp.getOutputStream(),"general"); + } + + @Override + public boolean no_cache() { + return no_cache; + } + }, "text/html","*/*"); + } - } - - public Page page() { - return get; - } + } + + public Page page() { + return get; + } } \ No newline at end of file diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java index 7011395c..cc51983b 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java @@ -28,41 +28,41 @@ import org.onap.aaf.misc.xgen.Cache; import org.onap.aaf.misc.xgen.html.HTMLGen; public class Form extends NamedCode { - private String preamble; - private NamedCode content; - - public Form(boolean no_cache, NamedCode content) { - super(no_cache,content); - this.content = content; - preamble=null; - } - - public Form preamble(String preamble) { - this.preamble = preamble; - return this; - } - + private String preamble; + private NamedCode content; + + public Form(boolean no_cache, NamedCode content) { + super(no_cache,content); + this.content = content; + preamble=null; + } + + public Form preamble(String preamble) { + this.preamble = preamble; + return this; + } + - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - if(preamble!=null) { - hgen.incr("p","class=preamble").text(preamble).end(); - } - hgen.incr("form","method=post"); - - content.code(cache, hgen); - - hgen.tagOnly("input", "type=submit", "value=Submit") - .tagOnly("input", "type=reset", "value=Reset") - .end(); - } + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + if(preamble!=null) { + hgen.incr("p","class=preamble").text(preamble).end(); + } + hgen.incr("form","method=post"); + + content.code(cache, hgen); + + hgen.tagOnly("input", "type=submit", "value=Submit") + .tagOnly("input", "type=reset", "value=Reset") + .end(); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.gui.NamedCode#idattrs() - */ - @Override - public String[] idattrs() { - return content.idattrs(); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.gui.NamedCode#idattrs() + */ + @Override + public String[] idattrs() { + return content.idattrs(); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java index e4bd6c7d..37576008 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java @@ -22,46 +22,46 @@ package org.onap.aaf.auth.gui; public abstract class NamedCode implements ContentCode { - private final boolean no_cache; - private String name; - private String[] idattrs; - - /* - * Mark whether this code should not be cached, and any attributes - */ - public NamedCode(final boolean no_cache, final String name) { - this.name = name; - idattrs = new String[] {name}; - this.no_cache = no_cache; - } - - public NamedCode(boolean no_cache, NamedCode content) { - this.no_cache = no_cache; - name=content.name; - idattrs = content.idattrs; - } + private final boolean no_cache; + private String name; + private String[] idattrs; + + /* + * Mark whether this code should not be cached, and any attributes + */ + public NamedCode(final boolean no_cache, final String name) { + this.name = name; + idattrs = new String[] {name}; + this.no_cache = no_cache; + } + + public NamedCode(boolean no_cache, NamedCode content) { + this.no_cache = no_cache; + name=content.name; + idattrs = content.idattrs; + } - /** - * Return ID and Any Attributes needed to create a "div" section of this code - * @return - */ - public String[] idattrs() { - return idattrs; - } - - public void addAttr(boolean first, String attr) { - String[] temp = new String[idattrs.length+1]; - if(first) { - temp[0] = attr; - System.arraycopy(idattrs, 0, temp, 1, idattrs.length); - } else { - temp[idattrs.length] = attr; - System.arraycopy(idattrs, 0, temp, 0, idattrs.length); - } - idattrs = temp; - } + /** + * Return ID and Any Attributes needed to create a "div" section of this code + * @return + */ + public String[] idattrs() { + return idattrs; + } + + public void addAttr(boolean first, String attr) { + String[] temp = new String[idattrs.length+1]; + if(first) { + temp[0] = attr; + System.arraycopy(idattrs, 0, temp, 1, idattrs.length); + } else { + temp[idattrs.length] = attr; + System.arraycopy(idattrs, 0, temp, 0, idattrs.length); + } + idattrs = temp; + } - public boolean no_cache() { - return no_cache; - } + public boolean no_cache() { + return no_cache; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java index 52673431..6010dd8b 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java @@ -40,40 +40,40 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.principal.TaggedPrincipal; public class OrgLookupFilter implements Filter { - - @Override - public void init(FilterConfig arg0) throws ServletException { - } + + @Override + public void init(FilterConfig arg0) throws ServletException { + } - @Override - public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { - final AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); - if(req instanceof HttpServletRequest) { - Principal p = ((HttpServletRequest)req).getUserPrincipal(); - if(p instanceof TaggedPrincipal) { - ((TaggedPrincipal)p).setTagLookup(new TaggedPrincipal.TagLookup() { - @Override - public String lookup() throws CadiException { - Identity id; - try { - id = trans.org().getIdentity(trans, p.getName()); - if(id!=null && id.isFound()) { - return id.firstName(); - } - } catch (OrganizationException e) { - throw new CadiException(e); - } - return p.getName(); - } - }); - } - fc.doFilter(req, resp); - } - - } + @Override + public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { + final AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); + if(req instanceof HttpServletRequest) { + Principal p = ((HttpServletRequest)req).getUserPrincipal(); + if(p instanceof TaggedPrincipal) { + ((TaggedPrincipal)p).setTagLookup(new TaggedPrincipal.TagLookup() { + @Override + public String lookup() throws CadiException { + Identity id; + try { + id = trans.org().getIdentity(trans, p.getName()); + if(id!=null && id.isFound()) { + return id.firstName(); + } + } catch (OrganizationException e) { + throw new CadiException(e); + } + return p.getName(); + } + }); + } + fc.doFilter(req, resp); + } + + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java index eb34a62c..a44a4846 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java @@ -61,342 +61,342 @@ import org.onap.aaf.misc.xgen.html.Imports; * */ public class Page extends HTMLCacheGen { - public static final String AAFURL_TOOLS = "aaf_url.tools"; - public static final String AAF_URL_TOOL_DOT = "aaf_url.tool."; - public static final String AAF_URL_CUIGUI = "aaf_url.cuigui"; // link to help - public static final String AAF_URL_GUI_ONBOARD = "aaf_url.gui_onboard"; - public static final String AAF_URL_AAF_HELP = "aaf_url.aaf_help"; - public static final String AAF_URL_CADI_HELP = "aaf_url.cadi_help"; - public static final String PERM_CA_TYPE = "certman"; - public static final String PERM_NS = Define.ROOT_NS(); + public static final String AAFURL_TOOLS = "aaf_url.tools"; + public static final String AAF_URL_TOOL_DOT = "aaf_url.tool."; + public static final String AAF_URL_CUIGUI = "aaf_url.cuigui"; // link to help + public static final String AAF_URL_GUI_ONBOARD = "aaf_url.gui_onboard"; + public static final String AAF_URL_AAF_HELP = "aaf_url.aaf_help"; + public static final String AAF_URL_CADI_HELP = "aaf_url.cadi_help"; + public static final String PERM_CA_TYPE = "certman"; + public static final String PERM_NS = Define.ROOT_NS(); - public static enum BROWSER {iPhone,html5,ie,ieOld}; - - public static final int MAX_LINE=20; + public static enum BROWSER {iPhone,html5,ie,ieOld}; + + public static final int MAX_LINE=20; - protected static final String[] NO_FIELDS = new String[0]; + protected static final String[] NO_FIELDS = new String[0]; - private static final String BROWSER_TYPE = "BROWSER_TYPE"; + private static final String BROWSER_TYPE = "BROWSER_TYPE"; - private final String bcName, bcUrl; - private final String[] fields; + private final String bcName, bcUrl; + private final String[] fields; - public final boolean no_cache; + public final boolean no_cache; - // Note: Only access is synchronized in "getPerm" - private final static Map> perms = new HashMap<>(); + // Note: Only access is synchronized in "getPerm" + private final static Map> perms = new HashMap<>(); - public String name() { - return bcName; - } - - public String url() { - return bcUrl; - } - - public String[] fields() { - return fields; - } - - public Page(AuthzEnv env, String name, String url, Enum[] en, final NamedCode ...content) throws APIException, IOException { - super(CacheGen.PRETTY, new PageCode(env, 1, content)); - fields = new String[en.length]; - int i=-1; - for(Enum p : en) { - fields[++i]=p.name(); - } + public String name() { + return bcName; + } + + public String url() { + return bcUrl; + } + + public String[] fields() { + return fields; + } + + public Page(AuthzEnv env, String name, String url, Enum[] en, final NamedCode ...content) throws APIException, IOException { + super(CacheGen.PRETTY, new PageCode(env, 1, content)); + fields = new String[en.length]; + int i=-1; + for(Enum p : en) { + fields[++i]=p.name(); + } - bcName = name; - bcUrl = url; - // Mark which fields must be "no_cache" - boolean no_cacheTemp=false; - for(NamedCode nc : content) { - if(nc.no_cache()) { - no_cacheTemp=true; - break; - } - } - no_cache=no_cacheTemp; - } - public Page(AuthzEnv env, String name, String url, String [] fields, final NamedCode ... content) throws APIException,IOException { - this(env,name,url,1,fields,content); - } - - public Page(AuthzEnv env, String name, String url, int backdots, String [] fields, final NamedCode ... content) throws APIException,IOException { - super(CacheGen.PRETTY, new PageCode(env, backdots, content)); - if(fields==null) { - this.fields = new String[0]; - } else { - this.fields = fields; - } - bcName = name; - bcUrl = url; - // Mark which fields must be "no_cache" - boolean no_cacheTemp=false; - for(NamedCode nc : content) { - if(nc.no_cache()) { - no_cacheTemp=true; - break; - } - } - no_cache=no_cacheTemp; - } - - - private static class PageCode implements Code { - private static final String AAF_GUI_TITLE = "aaf_gui_title"; - - private final ContentCode[] content; - private final Slot browserSlot; - private final int backdots; - protected AuthzEnv env; - private StaticSlot sTheme; + bcName = name; + bcUrl = url; + // Mark which fields must be "no_cache" + boolean no_cacheTemp=false; + for(NamedCode nc : content) { + if(nc.no_cache()) { + no_cacheTemp=true; + break; + } + } + no_cache=no_cacheTemp; + } + public Page(AuthzEnv env, String name, String url, String [] fields, final NamedCode ... content) throws APIException,IOException { + this(env,name,url,1,fields,content); + } + + public Page(AuthzEnv env, String name, String url, int backdots, String [] fields, final NamedCode ... content) throws APIException,IOException { + super(CacheGen.PRETTY, new PageCode(env, backdots, content)); + if(fields==null) { + this.fields = new String[0]; + } else { + this.fields = fields; + } + bcName = name; + bcUrl = url; + // Mark which fields must be "no_cache" + boolean no_cacheTemp=false; + for(NamedCode nc : content) { + if(nc.no_cache()) { + no_cacheTemp=true; + break; + } + } + no_cache=no_cacheTemp; + } + + + private static class PageCode implements Code { + private static final String AAF_GUI_TITLE = "aaf_gui_title"; + + private final ContentCode[] content; + private final Slot browserSlot; + private final int backdots; + protected AuthzEnv env; + private StaticSlot sTheme; - public PageCode(AuthzEnv env, int backdots, final ContentCode[] content) { - this.content = content; - this.backdots = backdots; - browserSlot = env.slot(BROWSER_TYPE); - sTheme = env.staticSlot(CachingFileAccess.CFA_WEB_PATH); - this.env = env; - } - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - // Note: I found that App Storage saves everything about the page, or not. Thus, if you declare the page uncacheable, none of the - // Artifacts, like JPGs are stored, which makes this feature useless for Server driven elements - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - switch(browser(trans,browserSlot)) { - case ieOld: - case ie: - hgen.directive("!DOCTYPE html"); - hgen.directive("meta", "http-equiv=X-UA-Compatible","content=IE=11"); - default: - } - } - }); - hgen.html(); - final String title = env.getProperty(AAF_GUI_TITLE,"Authentication/Authorization Framework"); - final String theme = env.get(sTheme); - Mark head = hgen.head(); - hgen.leaf(TITLE).text(title).end(); - hgen.imports(new Imports(backdots).css(theme + "/aaf5.css") - .js(theme + "/comm.js") - .js(theme + "/console.js") - .js(theme + "/common.js")); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - switch(browser(trans,browserSlot)) { - case iPhone: - hgen.imports(new Imports(backdots).css(theme + "/aaf5iPhone.css")); - break; - case ie: - case ieOld: - hgen.js().text("document.createElement('header');") - .text("document.createElement('nav');") - .done(); - case html5: - hgen.imports(new Imports(backdots).css(theme + "/aaf5Desktop.css")); - break; - } - } - }); - hgen.end(head); - - Mark body = hgen.body(); - Mark header = hgen.header(); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI state, AuthzTrans trans,Cache cache, HTMLGen xgen) - throws APIException, IOException { - // Obtain Server Info, and print - // AT&T Only - String env = trans.getProperty(Config.AAF_ENV,"N/A"); - xgen.leaf(H1).text(title + " on " + env).end(); - xgen.leaf("p","id=version").text("AAF Version: " + state.deployedVersion).end(); - - // Obtain User Info, and print - TaggedPrincipal p = trans.getUserPrincipal(); - String user,secured; - if(p==null) { - user = "please choose a Login Authority"; - secured = "NOT Secure!"; - } else { - user = p.personalName(); - secured = p.tag(); - } - xgen.leaf("p","id=welcome").text("Welcome, ") - .text(user) - .text("") - .text(secured) - .text("").end(); - - switch(browser(trans,browserSlot)) { - case ieOld: - case ie: - xgen.incr("h5").text("This app is Mobile First HTML5. Internet Explorer " - + " does not support all HTML5 standards. Old, non TSS-Standard versions may not function correctly.").br() - .text(" For best results, use a highly compliant HTML5 browser like Firefox.") - .end(); - break; - default: - } - } - }); - - hgen.hr(); - - int cIdx; - ContentCode nc; - // If BreadCrumbs, put here - if(content.length>0 && content[0] instanceof BreadCrumbs) { - nc = content[0]; - Mark ctnt = hgen.divID(nc.idattrs()); - nc.code(cache, hgen); - hgen.end(ctnt); - cIdx = 1; - } else { - cIdx = 0; - } - - hgen.end(header); - - Mark inner = hgen.divID("inner"); - // Content - for(int i=cIdx;i cache, final HTMLGen hgen) throws APIException, IOException { + // Note: I found that App Storage saves everything about the page, or not. Thus, if you declare the page uncacheable, none of the + // Artifacts, like JPGs are stored, which makes this feature useless for Server driven elements + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + switch(browser(trans,browserSlot)) { + case ieOld: + case ie: + hgen.directive("!DOCTYPE html"); + hgen.directive("meta", "http-equiv=X-UA-Compatible","content=IE=11"); + default: + } + } + }); + hgen.html(); + final String title = env.getProperty(AAF_GUI_TITLE,"Authentication/Authorization Framework"); + final String theme = env.get(sTheme); + Mark head = hgen.head(); + hgen.leaf(TITLE).text(title).end(); + hgen.imports(new Imports(backdots).css(theme + "/aaf5.css") + .js(theme + "/comm.js") + .js(theme + "/console.js") + .js(theme + "/common.js")); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + switch(browser(trans,browserSlot)) { + case iPhone: + hgen.imports(new Imports(backdots).css(theme + "/aaf5iPhone.css")); + break; + case ie: + case ieOld: + hgen.js().text("document.createElement('header');") + .text("document.createElement('nav');") + .done(); + case html5: + hgen.imports(new Imports(backdots).css(theme + "/aaf5Desktop.css")); + break; + } + } + }); + hgen.end(head); + + Mark body = hgen.body(); + Mark header = hgen.header(); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI state, AuthzTrans trans,Cache cache, HTMLGen xgen) + throws APIException, IOException { + // Obtain Server Info, and print + // AT&T Only + String env = trans.getProperty(Config.AAF_ENV,"N/A"); + xgen.leaf(H1).text(title + " on " + env).end(); + xgen.leaf("p","id=version").text("AAF Version: " + state.deployedVersion).end(); + + // Obtain User Info, and print + TaggedPrincipal p = trans.getUserPrincipal(); + String user,secured; + if(p==null) { + user = "please choose a Login Authority"; + secured = "NOT Secure!"; + } else { + user = p.personalName(); + secured = p.tag(); + } + xgen.leaf("p","id=welcome").text("Welcome, ") + .text(user) + .text("") + .text(secured) + .text("").end(); + + switch(browser(trans,browserSlot)) { + case ieOld: + case ie: + xgen.incr("h5").text("This app is Mobile First HTML5. Internet Explorer " + + " does not support all HTML5 standards. Old, non TSS-Standard versions may not function correctly.").br() + .text(" For best results, use a highly compliant HTML5 browser like Firefox.") + .end(); + break; + default: + } + } + }); + + hgen.hr(); + + int cIdx; + ContentCode nc; + // If BreadCrumbs, put here + if(content.length>0 && content[0] instanceof BreadCrumbs) { + nc = content[0]; + Mark ctnt = hgen.divID(nc.idattrs()); + nc.code(cache, hgen); + hgen.end(ctnt); + cIdx = 1; + } else { + cIdx = 0; + } + + hgen.end(header); + + Mark inner = hgen.divID("inner"); + // Content + for(int i=cIdx;i=0 - * - * Use int found in "ieVersion" - * - * Official IE 7 - * Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; - * .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) - * Official IE 8 - * Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; - * .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; ATT) - * - * IE 11 Compatibility - * Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; - * .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; InfoPath.3; HVD; ATT) - * - * IE 11 (not Compatiblity) - * Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; - * .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; InfoPath.3; HVD; ATT) - * - * @param trans - * @return - */ - public static BROWSER browser(AuthzTrans trans, Slot slot) { - BROWSER br = trans.get(slot, null); - if(br==null) { - String agent = trans.agent(); - int msie; - if(agent.contains("iPhone") /* other phones? */) { - br=BROWSER.iPhone; - } else if ((msie = agent.indexOf("MSIE"))>=0) { - msie+=5; - int end = agent.indexOf(";",msie); - float ver; - try { - ver = Float.valueOf(agent.substring(msie,end)); - br = ver<8f?BROWSER.ieOld:BROWSER.ie; - } catch (Exception e) { - br = BROWSER.ie; - } - } else { - br = BROWSER.html5; - } - trans.put(slot,br); - } - return br; - } - - /* - * Get, rather than create each time, permissions for validations - */ - protected static synchronized Permission getPerm(String instance, String action) { - Map msp = perms.get(instance); - Permission p; - if(msp==null) { - msp = new HashMap<>(); - perms.put(instance, msp); - p=null; - } else { - p = msp.get(instance); - } - if(p==null) { - p=new AAFPermission(PERM_NS, PERM_CA_TYPE,instance,action); - msp.put(action, p); - } - return p; - } + public static String getBrowserType() { + return BROWSER_TYPE; + } + + /** + * It's IE if int >=0 + * + * Use int found in "ieVersion" + * + * Official IE 7 + * Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; + * .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) + * Official IE 8 + * Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; + * .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; ATT) + * + * IE 11 Compatibility + * Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; + * .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; InfoPath.3; HVD; ATT) + * + * IE 11 (not Compatiblity) + * Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; + * .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; InfoPath.3; HVD; ATT) + * + * @param trans + * @return + */ + public static BROWSER browser(AuthzTrans trans, Slot slot) { + BROWSER br = trans.get(slot, null); + if(br==null) { + String agent = trans.agent(); + int msie; + if(agent.contains("iPhone") /* other phones? */) { + br=BROWSER.iPhone; + } else if ((msie = agent.indexOf("MSIE"))>=0) { + msie+=5; + int end = agent.indexOf(";",msie); + float ver; + try { + ver = Float.valueOf(agent.substring(msie,end)); + br = ver<8f?BROWSER.ieOld:BROWSER.ie; + } catch (Exception e) { + br = BROWSER.ie; + } + } else { + br = BROWSER.html5; + } + trans.put(slot,br); + } + return br; + } + + /* + * Get, rather than create each time, permissions for validations + */ + protected static synchronized Permission getPerm(String instance, String action) { + Map msp = perms.get(instance); + Permission p; + if(msp==null) { + msp = new HashMap<>(); + perms.put(instance, msp); + p=null; + } else { + p = msp.get(instance); + } + if(p==null) { + p=new AAFPermission(PERM_NS, PERM_CA_TYPE,instance,action); + msp.put(action, p); + } + return p; + } - protected static String getSingleParam(HttpServletRequest req, String tag) { - String values[] = req.getParameterValues(tag); - return values.length<1?null:values[0]; - } + protected static String getSingleParam(HttpServletRequest req, String tag) { + String values[] = req.getParameterValues(tag); + return values.length<1?null:values[0]; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java index b457fc9b..844270ed 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java @@ -26,24 +26,24 @@ import org.onap.aaf.misc.env.Slot; import org.onap.aaf.misc.env.TransStore; public abstract class SlotCode extends NamedCode { - private Slot[] slots; + private Slot[] slots; - public SlotCode(boolean no_cache,EnvStore env, String root, Enum ... params) { - super(no_cache,root); - slots = new Slot[params.length]; - for(int i=0;i env, String root, Enum ... params) { + super(no_cache,root); + slots = new Slot[params.length]; + for(int i=0;i T get(TRANS trans,Enum en, T dflt) { - return get(trans,en.ordinal(),dflt); - } - - public T get(TRANS trans,int idx, T dflt) { - if(idx>slots.length) { - return dflt; - } - return trans.get(slots[idx],dflt); - } + public T get(TRANS trans,Enum en, T dflt) { + return get(trans,en.ordinal(),dflt); + } + + public T get(TRANS trans,int idx, T dflt) { + if(idx>slots.length) { + return dflt; + } + return trans.get(slots[idx],dflt); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java index 6839a9ab..079593c9 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java @@ -42,188 +42,188 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; import org.onap.aaf.misc.xgen.html.State; public class Table, TRANS extends TransStore> extends NamedCode { - private final Slot ROW_MSG_SLOT, EMPTY_TABLE_SLOT; - private final String title; - private final String[] columns; - private final Rows rows; - private Code other; -// private DynamicCode prefix,postfix; + private final Slot ROW_MSG_SLOT, EMPTY_TABLE_SLOT; + private final String title; + private final String[] columns; + private final Rows rows; + private Code other; +// private DynamicCode prefix,postfix; - public Table(String title, TRANS trans, Data data, Code other, String name, String ... attrs) { - this(title,trans,data,name, attrs); - this.other = other; - } - - public Table(String title, TRANS trans, Data data, String name, String ... attrs) { - super(true,name); -// prefix=postfix=null; - for(String a : attrs) { - addAttr(false, a); - } - ROW_MSG_SLOT=trans.slot("TABLE_ROW_MSG"); - EMPTY_TABLE_SLOT=trans.slot("TABLE_EMPTY"); - this.columns = data.headers(); - boolean alt = false; - for(String s : attrs) { - if("class=std".equals(s) || "class=stdform".equals(s)) { - alt=true; - } - } - rows = new Rows(data,alt?1:0); - this.title = title; - // Derive an ID from title (from no spaces, etc), and prepend to IDAttributes (Protected from NamedCode) - addAttr(true,title(trans).replaceAll("\\s","")); - - other = null; - } + public Table(String title, TRANS trans, Data data, Code other, String name, String ... attrs) { + this(title,trans,data,name, attrs); + this.other = other; + } + + public Table(String title, TRANS trans, Data data, String name, String ... attrs) { + super(true,name); +// prefix=postfix=null; + for(String a : attrs) { + addAttr(false, a); + } + ROW_MSG_SLOT=trans.slot("TABLE_ROW_MSG"); + EMPTY_TABLE_SLOT=trans.slot("TABLE_EMPTY"); + this.columns = data.headers(); + boolean alt = false; + for(String s : attrs) { + if("class=std".equals(s) || "class=stdform".equals(s)) { + alt=true; + } + } + rows = new Rows(data,alt?1:0); + this.title = title; + // Derive an ID from title (from no spaces, etc), and prepend to IDAttributes (Protected from NamedCode) + addAttr(true,title(trans).replaceAll("\\s","")); + + other = null; + } - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(S state, TRANS trans, Cache cache, HTMLGen xgen) throws APIException, IOException { - rows.data.prefix(state, trans, cache, xgen); - } - }); - Mark table = new Mark(); - Mark tr = new Mark(); - - hgen.incr(table,TABLE); - if(title==null) { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(S state, TRANS trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - hgen.leaf("caption", "class=title").text(title(trans)).end(); - } - }); - } else { - hgen.leaf("caption", "class=title").text(title).end(); - } - hgen.incr(tr,TR); - for(String column : columns) { - hgen.leaf("th").text(column).end(); - } - hgen.end(tr); - - // Load Rows Dynamically - cache.dynamic(hgen, rows); - // End Table - hgen.end(table); - - if(other!=null) { - other.code(cache,hgen); - } - - // Print Message from Row Gathering, if available - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(S state, TRANS trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String msg; - if((msg = trans.get(EMPTY_TABLE_SLOT, null))!=null) { - hgen.incr("style").text("#inner tr,caption,input,p.preamble {display: none;}#inner p.notfound {margin: 0px 0px 0px 20px}").end(); - hgen.incr(HTMLGen.P,"class=notfound").text(msg).end().br(); - } else if((msg=trans.get(ROW_MSG_SLOT,null))!=null) { - hgen.p(msg).br(); - } - } - }); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(S state, TRANS trans, Cache cache, HTMLGen xgen) throws APIException, IOException { - rows.data.postfix(state, trans, cache, xgen); - } - }); + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(S state, TRANS trans, Cache cache, HTMLGen xgen) throws APIException, IOException { + rows.data.prefix(state, trans, cache, xgen); + } + }); + Mark table = new Mark(); + Mark tr = new Mark(); + + hgen.incr(table,TABLE); + if(title==null) { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(S state, TRANS trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + hgen.leaf("caption", "class=title").text(title(trans)).end(); + } + }); + } else { + hgen.leaf("caption", "class=title").text(title).end(); + } + hgen.incr(tr,TR); + for(String column : columns) { + hgen.leaf("th").text(column).end(); + } + hgen.end(tr); + + // Load Rows Dynamically + cache.dynamic(hgen, rows); + // End Table + hgen.end(table); + + if(other!=null) { + other.code(cache,hgen); + } + + // Print Message from Row Gathering, if available + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(S state, TRANS trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String msg; + if((msg = trans.get(EMPTY_TABLE_SLOT, null))!=null) { + hgen.incr("style").text("#inner tr,caption,input,p.preamble {display: none;}#inner p.notfound {margin: 0px 0px 0px 20px}").end(); + hgen.incr(HTMLGen.P,"class=notfound").text(msg).end().br(); + } else if((msg=trans.get(ROW_MSG_SLOT,null))!=null) { + hgen.p(msg).br(); + } + } + }); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(S state, TRANS trans, Cache cache, HTMLGen xgen) throws APIException, IOException { + rows.data.postfix(state, trans, cache, xgen); + } + }); - } + } - protected String title(TRANS trans) { - return title; - } + protected String title(TRANS trans) { + return title; + } - public static class Cells { - public static final Cells EMPTY = new Cells(); - private Cells() { - cells = new AbsCell[0][0]; - msg = "No Data Found"; - } - - public Cells(ArrayList arrayCells, String msg) { - cells = new AbsCell[arrayCells.size()][]; - arrayCells.toArray(cells); - this.msg = msg; - } - public AbsCell[][] cells; - public String msg; - - } - - public interface Data, TRANS extends Trans> { - // Note: Trans is not first to avoid Method Name Collision - public void prefix(S state, TRANS trans, final Cache cache, final HTMLGen hgen); - public Cells get(TRANS trans,S state); - public void postfix(S state, TRANS trans, final Cache cache, final HTMLGen hgen); - public String[] headers(); - } + public static class Cells { + public static final Cells EMPTY = new Cells(); + private Cells() { + cells = new AbsCell[0][0]; + msg = "No Data Found"; + } + + public Cells(ArrayList arrayCells, String msg) { + cells = new AbsCell[arrayCells.size()][]; + arrayCells.toArray(cells); + this.msg = msg; + } + public AbsCell[][] cells; + public String msg; + + } + + public interface Data, TRANS extends Trans> { + // Note: Trans is not first to avoid Method Name Collision + public void prefix(S state, TRANS trans, final Cache cache, final HTMLGen hgen); + public Cells get(TRANS trans,S state); + public void postfix(S state, TRANS trans, final Cache cache, final HTMLGen hgen); + public String[] headers(); + } - private class Rows extends DynamicCode { - private Data data; - private int alt; - - public Rows(Data data, int alt) { - this.data = data; - this.alt = alt; - } - - @Override - public void code(final S state, final TRANS trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - Mark tr = new Mark(); - Mark td = new Mark(); - - int alt = this.alt; - Cells cells = data.get(trans,state); - if(cells.cells.length>0) { - for(AbsCell[] row : cells.cells) { - if(row.length==0) { - hgen.text("") - .hr() - .text(""); - } else { - switch(alt) { - case 1: - alt=2; - case 0: - hgen.incr(tr,TR); - break; - default: - alt=1; - hgen.incr(tr,TR,"class=alt"); - } - for(AbsCell cell :row) { - hgen.leaf(td, TD,cell.attrs()); - cell.write(hgen); - hgen.end(td); - } - hgen.end(tr); - } - } - // Pass Msg back to Table code, in order to place after Table Complete - if(cells.msg!=null) { - trans.put(ROW_MSG_SLOT,cells.msg); - } - } else { - trans.put(EMPTY_TABLE_SLOT,cells.msg); - } - } - } + private class Rows extends DynamicCode { + private Data data; + private int alt; + + public Rows(Data data, int alt) { + this.data = data; + this.alt = alt; + } + + @Override + public void code(final S state, final TRANS trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + Mark tr = new Mark(); + Mark td = new Mark(); + + int alt = this.alt; + Cells cells = data.get(trans,state); + if(cells.cells.length>0) { + for(AbsCell[] row : cells.cells) { + if(row.length==0) { + hgen.text("
    ") + .hr() + .text(""); + } else { + switch(alt) { + case 1: + alt=2; + case 0: + hgen.incr(tr,TR); + break; + default: + alt=1; + hgen.incr(tr,TR,"class=alt"); + } + for(AbsCell cell :row) { + hgen.leaf(td, TD,cell.attrs()); + cell.write(hgen); + hgen.end(td); + } + hgen.end(tr); + } + } + // Pass Msg back to Table code, in order to place after Table Complete + if(cells.msg!=null) { + trans.put(ROW_MSG_SLOT,cells.msg); + } + } else { + trans.put(EMPTY_TABLE_SLOT,cells.msg); + } + } + } -// public Table setPrefix(DynamicCode dynamicCode) { -// prefix = dynamicCode; -// return this; -// } -// -// public Table setPostfix(DynamicCode dynamicCode) { -// postfix = dynamicCode; -// return this; -// } +// public Table setPrefix(DynamicCode dynamicCode) { +// prefix = dynamicCode; +// return this; +// } +// +// public Table setPostfix(DynamicCode dynamicCode) { +// postfix = dynamicCode; +// return this; +// } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java index ae71d5bf..f362418e 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java @@ -31,43 +31,43 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class XFrameFilter implements Filter { - enum TYPE {none,self}; - // Note: Content-Security Params need to be worked out for GUI before activating. - private final String xframe;//,csp; - - public XFrameFilter(TYPE type) { - switch(type) { - case self: - xframe="SAMEORIGIN"; -// csp="default-src 'self'"; - break; - case none: - default: - xframe="DENY"; -// csp="default-src 'none'"; - break; - - } - } - - @Override - public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { - if(resp instanceof HttpServletResponse) { - @SuppressWarnings("unused") - HttpServletResponse hresp = (HttpServletResponse)resp; - ((HttpServletResponse)resp).addHeader("X-Frame-Options", xframe); -// ((HttpServletResponse)resp).addHeader("Content-Security-Policy",csp); - } - fc.doFilter(req, resp); - } + enum TYPE {none,self}; + // Note: Content-Security Params need to be worked out for GUI before activating. + private final String xframe;//,csp; + + public XFrameFilter(TYPE type) { + switch(type) { + case self: + xframe="SAMEORIGIN"; +// csp="default-src 'self'"; + break; + case none: + default: + xframe="DENY"; +// csp="default-src 'none'"; + break; + + } + } + + @Override + public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { + if(resp instanceof HttpServletResponse) { + @SuppressWarnings("unused") + HttpServletResponse hresp = (HttpServletResponse)resp; + ((HttpServletResponse)resp).addHeader("X-Frame-Options", xframe); +// ((HttpServletResponse)resp).addHeader("Content-Security-Policy",csp); + } + fc.doFilter(req, resp); + } - @Override - public void init(FilterConfig fc) throws ServletException { - } + @Override + public void init(FilterConfig fc) throws ServletException { + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java index 95aa0525..235683d5 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java @@ -53,279 +53,279 @@ import aaf.v2_0.Api; import aaf.v2_0.Api.Route; public class ApiDocs extends Page { - // Package on purpose - private static final String HREF = "/gui/api"; - private static final String NAME = "AAF RESTful API"; - private static final String fields[] = {}; - private static final String ERROR_LINK = "JSON " - + "XML "; + // Package on purpose + private static final String HREF = "/gui/api"; + private static final String NAME = "AAF RESTful API"; + private static final String fields[] = {}; + private static final String ERROR_LINK = "JSON " + + "XML "; - - public ApiDocs(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, fields, - new BreadCrumbs(breadcrumbs), - new Preamble(gui), - new Table("AAF API Reference",gui.env.newTransNoAvg(),new Model(), "class=std") - ); - } - - private static class Preamble extends NamedCode { + + public ApiDocs(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, fields, + new BreadCrumbs(breadcrumbs), + new Preamble(gui), + new Table("AAF API Reference",gui.env.newTransNoAvg(),new Model(), "class=std") + ); + } + + private static class Preamble extends NamedCode { - private static final String I = "i"; - private final String fs_url; + private static final String I = "i"; + private final String fs_url; - public Preamble(AAF_GUI gui) { - super(false, "preamble"); - fs_url = gui.access.getProperty("fs_url", ""); - } + public Preamble(AAF_GUI gui) { + super(false, "preamble"); + fs_url = gui.access.getProperty("fs_url", ""); + } - @Override - public void code(Cache cache, HTMLGen xgen) throws APIException, IOException { - xgen.leaf(HTMLGen.H1).text("AAF 2.0 RESTful interface").end() - .hr(); - xgen.leaf(HTMLGen.H2).text("Accessing RESTful").end(); - xgen.incr(HTMLGen.UL) - .leaf(HTMLGen.LI).text("AAF RESTful service is secured by the following:").end() - .incr(HTMLGen.UL) - .leaf(HTMLGen.LI).text("The Client must utilize HTTP/S. Non Secure HTTP is not acceptable").end() - .leaf(HTMLGen.LI).text("The Client MUST supply an Identity validated by one of the following mechanisms").end() - .incr(HTMLGen.UL) - .leaf(HTMLGen.LI).text("BASIC AUTH protocol using Organization Registered AppID, provisioned in AAF").end() - .leaf(HTMLGen.LI).text("(Near Future) Application level Certificate").end() - .end() - .end() - .leaf(HTMLGen.LI).text("Responses").end() - .incr(HTMLGen.UL) - .leaf(HTMLGen.LI).text("Each API Entity listed shows what structure will be accepted by service (ContentType) " - + "or responded with by service (Accept). Therefore, use these in making your call. Critical for PUT/POST.").end() - .leaf(HTMLGen.LI).text("Each API call may respond with JSON or XML. Choose the ContentType/Accept that has " - + "+json after the type for JSON or +xml after the Type for XML").end() - .leaf(HTMLGen.LI).text("XSDs for Versions").end() - .incr(HTMLGen.UL) - .leaf(HTMLGen.LI).leaf(HTMLGen.A,"href=" + fs_url + "/aaf_2_0.xsd").text("API 2.0").end().end() - .end() - .leaf(HTMLGen.LI).text("AAF can support multiple Versions of the API. Choose the ContentType/Accept that has " - + "the appropriate version=?.?").end() - .leaf(HTMLGen.LI).text("All Errors coming from AAF return AT&T Standard Error Message as a String: " + ERROR_LINK - + " (does not apply to errors from Container)").end() - .end() - .leaf(HTMLGen.LI).text("Character Restrictions").end() - .incr(HTMLGen.UL) - .leaf(HTMLGen.LI).text("Character Restrictions must depend on the Enforcement Point used").end() - .leaf(HTMLGen.LI).text("Most AAF usage will be AAF Enforcement Point Characters for Instance and Action are:") - .br().br().leaf(I).text("a-zA-Z0-9,.()_-=%").end() - .br().br().text("For Instance, you may declare a multi-dimensional key with : (colon) separator, example:").end() - .br().leaf(I).text(":myCluster:myKeyspace").end() - .br().br().text("The * (asterix) may be used as a wild-card by itself or within the multi-dimensional key, example:") - .br().leaf(I).text(":myCluster:*").end() - .br().br().text("The % (percent) character can be used as an Escape Character. Applications can use % followed by 2 hexadecimal " - + "digits to cover odd keys. It is their code, however, which must translate.") - .br().br().text("The = (equals) is allowed so that Applications can pass Base64 encodations of binary keys").end() - .leaf(HTMLGen.LI).text("Ask for a Consultation on how these are typically used, or, if your tool is the only Enforcement Point, if set may be expanded").end() - .end() - .end(); - /* - - The Content is defined in the AAF XSD - TODO Add aaf.xsd”; - Character Restrictions + @Override + public void code(Cache cache, HTMLGen xgen) throws APIException, IOException { + xgen.leaf(HTMLGen.H1).text("AAF 2.0 RESTful interface").end() + .hr(); + xgen.leaf(HTMLGen.H2).text("Accessing RESTful").end(); + xgen.incr(HTMLGen.UL) + .leaf(HTMLGen.LI).text("AAF RESTful service is secured by the following:").end() + .incr(HTMLGen.UL) + .leaf(HTMLGen.LI).text("The Client must utilize HTTP/S. Non Secure HTTP is not acceptable").end() + .leaf(HTMLGen.LI).text("The Client MUST supply an Identity validated by one of the following mechanisms").end() + .incr(HTMLGen.UL) + .leaf(HTMLGen.LI).text("BASIC AUTH protocol using Organization Registered AppID, provisioned in AAF").end() + .leaf(HTMLGen.LI).text("(Near Future) Application level Certificate").end() + .end() + .end() + .leaf(HTMLGen.LI).text("Responses").end() + .incr(HTMLGen.UL) + .leaf(HTMLGen.LI).text("Each API Entity listed shows what structure will be accepted by service (ContentType) " + + "or responded with by service (Accept). Therefore, use these in making your call. Critical for PUT/POST.").end() + .leaf(HTMLGen.LI).text("Each API call may respond with JSON or XML. Choose the ContentType/Accept that has " + + "+json after the type for JSON or +xml after the Type for XML").end() + .leaf(HTMLGen.LI).text("XSDs for Versions").end() + .incr(HTMLGen.UL) + .leaf(HTMLGen.LI).leaf(HTMLGen.A,"href=" + fs_url + "/aaf_2_0.xsd").text("API 2.0").end().end() + .end() + .leaf(HTMLGen.LI).text("AAF can support multiple Versions of the API. Choose the ContentType/Accept that has " + + "the appropriate version=?.?").end() + .leaf(HTMLGen.LI).text("All Errors coming from AAF return AT&T Standard Error Message as a String: " + ERROR_LINK + + " (does not apply to errors from Container)").end() + .end() + .leaf(HTMLGen.LI).text("Character Restrictions").end() + .incr(HTMLGen.UL) + .leaf(HTMLGen.LI).text("Character Restrictions must depend on the Enforcement Point used").end() + .leaf(HTMLGen.LI).text("Most AAF usage will be AAF Enforcement Point Characters for Instance and Action are:") + .br().br().leaf(I).text("a-zA-Z0-9,.()_-=%").end() + .br().br().text("For Instance, you may declare a multi-dimensional key with : (colon) separator, example:").end() + .br().leaf(I).text(":myCluster:myKeyspace").end() + .br().br().text("The * (asterix) may be used as a wild-card by itself or within the multi-dimensional key, example:") + .br().leaf(I).text(":myCluster:*").end() + .br().br().text("The % (percent) character can be used as an Escape Character. Applications can use % followed by 2 hexadecimal " + + "digits to cover odd keys. It is their code, however, which must translate.") + .br().br().text("The = (equals) is allowed so that Applications can pass Base64 encodations of binary keys").end() + .leaf(HTMLGen.LI).text("Ask for a Consultation on how these are typically used, or, if your tool is the only Enforcement Point, if set may be expanded").end() + .end() + .end(); + /* + + The Content is defined in the AAF XSD - TODO Add aaf.xsd”; + Character Restrictions - URLs impose restrictions on characters which have specific meanings. This means you cannot have these characters in the Field Content you send - “#” is a “Fragment URL”, or anchor. Content after this Character is not sent. AAF cannot do anything about this… don’t use it. - “?=&”. These are used to delineate Parameters. - “/“ is used to separate fields - */ - } - - }; - /** - * Implement the Table Content for Permissions by User - * - * @author Jonathan - * - */ - private static class Model extends TableData { - public static final String[] HEADERS = new String[] {"Entity","Method","Path Info","Description"}; - private static final TextCell BLANK = new TextCell(""); - - @Override - public String[] headers() { - return HEADERS; - } - - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final ArrayList ns = new ArrayList<>(); - final ArrayList perms = new ArrayList<>(); - final ArrayList roles = new ArrayList<>(); - final ArrayList user = new ArrayList<>(); - final ArrayList aafOnly = new ArrayList<>(); - final ArrayList rv = new ArrayList<>(); - - - final TimeTaken tt = trans.start("AAF APIs",Env.REMOTE); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @SuppressWarnings("unchecked") - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fa = client.read("/api",gui.getDF(Api.class)); - if(fa.get(5000)) { - tt.done(); - TimeTaken tt2 = trans.start("Load Data", Env.SUB); - try { - if(fa.value!=null)for(Route r : fa.value.getRoute()) { - String path = r.getPath(); - // Build info - StringBuilder desc = new StringBuilder(); - - desc.append("

    "); - desc.append(r.getDesc()); - - if(r.getComments().size()>0) { - for(String ct : r.getComments()) { - desc.append("

    "); - desc.append(ct); - } - } - - if(r.getParam().size()>0) { - desc.append("


    Parameters

    "); - - for(String params : r.getParam()) { - String param[] = params.split("\\s*\\|\\s*"); - desc.append("

    "); - desc.append(param[0]); - desc.append(" : "); - desc.append(param[1]); - if("true".equalsIgnoreCase(param[2])) { - desc.append(" (Required)"); - } - } - } - - - if(r.getExpected()!=0) { - desc.append("

    Expected HTTP Code

    "); - desc.append(r.getExpected()); - } - - if(r.getExplicitErr().size()!=0) { - desc.append("

    Explicit HTTP Error Codes

    "); - boolean first = true; - for(int ee : r.getExplicitErr()) { - if(first) { - first = false; - } else { - desc.append(", "); - } - desc.append(ee); - } - } - - desc.append("

    "); - desc.append("GET".equals(r.getMeth())?"Accept:":"ContentType:"); - Collections.sort(r.getContentType()); - if(r.getPath().startsWith("/authn/basicAuth")) { - desc.append("

    text/plain"); - } - for(String ct : r.getContentType()) { - if(ct.contains("version=2")) { - desc.append("

    "); - desc.append(ct); - desc.append(""); - } - } - desc.append("

    "); - - - AbsCell[] sa = new AbsCell[] { - null, - new TextCell(r.getMeth(),"class=right"), - new TextCell(r.getPath()), - new TextCell(desc.toString()), - }; - - if(path.startsWith("/authz/perm")) { - sa[0] = perms.size()==0?new TextCell("PERMISSION"):BLANK; - perms.add(sa); - } else if(path.startsWith("/authz/role") || path.startsWith("/authz/userRole")) { - sa[0] = roles.size()==0?new TextCell("ROLE"):BLANK; - roles.add(sa); - } else if(path.startsWith("/authz/ns")) { - sa[0] = ns.size()==0?new TextCell("NAMESPACE"):BLANK; - ns.add(sa); - } else if(path.startsWith("/authn/basicAuth") - || path.startsWith("/authn/validate") - || path.startsWith("/authz/user")) { - sa[0] = user.size()==0?new TextCell("USER"):BLANK; - user.add(sa); - } else { - sa[0] = aafOnly.size()==0?new TextCell("AAF ONLY"):BLANK; - aafOnly.add(sa); - } - } - //TODO if(trans.fish(p)) - prepare(rv, perms,roles,ns,user); - } finally { - tt2.done(); - } - } else { - gui.writeError(trans, fa, null, 0); - } - return null; - } - }); - } catch (Exception e) { - trans.error().log(e.getMessage()); - } finally { - tt.done(); - } - - return new Cells(rv,null); - } + URLs impose restrictions on characters which have specific meanings. This means you cannot have these characters in the Field Content you send + “#” is a “Fragment URL”, or anchor. Content after this Character is not sent. AAF cannot do anything about this… don’t use it. + “?=&”. These are used to delineate Parameters. + “/“ is used to separate fields + */ + } + + }; + /** + * Implement the Table Content for Permissions by User + * + * @author Jonathan + * + */ + private static class Model extends TableData { + public static final String[] HEADERS = new String[] {"Entity","Method","Path Info","Description"}; + private static final TextCell BLANK = new TextCell(""); + + @Override + public String[] headers() { + return HEADERS; + } + + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final ArrayList ns = new ArrayList<>(); + final ArrayList perms = new ArrayList<>(); + final ArrayList roles = new ArrayList<>(); + final ArrayList user = new ArrayList<>(); + final ArrayList aafOnly = new ArrayList<>(); + final ArrayList rv = new ArrayList<>(); + + + final TimeTaken tt = trans.start("AAF APIs",Env.REMOTE); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @SuppressWarnings("unchecked") + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fa = client.read("/api",gui.getDF(Api.class)); + if(fa.get(5000)) { + tt.done(); + TimeTaken tt2 = trans.start("Load Data", Env.SUB); + try { + if(fa.value!=null)for(Route r : fa.value.getRoute()) { + String path = r.getPath(); + // Build info + StringBuilder desc = new StringBuilder(); + + desc.append("

    "); + desc.append(r.getDesc()); + + if(r.getComments().size()>0) { + for(String ct : r.getComments()) { + desc.append("

    "); + desc.append(ct); + } + } + + if(r.getParam().size()>0) { + desc.append("


    Parameters

    "); + + for(String params : r.getParam()) { + String param[] = params.split("\\s*\\|\\s*"); + desc.append("

    "); + desc.append(param[0]); + desc.append(" : "); + desc.append(param[1]); + if("true".equalsIgnoreCase(param[2])) { + desc.append(" (Required)"); + } + } + } + + + if(r.getExpected()!=0) { + desc.append("

    Expected HTTP Code

    "); + desc.append(r.getExpected()); + } + + if(r.getExplicitErr().size()!=0) { + desc.append("

    Explicit HTTP Error Codes

    "); + boolean first = true; + for(int ee : r.getExplicitErr()) { + if(first) { + first = false; + } else { + desc.append(", "); + } + desc.append(ee); + } + } + + desc.append("

    "); + desc.append("GET".equals(r.getMeth())?"Accept:":"ContentType:"); + Collections.sort(r.getContentType()); + if(r.getPath().startsWith("/authn/basicAuth")) { + desc.append("

    text/plain"); + } + for(String ct : r.getContentType()) { + if(ct.contains("version=2")) { + desc.append("

    "); + desc.append(ct); + desc.append(""); + } + } + desc.append("

    "); + + + AbsCell[] sa = new AbsCell[] { + null, + new TextCell(r.getMeth(),"class=right"), + new TextCell(r.getPath()), + new TextCell(desc.toString()), + }; + + if(path.startsWith("/authz/perm")) { + sa[0] = perms.size()==0?new TextCell("PERMISSION"):BLANK; + perms.add(sa); + } else if(path.startsWith("/authz/role") || path.startsWith("/authz/userRole")) { + sa[0] = roles.size()==0?new TextCell("ROLE"):BLANK; + roles.add(sa); + } else if(path.startsWith("/authz/ns")) { + sa[0] = ns.size()==0?new TextCell("NAMESPACE"):BLANK; + ns.add(sa); + } else if(path.startsWith("/authn/basicAuth") + || path.startsWith("/authn/validate") + || path.startsWith("/authz/user")) { + sa[0] = user.size()==0?new TextCell("USER"):BLANK; + user.add(sa); + } else { + sa[0] = aafOnly.size()==0?new TextCell("AAF ONLY"):BLANK; + aafOnly.add(sa); + } + } + //TODO if(trans.fish(p)) + prepare(rv, perms,roles,ns,user); + } finally { + tt2.done(); + } + } else { + gui.writeError(trans, fa, null, 0); + } + return null; + } + }); + } catch (Exception e) { + trans.error().log(e.getMessage()); + } finally { + tt.done(); + } + + return new Cells(rv,null); + } - @SuppressWarnings("unchecked") - private void prepare(ArrayList rv, ArrayList ... all) { - AbsCell lead; - AbsCell[] row; - for(ArrayList al : all) { - if(al.size()>1) { - row = al.get(0); - lead = row[0]; - row[0]=BLANK; - al.get(0).clone()[0]=BLANK; - Collections.sort(al, new Comparator() { - @Override - public int compare(AbsCell[] ca1, AbsCell[] ca2) { - int meth = ((TextCell)ca1[2]).name.compareTo( - ((TextCell)ca2[2]).name); - if(meth == 0) { - return (HttpMethods.valueOf(((TextCell)ca1[1]).name).compareTo( - HttpMethods.valueOf(((TextCell)ca2[1]).name))); - } else { - return meth; - } - } - }); - // set new first row - al.get(0)[0]=lead; + @SuppressWarnings("unchecked") + private void prepare(ArrayList rv, ArrayList ... all) { + AbsCell lead; + AbsCell[] row; + for(ArrayList al : all) { + if(al.size()>1) { + row = al.get(0); + lead = row[0]; + row[0]=BLANK; + al.get(0).clone()[0]=BLANK; + Collections.sort(al, new Comparator() { + @Override + public int compare(AbsCell[] ca1, AbsCell[] ca2) { + int meth = ((TextCell)ca1[2]).name.compareTo( + ((TextCell)ca2[2]).name); + if(meth == 0) { + return (HttpMethods.valueOf(((TextCell)ca1[1]).name).compareTo( + HttpMethods.valueOf(((TextCell)ca2[1]).name))); + } else { + return meth; + } + } + }); + // set new first row + al.get(0)[0]=lead; - rv.addAll(al); - } - } - } - } + rv.addAll(al); + } + } + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java index a98a16ca..3beed563 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java @@ -45,89 +45,89 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; * */ public class ApiExample extends Page { - public static final String HREF = "/gui/example/:tc"; - public static final String NAME = "APIExample"; + public static final String HREF = "/gui/example/:tc"; + public static final String NAME = "APIExample"; - public ApiExample(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME, HREF, 2/*backdots*/, new String[] {"API Code Example"}, - new BreadCrumbs(breadcrumbs), - new Model(NAME) - ); - } - - private static class Model extends NamedCode { - private static final String WITH_OPTIONAL_PARAMETERS = "\n\n////////////\n Data with Optional Parameters \n////////////\n\n"; + public ApiExample(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME, HREF, 2/*backdots*/, new String[] {"API Code Example"}, + new BreadCrumbs(breadcrumbs), + new Model(NAME) + ); + } + + private static class Model extends NamedCode { + private static final String WITH_OPTIONAL_PARAMETERS = "\n\n////////////\n Data with Optional Parameters \n////////////\n\n"; - public Model(String name) { - super(false,name); - } + public Model(String name) { + super(false,name); + } - @Override - public void code(Cache cache, HTMLGen xgen) throws APIException, IOException { - Mark inner = xgen.divID("inner"); - xgen.divID("example","class=std"); - cache.dynamic(xgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, Cache cache, HTMLGen xgen) throws APIException, IOException { - TimeTaken tt = trans.start("Code Example",Env.REMOTE); - try { - final String typecode; - int prefix = trans.path().lastIndexOf('/')+1; - String encoded = trans.path().substring(prefix); - typecode = Symm.base64noSplit.decode(encoded); - Future fp = gui.client().read("/api/example/" + encoded, - "application/Void+json" - ); - Future fs2; - if(typecode.contains("Request+")) { - fs2 = gui.client().read("/api/example/" + encoded+"?optional=true", - "application/Void+json" - ); - } else { - fs2=null; - } - - - if(fp.get(5000)) { - xgen.incr(HTMLGen.H1).text("Sample Code").end() - .incr(HTMLGen.H5).text(typecode).end(); - xgen.incr("pre"); - if(typecode.contains("+xml")) { - xgen.xml(fp.body()); - if(fs2!=null && fs2.get(5000)) { - xgen.text(WITH_OPTIONAL_PARAMETERS); - xgen.xml(fs2.body()); - } - } else { - xgen.text(fp.body()); - if(fs2!=null && fs2.get(5000)) { - xgen.text(WITH_OPTIONAL_PARAMETERS); - xgen.text(fs2.body()); - } - } - xgen.end(); - } else { - xgen.incr(HTMLGen.H3) - .textCR(2,"Error from AAF Service") - .end(); - gui.writeError(trans, fp, xgen, 0); - } + @Override + public void code(Cache cache, HTMLGen xgen) throws APIException, IOException { + Mark inner = xgen.divID("inner"); + xgen.divID("example","class=std"); + cache.dynamic(xgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, Cache cache, HTMLGen xgen) throws APIException, IOException { + TimeTaken tt = trans.start("Code Example",Env.REMOTE); + try { + final String typecode; + int prefix = trans.path().lastIndexOf('/')+1; + String encoded = trans.path().substring(prefix); + typecode = Symm.base64noSplit.decode(encoded); + Future fp = gui.client().read("/api/example/" + encoded, + "application/Void+json" + ); + Future fs2; + if(typecode.contains("Request+")) { + fs2 = gui.client().read("/api/example/" + encoded+"?optional=true", + "application/Void+json" + ); + } else { + fs2=null; + } + + + if(fp.get(5000)) { + xgen.incr(HTMLGen.H1).text("Sample Code").end() + .incr(HTMLGen.H5).text(typecode).end(); + xgen.incr("pre"); + if(typecode.contains("+xml")) { + xgen.xml(fp.body()); + if(fs2!=null && fs2.get(5000)) { + xgen.text(WITH_OPTIONAL_PARAMETERS); + xgen.xml(fs2.body()); + } + } else { + xgen.text(fp.body()); + if(fs2!=null && fs2.get(5000)) { + xgen.text(WITH_OPTIONAL_PARAMETERS); + xgen.text(fs2.body()); + } + } + xgen.end(); + } else { + xgen.incr(HTMLGen.H3) + .textCR(2,"Error from AAF Service") + .end(); + gui.writeError(trans, fp, xgen, 0); + } - } catch (APIException e) { - throw e; - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new APIException(e); - }finally { - tt.done(); - } - } - - }); - xgen.end(inner); - } - } + } catch (APIException e) { + throw e; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new APIException(e); + }finally { + tt.done(); + } + } + + }); + xgen.end(inner); + } + } -} - \ No newline at end of file +} + \ No newline at end of file diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java index 2797cd66..507cb21a 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java @@ -44,78 +44,78 @@ import aaf.v2_0.Approval; import aaf.v2_0.Approvals; public class ApprovalAction extends Page { - public ApprovalAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,"Approvals",ApprovalForm.HREF, ApprovalForm.FIELDS, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - final Slot sAppr = gui.env.slot(ApprovalForm.NAME+'.'+ApprovalForm.FIELDS[0]); - final Slot sUser = gui.env.slot(ApprovalForm.NAME+'.'+ApprovalForm.FIELDS[1]); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String[] appr = trans.get(sAppr,null); - String user = trans.get(sUser,null); - String lastPage = ApprovalForm.HREF; - if (user != null) { - lastPage += "?user="+user; - } - - if(appr==null) { - hgen.p("No Approvals have been selected."); - } else { - Approval app; - final Approvals apps = new Approvals(); - int count = 0; - for(String a : appr) { - if(a!=null) { - int idx = a.indexOf('|'); - if(idx>=0) { - app = new Approval(); - app.setStatus(a.substring(0,idx)); - app.setTicket(a.substring(++idx)); - app.setApprover(trans.getUserPrincipal().getName()); - apps.getApprovals().add(app); - ++count; - } - } - } - if(apps.getApprovals().isEmpty()) { - hgen.p("No Approvals have been sent."); - } else { - TimeTaken tt = trans.start("AAF Update Approvals",Env.REMOTE); - try { - final int total = count; - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client) throws APIException, CadiException { - boolean fail2 = true; - Future fa = client.update("/authz/approval",gui.getDF(Approvals.class),apps); - if(fa.get(AAF_GUI.TIMEOUT)) { - // Do Remote Call - fail2 = false; - hgen.p(total + (total==1?" Approval has":" Approvals have") + " been Saved"); - } else { - gui.writeError(trans, fa, hgen, 0); - } - return fail2; - } - }); - } catch (Exception e) { - e.printStackTrace(); - } finally { - tt.done(); - } - } + public ApprovalAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,"Approvals",ApprovalForm.HREF, ApprovalForm.FIELDS, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + final Slot sAppr = gui.env.slot(ApprovalForm.NAME+'.'+ApprovalForm.FIELDS[0]); + final Slot sUser = gui.env.slot(ApprovalForm.NAME+'.'+ApprovalForm.FIELDS[1]); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String[] appr = trans.get(sAppr,null); + String user = trans.get(sUser,null); + String lastPage = ApprovalForm.HREF; + if (user != null) { + lastPage += "?user="+user; + } + + if(appr==null) { + hgen.p("No Approvals have been selected."); + } else { + Approval app; + final Approvals apps = new Approvals(); + int count = 0; + for(String a : appr) { + if(a!=null) { + int idx = a.indexOf('|'); + if(idx>=0) { + app = new Approval(); + app.setStatus(a.substring(0,idx)); + app.setTicket(a.substring(++idx)); + app.setApprover(trans.getUserPrincipal().getName()); + apps.getApprovals().add(app); + ++count; + } + } + } + if(apps.getApprovals().isEmpty()) { + hgen.p("No Approvals have been sent."); + } else { + TimeTaken tt = trans.start("AAF Update Approvals",Env.REMOTE); + try { + final int total = count; + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client) throws APIException, CadiException { + boolean fail2 = true; + Future fa = client.update("/authz/approval",gui.getDF(Approvals.class),apps); + if(fa.get(AAF_GUI.TIMEOUT)) { + // Do Remote Call + fail2 = false; + hgen.p(total + (total==1?" Approval has":" Approvals have") + " been Saved"); + } else { + gui.writeError(trans, fa, hgen, 0); + } + return fail2; + } + }); + } catch (Exception e) { + e.printStackTrace(); + } finally { + tt.done(); + } + } - hgen.br(); - hgen.incr("a",true,"class=greenbutton","href="+lastPage).text("Back").end(); - } - } - }); - } - }); - } + hgen.br(); + hgen.incr("a",true,"class=greenbutton","href="+lastPage).text("Back").end(); + } + } + }); + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java index bc9811ba..14d434cb 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java @@ -64,235 +64,235 @@ import aaf.v2_0.Approval; import aaf.v2_0.Approvals; public class ApprovalForm extends Page { - // Package on purpose - static final String NAME="Approvals"; - static final String HREF = "/gui/approve"; - static final String[] FIELDS = new String[] {"line[]","user"}; - - - public ApprovalForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, FIELDS, + // Package on purpose + static final String NAME="Approvals"; + static final String HREF = "/gui/approve"; + static final String[] FIELDS = new String[] {"line[]","user"}; + + + public ApprovalForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, FIELDS, - new BreadCrumbs(breadcrumbs), - new NamedCode(false, "filterByUser") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String user = trans.get(trans.env().slot(NAME+".user"),""); - hgen.incr("p", "class=userFilter") - .text("Filter by User:") - .tagOnly("input", "type=text", "value="+user, "id=userTextBox") - .tagOnly("input", "type=button", "onclick=userFilter('"+HREF+"');", "value=Go!") - .end(); - } - }); - } - }, - new Form(true,new Table("Approval Requests", gui.env.newTransNoAvg(),new Model(gui.env),"class=stdform")) - .preamble("The following requires your Approval to proceed in the AAF System.

    Hover on Identity for Name; click for WebPhone; If Deny is the only option, User is no longer valid."), - new NamedCode(false, "selectAlljs") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - Mark jsStart = new Mark(); - hgen.js(jsStart); - hgen.text("function selectAll(radioClass) {"); - hgen.text("var radios = document.querySelectorAll(\".\"+radioClass);"); - hgen.text("for (i = 0; i < radios.length; i++) {"); - hgen.text("radios[i].checked = true;"); - hgen.text("}"); - hgen.text("}"); - hgen.end(jsStart); - } - }); - - } - - /** - * Implement the Table Content for Approvals - * - * @author Jonathan - * - */ - private static class Model extends TableData { - //TODO come up with a generic way to do ILM Info (people page) - private static final String TODO_ILM_INFO = "TODO: ILM Info"; - private static final String DOMAIN_OF_USER = "@DOMAIN"; - - private static final String[] headers = new String[] {"Identity","Request","Approve","Deny"}; - private Slot sUser; - - public Model(AuthzEnv env) { - sUser = env.slot(NAME+".user"); - } - - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String userParam = trans.get(sUser, null); - ArrayList rv = new ArrayList<>(); - String msg = null; - TimeTaken tt = trans.start("AAF Get Approvals for Approver",Env.REMOTE); - try { - final List pendingApprovals = new ArrayList<>(); - final List beginIndicesPerApprover = new ArrayList<>(); - int numLeft = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Integer code(Rcli client) throws CadiException, ConnectException, APIException { - Future fa = client.read("/authz/approval/approver/"+trans.user(),gui.getDF(Approvals.class)); - int numLeft = 0; - if(fa.get(AAF_GUI.TIMEOUT)) { - - if(fa.value!=null) { - for (Approval appr : fa.value.getApprovals()) { - if ("pending".equals(appr.getStatus())) { - if (userParam!=null && !appr.getUser().equalsIgnoreCase(userParam)) { - numLeft++; - continue; - } - pendingApprovals.add(appr); - } - } - } - - String prevApprover = null; - int overallIndex = 0; - - for (Approval appr : pendingApprovals) { - String currApprover = appr.getApprover(); - if (!currApprover.equals(prevApprover)) { - prevApprover = currApprover; - beginIndicesPerApprover.add(overallIndex); - } - overallIndex++; - } - } - return numLeft; - } - }); - - if (!pendingApprovals.isEmpty()) { - // Only add select all links if we have approvals - AbsCell[] selectAllRow = new AbsCell[] { - AbsCell.Null, - AbsCell.Null, - new ButtonCell("all", "onclick=selectAll('approve')", "class=selectAllButton"), - new ButtonCell("all", "onclick=selectAll('deny')", "class=selectAllButton") - }; - rv.add(selectAllRow); - } - - int line=-1; - - while (!beginIndicesPerApprover.isEmpty()) { - int beginIndex = beginIndicesPerApprover.remove(0); - int endIndex = (beginIndicesPerApprover.isEmpty()?pendingApprovals.size():beginIndicesPerApprover.get(0)); - List currApproverList = pendingApprovals.subList(beginIndex, endIndex); - - String currApproverFull = currApproverList.get(0).getApprover(); - String currApproverShort = currApproverFull.substring(0,currApproverFull.indexOf('@')); - String currApprover = (trans.user().indexOf('@')<0?currApproverShort:currApproverFull); - if (!currApprover.equals(trans.user())) { - AbsCell[] approverHeader; - if (currApproverFull.substring(currApproverFull.indexOf('@')).equals(DOMAIN_OF_USER)) { - approverHeader = new AbsCell[] { - new TextAndRefCell("Approvals Delegated to Me by ", currApprover, - TODO_ILM_INFO + currApproverShort, - true, - new String[] {"colspan=4", "class=head"}) - }; - } else { - approverHeader = new AbsCell[] { - new TextCell("Approvals Delegated to Me by " + currApprover, - new String[] {"colspan=4", "class=head"}) - }; - } - rv.add(approverHeader); - } - - // Sort by User Requesting - Collections.sort(currApproverList, new Comparator() { - @Override - public int compare(Approval a1, Approval a2) { - return a1.getUser().compareTo(a2.getUser()); - } - }); - - String prevUser = null; - boolean userOK=true; + new BreadCrumbs(breadcrumbs), + new NamedCode(false, "filterByUser") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String user = trans.get(trans.env().slot(NAME+".user"),""); + hgen.incr("p", "class=userFilter") + .text("Filter by User:") + .tagOnly("input", "type=text", "value="+user, "id=userTextBox") + .tagOnly("input", "type=button", "onclick=userFilter('"+HREF+"');", "value=Go!") + .end(); + } + }); + } + }, + new Form(true,new Table("Approval Requests", gui.env.newTransNoAvg(),new Model(gui.env),"class=stdform")) + .preamble("The following requires your Approval to proceed in the AAF System.

    Hover on Identity for Name; click for WebPhone; If Deny is the only option, User is no longer valid."), + new NamedCode(false, "selectAlljs") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + Mark jsStart = new Mark(); + hgen.js(jsStart); + hgen.text("function selectAll(radioClass) {"); + hgen.text("var radios = document.querySelectorAll(\".\"+radioClass);"); + hgen.text("for (i = 0; i < radios.length; i++) {"); + hgen.text("radios[i].checked = true;"); + hgen.text("}"); + hgen.text("}"); + hgen.end(jsStart); + } + }); + + } + + /** + * Implement the Table Content for Approvals + * + * @author Jonathan + * + */ + private static class Model extends TableData { + //TODO come up with a generic way to do ILM Info (people page) + private static final String TODO_ILM_INFO = "TODO: ILM Info"; + private static final String DOMAIN_OF_USER = "@DOMAIN"; + + private static final String[] headers = new String[] {"Identity","Request","Approve","Deny"}; + private Slot sUser; + + public Model(AuthzEnv env) { + sUser = env.slot(NAME+".user"); + } + + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String userParam = trans.get(sUser, null); + ArrayList rv = new ArrayList<>(); + String msg = null; + TimeTaken tt = trans.start("AAF Get Approvals for Approver",Env.REMOTE); + try { + final List pendingApprovals = new ArrayList<>(); + final List beginIndicesPerApprover = new ArrayList<>(); + int numLeft = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Integer code(Rcli client) throws CadiException, ConnectException, APIException { + Future fa = client.read("/authz/approval/approver/"+trans.user(),gui.getDF(Approvals.class)); + int numLeft = 0; + if(fa.get(AAF_GUI.TIMEOUT)) { + + if(fa.value!=null) { + for (Approval appr : fa.value.getApprovals()) { + if ("pending".equals(appr.getStatus())) { + if (userParam!=null && !appr.getUser().equalsIgnoreCase(userParam)) { + numLeft++; + continue; + } + pendingApprovals.add(appr); + } + } + } + + String prevApprover = null; + int overallIndex = 0; + + for (Approval appr : pendingApprovals) { + String currApprover = appr.getApprover(); + if (!currApprover.equals(prevApprover)) { + prevApprover = currApprover; + beginIndicesPerApprover.add(overallIndex); + } + overallIndex++; + } + } + return numLeft; + } + }); + + if (!pendingApprovals.isEmpty()) { + // Only add select all links if we have approvals + AbsCell[] selectAllRow = new AbsCell[] { + AbsCell.Null, + AbsCell.Null, + new ButtonCell("all", "onclick=selectAll('approve')", "class=selectAllButton"), + new ButtonCell("all", "onclick=selectAll('deny')", "class=selectAllButton") + }; + rv.add(selectAllRow); + } + + int line=-1; + + while (!beginIndicesPerApprover.isEmpty()) { + int beginIndex = beginIndicesPerApprover.remove(0); + int endIndex = (beginIndicesPerApprover.isEmpty()?pendingApprovals.size():beginIndicesPerApprover.get(0)); + List currApproverList = pendingApprovals.subList(beginIndex, endIndex); + + String currApproverFull = currApproverList.get(0).getApprover(); + String currApproverShort = currApproverFull.substring(0,currApproverFull.indexOf('@')); + String currApprover = (trans.user().indexOf('@')<0?currApproverShort:currApproverFull); + if (!currApprover.equals(trans.user())) { + AbsCell[] approverHeader; + if (currApproverFull.substring(currApproverFull.indexOf('@')).equals(DOMAIN_OF_USER)) { + approverHeader = new AbsCell[] { + new TextAndRefCell("Approvals Delegated to Me by ", currApprover, + TODO_ILM_INFO + currApproverShort, + true, + new String[] {"colspan=4", "class=head"}) + }; + } else { + approverHeader = new AbsCell[] { + new TextCell("Approvals Delegated to Me by " + currApprover, + new String[] {"colspan=4", "class=head"}) + }; + } + rv.add(approverHeader); + } + + // Sort by User Requesting + Collections.sort(currApproverList, new Comparator() { + @Override + public int compare(Approval a1, Approval a2) { + return a1.getUser().compareTo(a2.getUser()); + } + }); + + String prevUser = null; + boolean userOK=true; - for (Approval appr : currApproverList) { - if(++line0) { - msg = "After these, there will be " + numLeft + " approvals left to process"; - } - if(rv.isEmpty()) { - if (numLeft>0) { - msg = "No Approvals to process at this time for user " + userParam +". You have " - + numLeft + " other approvals to process."; - } else { - msg = "No Approvals to process at this time"; - } - } - } catch (Exception e) { - trans.error().log(e); - } finally { - tt.done(); - } - return new Cells(rv,msg); - } - } + for (Approval appr : currApproverList) { + if(++line0) { + msg = "After these, there will be " + numLeft + " approvals left to process"; + } + if(rv.isEmpty()) { + if (numLeft>0) { + msg = "No Approvals to process at this time for user " + userParam +". You have " + + numLeft + " other approvals to process."; + } else { + msg = "No Approvals to process at this time"; + } + } + } catch (Exception e) { + trans.error().log(e); + } finally { + tt.done(); + } + return new Cells(rv,msg); + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java index 1bf0ed76..8088a700 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java @@ -50,170 +50,170 @@ import certman.v1_0.Artifacts; import certman.v1_0.Artifacts.Artifact; public class CMArtiChangeAction extends Page { - public CMArtiChangeAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,CMArtiChangeForm.NAME,CMArtiChangeForm.HREF, CMArtiChangeForm.fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - final Slot sID = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[0]); - final Slot sMachine = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[1]); - final Slot sNS = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[2]); - final Slot sDirectory = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[3]); - final Slot sCA = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[4]); - final Slot sOSUser = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[5]); - final Slot sRenewal = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[6]); - final Slot sNotify = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[7]); - final Slot sCmd = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[8]); - final Slot sOther = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[9]); - final Slot sType = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[10]); - final Slot sSans = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[11]); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + public CMArtiChangeAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,CMArtiChangeForm.NAME,CMArtiChangeForm.HREF, CMArtiChangeForm.fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + final Slot sID = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[0]); + final Slot sMachine = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[1]); + final Slot sNS = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[2]); + final Slot sDirectory = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[3]); + final Slot sCA = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[4]); + final Slot sOSUser = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[5]); + final Slot sRenewal = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[6]); + final Slot sNotify = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[7]); + final Slot sCmd = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[8]); + final Slot sOther = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[9]); + final Slot sType = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[10]); + final Slot sSans = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[11]); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { trans.info().log("Step 1"); - final Artifact arti = new Artifact(); - final String machine = trans.get(sMachine,null); - final String ca = trans.get(sCA, null); - final String sans = ((String)trans.get(sSans,null)); - if(sans!=null) { - for(String s: Split.splitTrim(',', sans)) { - arti.getSans().add(s); - } - } - // Disallow IP entries, except by special Permission - if(!trans.fish(getPerm(ca,"ip"))) { - boolean ok=true; - if(IPValidator.ip(machine)) { - ok=false; - } - if(ok) { - for(String s: arti.getSans()) { - if(IPValidator.ip(s)) { - ok=false; - break; - } - } - } - if(!ok) { - hgen.p("Policy Failure: IPs in certificates are only allowed by Exception."); - return; - } - } - - // Disallow Domain based Definitions without exception - if(machine.startsWith("*")) { // Domain set - if(!trans.fish(getPerm(ca, "domain"))) { - hgen.p("Policy Failure: Domain Artifact Declarations are only allowed by Exception."); - return; - } - } - - arti.setMechid((String)trans.get(sID,null)); - arti.setMachine(machine); - arti.setNs((String)trans.get(sNS,null)); - arti.setDir((String)trans.get(sDirectory,null)); - arti.setCa(ca); - arti.setOsUser((String)trans.get(sOSUser, null)); - arti.setRenewDays(Integer.parseInt((String)trans.get(sRenewal, null))); - arti.setNotification((String)trans.get(sNotify, null)); - String[] checkbox = trans.get(sType,null); - for(int i=0;i ok = new Holder(false); - final Holder deleted = new Holder(false); - Future f = gui.cmClientAsUser(trans.getUserPrincipal(), new Retryable>() { - @Override - public Future code(Rcli client)throws CadiException, ConnectException, APIException { - Future rv = null; - switch((String)trans.get(sCmd, "")) { - case CMArtiChangeForm.CREATE: - Future fc; - rv = fc = client.create("/cert/artifacts", gui.artifactsDF, artifacts); - if(fc.get(AAFcli.timeout())) { - hgen.p("Created Artifact " + arti.getMechid() + " on " + arti.getMachine()); - ok.set(true); - } - break; - case CMArtiChangeForm.UPDATE: - Future fu = client.update("/cert/artifacts", gui.artifactsDF, artifacts); - if((rv=fu).get(AAFcli.timeout())) { - hgen.p("Artifact " + arti.getMechid() + " on " + arti.getMachine() + " is updated"); - ok.set(true); - } - break; - case CMArtiChangeForm.COPY: - Future future = client.read("/cert/artifacts/"+arti.getMechid()+'/'+arti.getMachine(), gui.artifactsDF); - rv = future; - if(future.get(AAFcli.timeout())) { - for(Artifact a : future.value.getArtifact()) { // only one, because these two are key - for(String newMachine :Split.split(',', trans.get(sOther, ""))) { - a.setMachine(newMachine); - Future fup = client.update("/cert/artifacts", gui.artifactsDF, future.value); - if(fup.get(AAFcli.timeout())) { - hgen.p("Copied to " + newMachine); - ok.set(true); - } - } - } - } - break; - case CMArtiChangeForm.DELETE: - Future fv; - rv = fv = client.delete("/cert/artifacts/"+arti.getMechid()+"/"+arti.getMachine(),"application/json"); - if(fv.get(AAFcli.timeout())) { - hgen.p("Deleted " + arti.getMechid() + " on " + arti.getMachine()); - ok.set(true); - deleted.set(true); - } - break; - } - return rv; - } - }); - if(!ok.get()) { - if(f==null) { - hgen.p("Unknown Command"); - } else { - if(f.body().contains("%")) { - Error err = gui.getDF(Error.class).newData().in(TYPE.JSON).load(f.body()).asObject(); - hgen.p(Vars.convert(err.getText(),err.getVariables())); - } else { - hgen.p(arti.getMechid() + " on " + arti.getMachine() + ": " + f.body()); - } - } - } - hgen.br().leaf(HTMLGen.A,"class=greenbutton","href="+(deleted.get()?CMArtifactShow.HREF:CMArtiChangeForm.HREF)+ - "?id="+arti.getMechid()+ - "&machine="+arti.getMachine() + - "&ns="+arti.getNs()) - .text("Back") - .end(); + // Run Validations + if (arti.getMechid()==null || arti.getMechid().indexOf('@')<=0) { + hgen.p("Data Entry Failure: Please enter a valid ID, including domain."); + // VALIDATE OTHERS? + } else { // everything else is checked by Server + + try { + final Artifacts artifacts = new Artifacts(); + artifacts.getArtifact().add(arti); + final Holder ok = new Holder(false); + final Holder deleted = new Holder(false); + Future f = gui.cmClientAsUser(trans.getUserPrincipal(), new Retryable>() { + @Override + public Future code(Rcli client)throws CadiException, ConnectException, APIException { + Future rv = null; + switch((String)trans.get(sCmd, "")) { + case CMArtiChangeForm.CREATE: + Future fc; + rv = fc = client.create("/cert/artifacts", gui.artifactsDF, artifacts); + if(fc.get(AAFcli.timeout())) { + hgen.p("Created Artifact " + arti.getMechid() + " on " + arti.getMachine()); + ok.set(true); + } + break; + case CMArtiChangeForm.UPDATE: + Future fu = client.update("/cert/artifacts", gui.artifactsDF, artifacts); + if((rv=fu).get(AAFcli.timeout())) { + hgen.p("Artifact " + arti.getMechid() + " on " + arti.getMachine() + " is updated"); + ok.set(true); + } + break; + case CMArtiChangeForm.COPY: + Future future = client.read("/cert/artifacts/"+arti.getMechid()+'/'+arti.getMachine(), gui.artifactsDF); + rv = future; + if(future.get(AAFcli.timeout())) { + for(Artifact a : future.value.getArtifact()) { // only one, because these two are key + for(String newMachine :Split.split(',', trans.get(sOther, ""))) { + a.setMachine(newMachine); + Future fup = client.update("/cert/artifacts", gui.artifactsDF, future.value); + if(fup.get(AAFcli.timeout())) { + hgen.p("Copied to " + newMachine); + ok.set(true); + } + } + } + } + break; + case CMArtiChangeForm.DELETE: + Future fv; + rv = fv = client.delete("/cert/artifacts/"+arti.getMechid()+"/"+arti.getMachine(),"application/json"); + if(fv.get(AAFcli.timeout())) { + hgen.p("Deleted " + arti.getMechid() + " on " + arti.getMachine()); + ok.set(true); + deleted.set(true); + } + break; + } + return rv; + } + }); + if(!ok.get()) { + if(f==null) { + hgen.p("Unknown Command"); + } else { + if(f.body().contains("%")) { + Error err = gui.getDF(Error.class).newData().in(TYPE.JSON).load(f.body()).asObject(); + hgen.p(Vars.convert(err.getText(),err.getVariables())); + } else { + hgen.p(arti.getMechid() + " on " + arti.getMachine() + ": " + f.body()); + } + } + } + hgen.br().leaf(HTMLGen.A,"class=greenbutton","href="+(deleted.get()?CMArtifactShow.HREF:CMArtiChangeForm.HREF)+ + "?id="+arti.getMechid()+ + "&machine="+arti.getMachine() + + "&ns="+arti.getNs()) + .text("Back") + .end(); - } catch (Exception e) { - hgen.p("Unknown Error"); - e.printStackTrace(); - } - - } - hgen.br(); - } - }); - } - }); - } + } catch (Exception e) { + hgen.p("Unknown Error"); + e.printStackTrace(); + } + + } + hgen.br(); + } + }); + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java index a96b08b9..0268f498 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java @@ -53,194 +53,194 @@ import certman.v1_0.Artifacts; import certman.v1_0.Artifacts.Artifact; public class CMArtiChangeForm extends Page { - private static final String COPY_ARTIFACT = "copyArtifact"; - private static final String DELETE_ARTIFACT = "deleteArtifact"; - - // Package on purpose - static final String HREF = "/gui/artichange"; - static final String NAME = "ArtifactChange"; - static final String fields[] = {"id","machine","ns","directory","ca","osuser","renewal","notify","cmd","others","types[]","sans"}; - - static final String types[] = {"pkcs12","jks","file","script"}; - static final String UPDATE = "Update"; - static final String CREATE = "Create"; - static final String COPY = "Copy"; - static final String DELETE = "Delete"; - - public CMArtiChangeForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - private final Slot sID = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[0]); - private final Slot sMach = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[1]); - private final Slot sNS = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[2]); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - Mark js = new Mark(); - Mark fn = new Mark(); - hgen.js(js).function(fn,COPY_ARTIFACT) - .text("f=document.getElementById('"+fields[9]+"')") - .text("s=document.getElementById('theButton')") - .text("cmd=document.getElementById('"+fields[8]+"')") - .text("ins=document.getElementById('instruct')") - .text("c=document.getElementById('cbcopy')") - .text("trd=document.getElementById('trdelete')") - .li("if (c.checked==true) {" , - "f.style.display=ins.style.display='block'", - "trd.style.display='none'", - "s.orig=s.value;", - "s.value='Copy'", - "cmd.setAttribute('value',s.value)", - "} else {", - "f.style.display=ins.style.display='none';", - "trd.style.display='block'", - "s.value=s.orig", - "cmd.setAttribute('value',s.orig)", - "}" - ) - .end(fn) - .function(fn, DELETE_ARTIFACT) - .text("d=document.getElementById('cbdelete')") - .text("trc=document.getElementById('trcopy')") - .text("s=document.getElementById('theButton')") - .text("cmd=document.getElementById('"+fields[8]+"')") - .li("if (d.checked==true) {", - "s.orig=s.value;", - "s.value='Delete';", - "trc.style.display='none';", - "cmd.setAttribute('value',s.value);", - "} else {", - "s.value=s.orig;", - "trc.style.display='block';", - "cmd.setAttribute('value',s.orig);", - "}" - ) - .end(js); + private static final String COPY_ARTIFACT = "copyArtifact"; + private static final String DELETE_ARTIFACT = "deleteArtifact"; + + // Package on purpose + static final String HREF = "/gui/artichange"; + static final String NAME = "ArtifactChange"; + static final String fields[] = {"id","machine","ns","directory","ca","osuser","renewal","notify","cmd","others","types[]","sans"}; + + static final String types[] = {"pkcs12","jks","file","script"}; + static final String UPDATE = "Update"; + static final String CREATE = "Create"; + static final String COPY = "Copy"; + static final String DELETE = "Delete"; + + public CMArtiChangeForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + private final Slot sID = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[0]); + private final Slot sMach = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[1]); + private final Slot sNS = gui.env.slot(CMArtiChangeForm.NAME+'.'+CMArtiChangeForm.fields[2]); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + Mark js = new Mark(); + Mark fn = new Mark(); + hgen.js(js).function(fn,COPY_ARTIFACT) + .text("f=document.getElementById('"+fields[9]+"')") + .text("s=document.getElementById('theButton')") + .text("cmd=document.getElementById('"+fields[8]+"')") + .text("ins=document.getElementById('instruct')") + .text("c=document.getElementById('cbcopy')") + .text("trd=document.getElementById('trdelete')") + .li("if (c.checked==true) {" , + "f.style.display=ins.style.display='block'", + "trd.style.display='none'", + "s.orig=s.value;", + "s.value='Copy'", + "cmd.setAttribute('value',s.value)", + "} else {", + "f.style.display=ins.style.display='none';", + "trd.style.display='block'", + "s.value=s.orig", + "cmd.setAttribute('value',s.orig)", + "}" + ) + .end(fn) + .function(fn, DELETE_ARTIFACT) + .text("d=document.getElementById('cbdelete')") + .text("trc=document.getElementById('trcopy')") + .text("s=document.getElementById('theButton')") + .text("cmd=document.getElementById('"+fields[8]+"')") + .li("if (d.checked==true) {", + "s.orig=s.value;", + "s.value='Delete';", + "trc.style.display='none';", + "cmd.setAttribute('value',s.value);", + "} else {", + "s.value=s.orig;", + "trc.style.display='block';", + "cmd.setAttribute('value',s.orig);", + "}" + ) + .end(js); - hgen.leaf(HTMLGen.TITLE).text("Certificate Artifact Form").end(); - Mark form = new Mark(); - hgen.incr(form, "form","action="+HREF,"method=post"); - - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + hgen.leaf(HTMLGen.TITLE).text("Certificate Artifact Form").end(); + Mark form = new Mark(); + hgen.incr(form, "form","action="+HREF,"method=post"); + + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final String incomingMach = trans.get(sMach,""); - String incomingNS = trans.get(sNS,""); - String id= trans.get(sID, ""); - final String incomingID = id.indexOf('@')>=0?id:id+'@'+FQI.reverseDomain(incomingNS); + final String incomingMach = trans.get(sMach,""); + String incomingNS = trans.get(sNS,""); + String id= trans.get(sID, ""); + final String incomingID = id.indexOf('@')>=0?id:id+'@'+FQI.reverseDomain(incomingNS); - String submitText=UPDATE; - boolean delete=true; - try { - Artifact arti =gui.cmClientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Artifact code(Rcli client) throws CadiException, ConnectException, APIException { - Future fa = client.read("/cert/artifacts/"+incomingID+'/'+incomingMach, gui.artifactsDF); - if(fa.get(AAFcli.timeout())) { - for(Artifact arti : fa.value.getArtifact()) { - return arti; // just need the first one - } - } - return null; - } - }); - if(arti==null) { - Organization org = OrganizationFactory.get(trans); - Identity user = org.getIdentity(trans, incomingID); - if(user==null) { - hgen.p("The mechID you typed, \"" + incomingID + "\", is not a valid " + org.getName() + " ID"); - return; - } - arti = new Artifact(); - arti.setMechid(incomingID); - Identity managedBy = user.responsibleTo(); - if(managedBy == null) { - arti.setSponsor("Unknown Sponsor"); - } else { - arti.setSponsor(managedBy.fullID()); - } - arti.setMachine(incomingMach); - arti.setNs(incomingNS); - arti.setDir(""); - arti.setCa("aaf"); - arti.setOsUser(""); - arti.setRenewDays(30); - arti.setNotification("mailto:"+user.email()); - arti.getType().add(types[0]); - arti.getType().add(types[3]); - submitText = CREATE; - delete = false; - } else { - if(arti.getNotification()==null) { - Organization org = OrganizationFactory.get(trans); - Identity user = org.getIdentity(trans, incomingID); - arti.setNotification("mailto:"+user.email()); - } - } - Mark table = new Mark(TABLE); - hgen.incr(table) - .input(fields[0],"AppID*",true,"value="+arti.getMechid()) - .input("sponsor", "Sponsor",false,"value="+arti.getSponsor(),"readonly","style=border:none;background-color:white;") - .input(fields[1],"FQDN*",true,"value="+arti.getMachine(),"style=width:130%;"); -// if(maySans) { - hgen.incr(HTMLGen.TR).incr(HTMLGen.TD).end() - .incr(HTMLGen.TD,"class=subtext").text("Use Fully Qualified Domain Names (that will be in DNS), "); - if(!trans.fish(getPerm(arti.getCa(),"ip"))) { - hgen.text("NO "); - } - StringBuilder sb = null; - for(String s: arti.getSans()) { - if(sb==null) { - sb = new StringBuilder(); - } else { - sb.append(", "); - } - sb.append(s); - } - - hgen.text("IPs allowed, separated by commas.").end() - .input(fields[11], "SANs", false, "value="+(sb==null?"":sb.toString()),"style=width:130%;"); -// } - hgen.input(fields[2],"Namespace",true,"value="+arti.getNs(),"style=width:130%;") - .input(fields[3],"Directory", true, "value="+arti.getDir(),"style=width:130%;") - .input(fields[4],"Certificate Authority",true,"value="+arti.getCa(),"style=width:130%;") - .input(fields[5],"O/S User",true,"value="+arti.getOsUser()) - .input(fields[6],"Renewal Days before Expiration", true, "value="+arti.getRenewDays(),"style=width:20%;") - .input(fields[7],"Notification",true,"value="+arti.getNotification()) - .incr(HTMLGen.TR) - .incr(HTMLGen.TD).leaf("label","for=types","required").text("Artifact Types").end(2) - .incr(HTMLGen.TD); - for(int i=0;i slotCode; - private enum Params{id,ns}; + + public static final String HREF = "/gui/cmarti"; + public static final String NAME = "ArtifactsShow"; + private static ArtiTable arti; + public static SlotCode slotCode; + private enum Params{id,ns}; - public CMArtifactShow(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME, HREF, Params.values() , - new BreadCrumbs(breadcrumbs), - arti = new ArtiTable(gui.env) - ); - // Setting so we can get access to HTMLGen clone and Slots - arti.set(this,slotCode); - } - - private static class ArtiTable extends Table { - private static Model model; - private SlotCode sc; - enum Params {id,ns}; - public ArtiTable(AuthzEnv env) { - super((String)null,env.newTransNoAvg(),model = new Model(), - slotCode = new SlotCode(false,env,NAME,Params.values()) { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - Mark js = new Mark(); - hgen.js(js).function("newArtifact") - .text("machine=document.getElementById('machine');") - .text("window.open('" - +CMArtiChangeForm.HREF+ - "?id="+get(trans, Params.id,"")+ - "&ns="+get(trans, Params.ns,"")+ - "&machine='+machine.value,'_self');" - ).end(js); - hgen.leaf("input","id=machine","style=margin:1em 1em 1em 1em;width:30%").end(); - hgen.leaf(HTMLGen.A,"class=greenbutton","href=javascript:newArtifact()","style=color:white;").text("New FQDN").end(); - } - }); - } - },"class=std"); - } - + public CMArtifactShow(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME, HREF, Params.values() , + new BreadCrumbs(breadcrumbs), + arti = new ArtiTable(gui.env) + ); + // Setting so we can get access to HTMLGen clone and Slots + arti.set(this,slotCode); + } + + private static class ArtiTable extends Table { + private static Model model; + private SlotCode sc; + enum Params {id,ns}; + public ArtiTable(AuthzEnv env) { + super((String)null,env.newTransNoAvg(),model = new Model(), + slotCode = new SlotCode(false,env,NAME,Params.values()) { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + Mark js = new Mark(); + hgen.js(js).function("newArtifact") + .text("machine=document.getElementById('machine');") + .text("window.open('" + +CMArtiChangeForm.HREF+ + "?id="+get(trans, Params.id,"")+ + "&ns="+get(trans, Params.ns,"")+ + "&machine='+machine.value,'_self');" + ).end(js); + hgen.leaf("input","id=machine","style=margin:1em 1em 1em 1em;width:30%").end(); + hgen.leaf(HTMLGen.A,"class=greenbutton","href=javascript:newArtifact()","style=color:white;").text("New FQDN").end(); + } + }); + } + },"class=std"); + } + - public void set(CMArtifactShow cmArtifactShow, SlotCode sc) { - this.sc = sc; - model.set(cmArtifactShow,sc); - } - - @Override - protected String title(AuthzTrans trans) { - StringBuilder sb = new StringBuilder("X509 Certificates"); - if(sc!=null) { // initialized - sb.append(" for "); - String id = sc.get(trans,Params.id,""); - sb.append(id); - if(id.indexOf('@')<0) { - sb.append('@'); - sb.append(FQI.reverseDomain(sc.get(trans, Params.ns,"missingDomain"))); - } - } - return sb.toString(); - } - } - /** - * Implement the table content for Cred Detail - * - * @author Jeremiah - * - */ - private static class Model implements Table.Data { - private CMArtifactShow cas; - private SlotCode sc; + public void set(CMArtifactShow cmArtifactShow, SlotCode sc) { + this.sc = sc; + model.set(cmArtifactShow,sc); + } + + @Override + protected String title(AuthzTrans trans) { + StringBuilder sb = new StringBuilder("X509 Certificates"); + if(sc!=null) { // initialized + sb.append(" for "); + String id = sc.get(trans,Params.id,""); + sb.append(id); + if(id.indexOf('@')<0) { + sb.append('@'); + sb.append(FQI.reverseDomain(sc.get(trans, Params.ns,"missingDomain"))); + } + } + return sb.toString(); + } + } + /** + * Implement the table content for Cred Detail + * + * @author Jeremiah + * + */ + private static class Model implements Table.Data { + private CMArtifactShow cas; + private SlotCode sc; - // Covering for Constructor Order - private void set(CMArtifactShow cas, SlotCode sc) { - this.cas = cas; - this.sc = sc; - } + // Covering for Constructor Order + private void set(CMArtifactShow cas, SlotCode sc) { + this.cas = cas; + this.sc = sc; + } - private static final String[] headers = new String[]{"FQDN","Directory","CA","Renews","Expires",""}; - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - String str = sc.get(trans,Params.id, null); - if(str==null) { - return Cells.EMPTY; - } - final String id = str.indexOf('@')>=0?str:str + '@' + FQI.reverseDomain(sc.get(trans,Params.ns, "")); - final ArrayList rv = new ArrayList<>(); - final TimeTaken tt = trans.start("AAF X509 Details",Env.REMOTE); - try { - gui.cmClientAsUser(trans.getUserPrincipal(),new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fuCI = client.read("/cert/id/"+id,gui.certInfoDF); - Future fuArt = client.read("/cert/artifacts?mechid="+id, gui.artifactsDF); - - X509Certificate[] lc; - if(fuCI.get(AAFcli.timeout())) { - TimeTaken tt1 = trans.start("x509Certificate", Env.SUB); - try { - Collection xcs = Factory.toX509Certificate(fuCI.value.getCerts()); - lc = new X509Certificate[xcs.size()]; - xcs.toArray(lc); - } catch (CertificateException e) { - trans.error().log(e,"Bad Certificate entry"); - throw new CadiException(e); - } finally { - tt1.done(); - } - } else { - lc = null; - trans.error().log("Cannot retrieve Certificates for " + id); - } - if(fuArt.get(AAFcli.timeout())) { - for(Artifact arti : fuArt.value.getArtifact()) { - StringWriter sw = new StringWriter(); - HTMLGen hgen = cas.clone(sw); - Mark mark = new Mark(); - hgen.leaf(HTMLGen.A,"class=button", - "href="+CMArtiChangeForm.HREF+"?id="+arti.getMechid() +"&machine="+arti.getMachine()+"&ns="+arti.getNs()) - .text("Details") - .end(mark); - Date last = null; - if(lc!=null) { - for(X509Certificate xc : lc) { - if(xc.getSubjectDN().getName().contains("CN="+arti.getMachine())) { - if(last==null || last.before(xc.getNotAfter())) { - last = xc.getNotAfter(); - } - } - } - } - GregorianCalendar renew; - if(last!=null) { - renew = new GregorianCalendar(); - renew.setTime(last); - renew.add(GregorianCalendar.DAY_OF_MONTH,arti.getRenewDays()*-1); - } else { - renew = null; - } + private static final String[] headers = new String[]{"FQDN","Directory","CA","Renews","Expires",""}; + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + String str = sc.get(trans,Params.id, null); + if(str==null) { + return Cells.EMPTY; + } + final String id = str.indexOf('@')>=0?str:str + '@' + FQI.reverseDomain(sc.get(trans,Params.ns, "")); + final ArrayList rv = new ArrayList<>(); + final TimeTaken tt = trans.start("AAF X509 Details",Env.REMOTE); + try { + gui.cmClientAsUser(trans.getUserPrincipal(),new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fuCI = client.read("/cert/id/"+id,gui.certInfoDF); + Future fuArt = client.read("/cert/artifacts?mechid="+id, gui.artifactsDF); + + X509Certificate[] lc; + if(fuCI.get(AAFcli.timeout())) { + TimeTaken tt1 = trans.start("x509Certificate", Env.SUB); + try { + Collection xcs = Factory.toX509Certificate(fuCI.value.getCerts()); + lc = new X509Certificate[xcs.size()]; + xcs.toArray(lc); + } catch (CertificateException e) { + trans.error().log(e,"Bad Certificate entry"); + throw new CadiException(e); + } finally { + tt1.done(); + } + } else { + lc = null; + trans.error().log("Cannot retrieve Certificates for " + id); + } + if(fuArt.get(AAFcli.timeout())) { + for(Artifact arti : fuArt.value.getArtifact()) { + StringWriter sw = new StringWriter(); + HTMLGen hgen = cas.clone(sw); + Mark mark = new Mark(); + hgen.leaf(HTMLGen.A,"class=button", + "href="+CMArtiChangeForm.HREF+"?id="+arti.getMechid() +"&machine="+arti.getMachine()+"&ns="+arti.getNs()) + .text("Details") + .end(mark); + Date last = null; + if(lc!=null) { + for(X509Certificate xc : lc) { + if(xc.getSubjectDN().getName().contains("CN="+arti.getMachine())) { + if(last==null || last.before(xc.getNotAfter())) { + last = xc.getNotAfter(); + } + } + } + } + GregorianCalendar renew; + if(last!=null) { + renew = new GregorianCalendar(); + renew.setTime(last); + renew.add(GregorianCalendar.DAY_OF_MONTH,arti.getRenewDays()*-1); + } else { + renew = null; + } - rv.add(new AbsCell[] { - new TextCell(arti.getMachine(),"style=width:20%;"), - new TextCell(arti.getDir(),"style=width:25%;"), - new TextCell(arti.getCa(),"style=width:2%;text-align:center;"), - new TextCell(renew==null? - arti.getRenewDays().toString() + " days before Exp": - Chrono.dateOnlyStamp(renew),"style=width:6%;text-align:center;"), - new TextCell(last==null?"None Deployed":Chrono.dateOnlyStamp(last),"style=width:5%;text-align:center;"), - new TextCell(sw.toString(),"style=width:10%;text-align:center;") - }); - } - } else { - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); - } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(); - } finally { - tt.done(); - } - return new Cells(rv,null); - } + rv.add(new AbsCell[] { + new TextCell(arti.getMachine(),"style=width:20%;"), + new TextCell(arti.getDir(),"style=width:25%;"), + new TextCell(arti.getCa(),"style=width:2%;text-align:center;"), + new TextCell(renew==null? + arti.getRenewDays().toString() + " days before Exp": + Chrono.dateOnlyStamp(renew),"style=width:6%;text-align:center;"), + new TextCell(last==null?"None Deployed":Chrono.dateOnlyStamp(last),"style=width:5%;text-align:center;"), + new TextCell(sw.toString(),"style=width:10%;text-align:center;") + }); + } + } else { + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); + } + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(); + } finally { + tt.done(); + } + return new Cells(rv,null); + } - @Override - public void prefix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { - } + @Override + public void prefix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { + } - @Override - public void postfix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { - } + @Override + public void postfix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { + } - } - + } + } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java index 208c750e..7daee3dd 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java @@ -67,286 +67,286 @@ import certman.v1_0.Artifacts; import certman.v1_0.Artifacts.Artifact; public class CredDetail extends Page { - - public static final String HREF = "/gui/creddetail"; - public static final String NAME = "CredDetail"; - private static Model model; - private static SlotCode slotCode; - enum Params {id,ns}; + + public static final String HREF = "/gui/creddetail"; + public static final String NAME = "CredDetail"; + private static Model model; + private static SlotCode slotCode; + enum Params {id,ns}; - public CredDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME, HREF, Params.values(), - new BreadCrumbs(breadcrumbs), - new Table("Cred Details",gui.env.newTransNoAvg(),model = new Model(), - slotCode = new SlotCode(false,gui.env,NAME,Params.values()) { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String ns = get(trans, Params.ns,""); - String domain = FQI.reverseDomain(ns); - Mark js = new Mark(), fn=new Mark(); - hgen.js(js).function(fn,"newArtifact") - .text("id=document.getElementById('id');") - .text("if(id.value=='') {alert('Enter the id in box');} else {") - .text("window.open('"+CMArtiChangeForm.HREF+"?id='+id.value+'&ns="+ns+"','_self');}" - ) - .end(fn) - .function("newPassword") - .text("id=document.getElementById('id');") - .text("if(id.value=='') {alert('Enter the id in box');} else {") - .text("window.open('"+PassChangeForm.HREF+"?id='+id.value+'@"+domain+"&ns="+ns+"','_self');}" - ) - .end(js); - hgen.leaf("i","style=margin:1em 0em 1em 1em;").text("ID:").end() - .leaf("input","id=id","style=width:10%;").end().text("@").text(domain).br() - .leaf(HTMLGen.A,"class=greenbutton","href=javascript:newArtifact()","style=color:white;margin:1.2em 0em 1em 1em;").text("As Cert Artifact").end() - .leaf(HTMLGen.A,"class=greenbutton","href=javascript:newPassword()","style=color:white;margin:1.2em 0em 1em 1em;").text("w/Password").end() - ; - } - }); - } - },"class=std") - - ); - // Setting so we can get access to HTMLGen clone - model.set(this,slotCode); - } + public CredDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME, HREF, Params.values(), + new BreadCrumbs(breadcrumbs), + new Table("Cred Details",gui.env.newTransNoAvg(),model = new Model(), + slotCode = new SlotCode(false,gui.env,NAME,Params.values()) { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String ns = get(trans, Params.ns,""); + String domain = FQI.reverseDomain(ns); + Mark js = new Mark(), fn=new Mark(); + hgen.js(js).function(fn,"newArtifact") + .text("id=document.getElementById('id');") + .text("if(id.value=='') {alert('Enter the id in box');} else {") + .text("window.open('"+CMArtiChangeForm.HREF+"?id='+id.value+'&ns="+ns+"','_self');}" + ) + .end(fn) + .function("newPassword") + .text("id=document.getElementById('id');") + .text("if(id.value=='') {alert('Enter the id in box');} else {") + .text("window.open('"+PassChangeForm.HREF+"?id='+id.value+'@"+domain+"&ns="+ns+"','_self');}" + ) + .end(js); + hgen.leaf("i","style=margin:1em 0em 1em 1em;").text("ID:").end() + .leaf("input","id=id","style=width:10%;").end().text("@").text(domain).br() + .leaf(HTMLGen.A,"class=greenbutton","href=javascript:newArtifact()","style=color:white;margin:1.2em 0em 1em 1em;").text("As Cert Artifact").end() + .leaf(HTMLGen.A,"class=greenbutton","href=javascript:newPassword()","style=color:white;margin:1.2em 0em 1em 1em;").text("w/Password").end() + ; + } + }); + } + },"class=std") + + ); + // Setting so we can get access to HTMLGen clone + model.set(this,slotCode); + } - /** - * Implement the table content for Cred Detail - * - * @author Jeremiah - * - */ - private static class Model extends TableData { - private static final String STYLE_WIDTH_5 = "style=width:5%;"; - private static final String STYLE_WIDTH_10 = "style=width:10%;"; - private static final String STYLE_WIDTH_15 = "style=width:15%;"; - private static final String STYLE_WIDTH_20 = "style=width:20%;"; - private static final String STYLE_WIDTH_70 = "style=width:70%;"; - private SlotCode sc; - private CredDetail cd; - // Covering for Constructor Order - private void set(CredDetail credDetail, SlotCode slotCode) { - cd = credDetail; - sc = slotCode; - } - - @Override - public void prefix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { - } + /** + * Implement the table content for Cred Detail + * + * @author Jeremiah + * + */ + private static class Model extends TableData { + private static final String STYLE_WIDTH_5 = "style=width:5%;"; + private static final String STYLE_WIDTH_10 = "style=width:10%;"; + private static final String STYLE_WIDTH_15 = "style=width:15%;"; + private static final String STYLE_WIDTH_20 = "style=width:20%;"; + private static final String STYLE_WIDTH_70 = "style=width:70%;"; + private SlotCode sc; + private CredDetail cd; + // Covering for Constructor Order + private void set(CredDetail credDetail, SlotCode slotCode) { + cd = credDetail; + sc = slotCode; + } + + @Override + public void prefix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { + } - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String ns = sc.get(trans, Params.ns, ""); - final String id = sc.get(trans, Params.id, ""); - if(ns==null) { - return Cells.EMPTY; - } - final ArrayList rv = new ArrayList<>(); - final TimeTaken tt = trans.start("AAF Cred Details",Env.REMOTE); - List la; - try { - la = gui.cmClientAsUser(trans.getUserPrincipal(), new Retryable>() { - @Override - public List code(Rcli client)throws CadiException, ConnectException, APIException { - Future fa = client.read("/cert/artifacts?ns="+ns,gui.artifactsDF); - if(fa.get(AAFcli.timeout())) { - return fa.value.getArtifact(); - } else { - return null; - } - } + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String ns = sc.get(trans, Params.ns, ""); + final String id = sc.get(trans, Params.id, ""); + if(ns==null) { + return Cells.EMPTY; + } + final ArrayList rv = new ArrayList<>(); + final TimeTaken tt = trans.start("AAF Cred Details",Env.REMOTE); + List la; + try { + la = gui.cmClientAsUser(trans.getUserPrincipal(), new Retryable>() { + @Override + public List code(Rcli client)throws CadiException, ConnectException, APIException { + Future fa = client.read("/cert/artifacts?ns="+ns,gui.artifactsDF); + if(fa.get(AAFcli.timeout())) { + return fa.value.getArtifact(); + } else { + return null; + } + } - }); - final Set lns = new HashSet<>(); - if(la!=null) { - for(Artifact a : la){ - lns.add(a.getMechid()); - } - } - gui.clientAsUser(trans.getUserPrincipal(),new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fu = client.read("/authn/creds/ns/"+ns,gui.getDF(Users.class)); - if(fu.get(AAFcli.timeout())) { - // Organize User entries - Map>>> users = new HashMap<>(); - - List>> lmu=null; - Map> mu = null; - List lu = null; - - for (User u : fu.value.getUser()) { - if(u.getType() == 200) { - lns.remove(u.getId()); - } - lmu = users.get(u.getId()); - if(lmu==null) { - users.put(u.getId(),lmu=new ArrayList<>()); - } - mu=null; - for(Map> xmu : lmu) { - if(xmu.containsKey(u.getType())) { - mu = xmu; - } - } - - if(mu==null) { - lmu.add(mu=new HashMap<>()); - } - - lu = mu.get(u.getType()); - if(lu==null) { - mu.put(u.getType(),lu = new ArrayList<>()); - } - lu.add(u); - } + }); + final Set lns = new HashSet<>(); + if(la!=null) { + for(Artifact a : la){ + lns.add(a.getMechid()); + } + } + gui.clientAsUser(trans.getUserPrincipal(),new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fu = client.read("/authn/creds/ns/"+ns,gui.getDF(Users.class)); + if(fu.get(AAFcli.timeout())) { + // Organize User entries + Map>>> users = new HashMap<>(); + + List>> lmu=null; + Map> mu = null; + List lu = null; + + for (User u : fu.value.getUser()) { + if(u.getType() == 200) { + lns.remove(u.getId()); + } + lmu = users.get(u.getId()); + if(lmu==null) { + users.put(u.getId(),lmu=new ArrayList<>()); + } + mu=null; + for(Map> xmu : lmu) { + if(xmu.containsKey(u.getType())) { + mu = xmu; + } + } + + if(mu==null) { + lmu.add(mu=new HashMap<>()); + } + + lu = mu.get(u.getType()); + if(lu==null) { + mu.put(u.getType(),lu = new ArrayList<>()); + } + lu.add(u); + } - int count=0; - for (Entry>>> ulm : users.entrySet()) { - String key = "cred_"+count++; - StringWriter buttons = new StringWriter(); - HTMLGen hgen = cd.clone(buttons); - hgen.leaf("button","onclick=divVisibility('"+key+"');","class=button").text("Expand").end(); - - StringWriter creds = new StringWriter(); - hgen = cd.clone(creds); - Mark div = hgen.divID(key,ulm.getKey().equals(id)?"":"style=display:none;"); - for(Map> miu : ulm.getValue()) { - Mark utable = new Mark(); - hgen.leaf(utable,HTMLGen.TABLE); + int count=0; + for (Entry>>> ulm : users.entrySet()) { + String key = "cred_"+count++; + StringWriter buttons = new StringWriter(); + HTMLGen hgen = cd.clone(buttons); + hgen.leaf("button","onclick=divVisibility('"+key+"');","class=button").text("Expand").end(); + + StringWriter creds = new StringWriter(); + hgen = cd.clone(creds); + Mark div = hgen.divID(key,ulm.getKey().equals(id)?"":"style=display:none;"); + for(Map> miu : ulm.getValue()) { + Mark utable = new Mark(); + hgen.leaf(utable,HTMLGen.TABLE); - Mark uRow = new Mark(); - String cls; - boolean first = true; - - for( Entry> es : miu.entrySet()) { - Collections.sort(es.getValue(),new Comparator() { - @Override - public int compare(User u1, User u2) { - int rv = u1.getType().compareTo(u2.getType()); - return rv==0?u2.getExpires().compare(u1.getExpires()):rv; - } - }); - int xcnt = 0; - XMLGregorianCalendar oldest=null, newest=null; - String id = null; - for(User u: es.getValue()) { - if(id==null) { - id = u.getId(); - } - // Need to compile entries for Certificates on this screen - if(es.getKey()==200) { - ++xcnt; - if(oldest==null || oldest.compare(u.getExpires())<0) { - oldest = u.getExpires(); - } - if(newest==null || newest.compare(u.getExpires())<0) { - newest = u.getExpires(); - } - } else { - hgen.leaf(uRow,HTMLGen.TR); - if(first) { - hgen.leaf(HTMLGen.TD,cls="class=detailFirst",STYLE_WIDTH_10); - switch(es.getKey()) { - case 1: - case 2: hgen.text("Password"); - break; - case 10: hgen.text("Certificate"); break; - } - } else { - hgen.leaf(HTMLGen.TD,cls="class=detail",STYLE_WIDTH_10+"text-align:center;").text("\""); - } - hgen.end(); - hgen.incr(HTMLGen.TD,cls,STYLE_WIDTH_20); - - hgen.leaf(HTMLGen.A, - "class=button", - "href="+PassDeleteAction.HREF+ - "?id="+id+ - "&ns="+ns+ - "&date="+u.getExpires().toXMLFormat() + - "&type="+u.getType()) - .text("Delete").end(); - if(first && es.getKey()<10) { // Change Password Screen - hgen.leaf(HTMLGen.A,"class=button","href="+PassChangeForm.HREF+"?id="+id+"&ns="+ns) - .text("Add") - .end(); - } - first=false; - hgen.end().leaf(HTMLGen.TD,cls,STYLE_WIDTH_70) - .text(Chrono.niceDateStamp(u.getExpires())) - .end(); - - hgen.end(uRow); - } - } - if(xcnt>0) { // print compilations, if any, of Certificate - hgen.leaf(uRow,HTMLGen.TR) - .leaf(HTMLGen.TD,cls="class=detailFirst",STYLE_WIDTH_10).text("x509").end() - .leaf(HTMLGen.TD, cls,STYLE_WIDTH_20) - .leaf(HTMLGen.A,"class=button","href="+CMArtifactShow.HREF+"?id="+id+"&ns="+ns) - .text("View All") - .end(2) - .leaf(HTMLGen.TD, cls,STYLE_WIDTH_70).text(String.format( - xcnt>0?"%d Certificate%s, ranging from %s to %s" - :"%d Certificate%s", - xcnt, - xcnt==1?"":"s", - Chrono.niceDateStamp(oldest), - Chrono.niceDateStamp(newest))) - .end(uRow); - - } - } - hgen.end(utable); - } - - hgen.end(div); + Mark uRow = new Mark(); + String cls; + boolean first = true; + + for( Entry> es : miu.entrySet()) { + Collections.sort(es.getValue(),new Comparator() { + @Override + public int compare(User u1, User u2) { + int rv = u1.getType().compareTo(u2.getType()); + return rv==0?u2.getExpires().compare(u1.getExpires()):rv; + } + }); + int xcnt = 0; + XMLGregorianCalendar oldest=null, newest=null; + String id = null; + for(User u: es.getValue()) { + if(id==null) { + id = u.getId(); + } + // Need to compile entries for Certificates on this screen + if(es.getKey()==200) { + ++xcnt; + if(oldest==null || oldest.compare(u.getExpires())<0) { + oldest = u.getExpires(); + } + if(newest==null || newest.compare(u.getExpires())<0) { + newest = u.getExpires(); + } + } else { + hgen.leaf(uRow,HTMLGen.TR); + if(first) { + hgen.leaf(HTMLGen.TD,cls="class=detailFirst",STYLE_WIDTH_10); + switch(es.getKey()) { + case 1: + case 2: hgen.text("Password"); + break; + case 10: hgen.text("Certificate"); break; + } + } else { + hgen.leaf(HTMLGen.TD,cls="class=detail",STYLE_WIDTH_10+"text-align:center;").text("\""); + } + hgen.end(); + hgen.incr(HTMLGen.TD,cls,STYLE_WIDTH_20); + + hgen.leaf(HTMLGen.A, + "class=button", + "href="+PassDeleteAction.HREF+ + "?id="+id+ + "&ns="+ns+ + "&date="+u.getExpires().toXMLFormat() + + "&type="+u.getType()) + .text("Delete").end(); + if(first && es.getKey()<10) { // Change Password Screen + hgen.leaf(HTMLGen.A,"class=button","href="+PassChangeForm.HREF+"?id="+id+"&ns="+ns) + .text("Add") + .end(); + } + first=false; + hgen.end().leaf(HTMLGen.TD,cls,STYLE_WIDTH_70) + .text(Chrono.niceDateStamp(u.getExpires())) + .end(); + + hgen.end(uRow); + } + } + if(xcnt>0) { // print compilations, if any, of Certificate + hgen.leaf(uRow,HTMLGen.TR) + .leaf(HTMLGen.TD,cls="class=detailFirst",STYLE_WIDTH_10).text("x509").end() + .leaf(HTMLGen.TD, cls,STYLE_WIDTH_20) + .leaf(HTMLGen.A,"class=button","href="+CMArtifactShow.HREF+"?id="+id+"&ns="+ns) + .text("View All") + .end(2) + .leaf(HTMLGen.TD, cls,STYLE_WIDTH_70).text(String.format( + xcnt>0?"%d Certificate%s, ranging from %s to %s" + :"%d Certificate%s", + xcnt, + xcnt==1?"":"s", + Chrono.niceDateStamp(oldest), + Chrono.niceDateStamp(newest))) + .end(uRow); + + } + } + hgen.end(utable); + } + + hgen.end(div); - rv.add(new AbsCell[] { - new TextCell(ulm.getKey(),STYLE_WIDTH_15), - new TextCell(buttons.toString(),STYLE_WIDTH_5), - new TextCell(creds.toString(),STYLE_WIDTH_70) - }); - } - for(String missing : lns) { - StringWriter buttons = new StringWriter(); - HTMLGen hgen = cd.clone(buttons); - hgen.leaf(HTMLGen.A,"class=button","href="+CMArtifactShow.HREF+"?id="+missing+"&ns="+ns) - .text("View All") - .end(2); - rv.add(new AbsCell[] { - new TextCell(missing,STYLE_WIDTH_15), - new TextCell(buttons.toString(),STYLE_WIDTH_5), - new TextCell("No X509 Credential Instantiated") - }); - } + rv.add(new AbsCell[] { + new TextCell(ulm.getKey(),STYLE_WIDTH_15), + new TextCell(buttons.toString(),STYLE_WIDTH_5), + new TextCell(creds.toString(),STYLE_WIDTH_70) + }); + } + for(String missing : lns) { + StringWriter buttons = new StringWriter(); + HTMLGen hgen = cd.clone(buttons); + hgen.leaf(HTMLGen.A,"class=button","href="+CMArtifactShow.HREF+"?id="+missing+"&ns="+ns) + .text("View All") + .end(2); + rv.add(new AbsCell[] { + new TextCell(missing,STYLE_WIDTH_15), + new TextCell(buttons.toString(),STYLE_WIDTH_5), + new TextCell("No X509 Credential Instantiated") + }); + } - } else { - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); - } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(); - } finally { - tt.done(); - } - return new Cells(rv,null); - } + } else { + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); + } + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(); + } finally { + tt.done(); + } + return new Cells(rv,null); + } - @Override - public void postfix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { - } + @Override + public void postfix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { + } - } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java index caad42b5..e0a73dca 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java @@ -36,42 +36,42 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; public class Home extends Page { - public static final String HREF = "/gui/home"; - public Home(final AAF_GUI gui) throws APIException, IOException { - super(gui.env,"Home",HREF, NO_FIELDS, new NamedCode(false,"content") { - @Override - public void code(final Cache cache, final HTMLGen xgen) throws APIException, IOException { -// // TEMP -// JSGen jsg = xgen.js(); -// jsg.function("httpPost","sURL","sParam") -// .text("var oURL = new java.net.URL(sURL)") -// .text("var oConn = oURL.openConnection();") -// .text("oConn.setDoInput(true);") -// .text("oConn.setDoOutpu(true);") -// .text("oConn.setUseCaches(false);") -// .text("oConn.setRequestProperty(\"Content-Type\",\"application/x-www-form-urlencoded\");") -// .text(text) -// jsg.done(); - // TEMP - final Mark pages = xgen.divID("Pages"); - xgen.leaf(H3).text("Choose from the following:").end() - .leaf(A,"href=myperms").text("My Permissions").end() - .leaf(A,"href=myroles").text("My Roles").end() - // TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page - .leaf(A,"href=ns").text("My Namespaces").end() - .leaf(A,"href=approve").text("My Approvals").end() - .leaf(A, "href=myrequests").text("My Pending Requests").end() - // Enable later -// .leaf(A, "href=onboard").text("Onboarding").end() - // Password Change. If logged in as CSP/GSO, go to their page - .leaf(A,"href=passwd").text("Password Management").end() - .leaf(A,"href=cui").text("Command Prompt").end() - .leaf(A,"href=api").text("AAF API").end() - ; - - xgen.end(pages); - } - }); - } + public static final String HREF = "/gui/home"; + public Home(final AAF_GUI gui) throws APIException, IOException { + super(gui.env,"Home",HREF, NO_FIELDS, new NamedCode(false,"content") { + @Override + public void code(final Cache cache, final HTMLGen xgen) throws APIException, IOException { +// // TEMP +// JSGen jsg = xgen.js(); +// jsg.function("httpPost","sURL","sParam") +// .text("var oURL = new java.net.URL(sURL)") +// .text("var oConn = oURL.openConnection();") +// .text("oConn.setDoInput(true);") +// .text("oConn.setDoOutpu(true);") +// .text("oConn.setUseCaches(false);") +// .text("oConn.setRequestProperty(\"Content-Type\",\"application/x-www-form-urlencoded\");") +// .text(text) +// jsg.done(); + // TEMP + final Mark pages = xgen.divID("Pages"); + xgen.leaf(H3).text("Choose from the following:").end() + .leaf(A,"href=myperms").text("My Permissions").end() + .leaf(A,"href=myroles").text("My Roles").end() + // TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page + .leaf(A,"href=ns").text("My Namespaces").end() + .leaf(A,"href=approve").text("My Approvals").end() + .leaf(A, "href=myrequests").text("My Pending Requests").end() + // Enable later +// .leaf(A, "href=onboard").text("Onboarding").end() + // Password Change. If logged in as CSP/GSO, go to their page + .leaf(A,"href=passwd").text("Password Management").end() + .leaf(A,"href=cui").text("Command Prompt").end() + .leaf(A,"href=api").text("AAF API").end() + ; + + xgen.end(pages); + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java index 7dcc65aa..5b614edc 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java @@ -38,78 +38,78 @@ import org.onap.aaf.misc.xgen.Mark; import org.onap.aaf.misc.xgen.html.HTMLGen; public class LoginLanding extends Page { - public static final String HREF = "/login"; - static final String NAME = "Login"; - static final String fields[] = {"id","password","environment"}; - static final String envs[] = {"DEV","TEST","PROD"}; - - public LoginLanding(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME,HREF, fields, new NamedCode(true, "content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - hgen.leaf("p").text("No login credentials are found in your current session. " + - "Choose your preferred login option to continue.").end(); - - Mark loginPaths = hgen.divID("Pages"); - - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI authGUI, AuthzTrans trans, Cache cache, HTMLGen xgen) throws APIException, IOException { - HttpServletRequest req = trans.get(gui.slot_httpServletRequest, null); - if(req!=null) { - String query = req.getQueryString(); - if(query!=null) { - for(String qs : query.split("&")) { - int equals = qs.indexOf('='); - xgen.leaf(HTMLGen.A, "href="+URLDecoder.decode(qs.substring(equals+1),Config.UTF_8)).text(qs.substring(0,equals).replace('_', ' ')).end(); - } - } - } - xgen.leaf(HTMLGen.A, "href=gui/home?Authentication=BasicAuth").text("AAF Basic Auth").end(); - } - }); -// hgen.leaf("a", "href=#","onclick=divVisibility('cso');").text("Global Login").end() -// .incr("p", "id=cso","style=display:none").text("this will redirect to global login").end() -// .leaf("a", "href=#","onclick=divVisibility('tguard');").text("tGuard").end() -// .incr("p", "id=tguard","style=display:none").text("this will redirect to tGuard login").end() -// hgen.leaf("a", "href=#","onclick=divVisibility('basicauth');").text("AAF Basic Auth").end(); - hgen.end(loginPaths); - -// hgen.incr("form","method=post","style=display:none","id=basicauth","gui/home?Authentication=BasicAuth"); -// Mark table = new Mark(TABLE); -// hgen.incr(table); -// cache.dynamic(hgen, new DynamicCode() { -// @Override -// public void code(final AuthGUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) -// throws APIException, IOException { -// hgen -// .input(fields[0],"Username",true) -// .input(fields[1],"Password",true, "type=password"); -// Mark selectRow = new Mark(); -// hgen -// .incr(selectRow, "tr") -// .incr("td") -// .incr("label", "for=envs", "required").text("Environment").end() -// .end() -// .incr("td") -// .incr("select", "name=envs", "id=envs", "required") -// .incr("option", "value=").text("Select Environment").end(); -// for (String env : envs) { -// hgen.incr("option", "value="+env).text(env).end(); -// } -// hgen -// .end(selectRow) - -// hgen.end(); -// } -// }); -// hgen.end(); -// hgen.tagOnly("input", "type=submit", "value=Submit") -// .tagOnly("input", "type=reset", "value=Reset") -// .end(); - + public static final String HREF = "/login"; + static final String NAME = "Login"; + static final String fields[] = {"id","password","environment"}; + static final String envs[] = {"DEV","TEST","PROD"}; + + public LoginLanding(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME,HREF, fields, new NamedCode(true, "content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + hgen.leaf("p").text("No login credentials are found in your current session. " + + "Choose your preferred login option to continue.").end(); + + Mark loginPaths = hgen.divID("Pages"); + + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI authGUI, AuthzTrans trans, Cache cache, HTMLGen xgen) throws APIException, IOException { + HttpServletRequest req = trans.get(gui.slot_httpServletRequest, null); + if(req!=null) { + String query = req.getQueryString(); + if(query!=null) { + for(String qs : query.split("&")) { + int equals = qs.indexOf('='); + xgen.leaf(HTMLGen.A, "href="+URLDecoder.decode(qs.substring(equals+1),Config.UTF_8)).text(qs.substring(0,equals).replace('_', ' ')).end(); + } + } + } + xgen.leaf(HTMLGen.A, "href=gui/home?Authentication=BasicAuth").text("AAF Basic Auth").end(); + } + }); +// hgen.leaf("a", "href=#","onclick=divVisibility('cso');").text("Global Login").end() +// .incr("p", "id=cso","style=display:none").text("this will redirect to global login").end() +// .leaf("a", "href=#","onclick=divVisibility('tguard');").text("tGuard").end() +// .incr("p", "id=tguard","style=display:none").text("this will redirect to tGuard login").end() +// hgen.leaf("a", "href=#","onclick=divVisibility('basicauth');").text("AAF Basic Auth").end(); + hgen.end(loginPaths); + +// hgen.incr("form","method=post","style=display:none","id=basicauth","gui/home?Authentication=BasicAuth"); +// Mark table = new Mark(TABLE); +// hgen.incr(table); +// cache.dynamic(hgen, new DynamicCode() { +// @Override +// public void code(final AuthGUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) +// throws APIException, IOException { +// hgen +// .input(fields[0],"Username",true) +// .input(fields[1],"Password",true, "type=password"); +// Mark selectRow = new Mark(); +// hgen +// .incr(selectRow, "tr") +// .incr("td") +// .incr("label", "for=envs", "required").text("Environment").end() +// .end() +// .incr("td") +// .incr("select", "name=envs", "id=envs", "required") +// .incr("option", "value=").text("Select Environment").end(); +// for (String env : envs) { +// hgen.incr("option", "value="+env).text(env).end(); +// } +// hgen +// .end(selectRow) + +// hgen.end(); +// } +// }); +// hgen.end(); +// hgen.tagOnly("input", "type=submit", "value=Submit") +// .tagOnly("input", "type=reset", "value=Reset") +// .end(); + - } - }); - } + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLandingAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLandingAction.java index 9ab3fa71..f20caebb 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLandingAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLandingAction.java @@ -35,31 +35,31 @@ import org.onap.aaf.misc.xgen.DynamicCode; import org.onap.aaf.misc.xgen.html.HTMLGen; public class LoginLandingAction extends Page { - public LoginLandingAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,"Login",LoginLanding.HREF, LoginLanding.fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - final Slot sID = gui.env.slot(LoginLanding.NAME+'.'+LoginLanding.fields[0]); -// final Slot sPassword = gui.env.slot(LoginLanding.NAME+'.'+LoginLanding.fields[1]); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String username = trans.get(sID,null); -// String password = trans.get(sPassword,null); + public LoginLandingAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,"Login",LoginLanding.HREF, LoginLanding.fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + final Slot sID = gui.env.slot(LoginLanding.NAME+'.'+LoginLanding.fields[0]); +// final Slot sPassword = gui.env.slot(LoginLanding.NAME+'.'+LoginLanding.fields[1]); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String username = trans.get(sID,null); +// String password = trans.get(sPassword,null); - hgen.p("User: "+username); - hgen.p("Pass: ********"); - - // TODO: clarification from JG - // put in request header? - // then pass through authn/basicAuth call? - - } - }); - } - }); - } + hgen.p("User: "+username); + hgen.p("Pass: ********"); + + // TODO: clarification from JG + // put in request header? + // then pass through authn/basicAuth call? + + } + }); + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java index 0a74d607..faf657e7 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java @@ -58,187 +58,187 @@ import aaf.v2_0.Role; import aaf.v2_0.Roles; public class NsDetail extends Page { - - public static final String HREF = "/gui/nsdetail"; - public static final String NAME = "NsDetail"; - public static enum NS_FIELD { OWNERS, ADMINS, ROLES, PERMISSIONS, CREDS}; - private static final String BLANK = ""; - private static Slot keySlot; - private static Model model; - private static String gw_url; - - - public NsDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME, HREF, new String[] {"ns"}, - new BreadCrumbs(breadcrumbs), - new Table("Namespace Details",gui.env.newTransNoAvg(),model=new Model(),"class=detail") - ); - model.set(this); - keySlot = gui.env.slot(NAME+".ns"); - gw_url = gui.env.getProperty(Config.GW_URL); - if(gw_url==null) { - gw_url=""; - } else { - gw_url+="/aaf/2.0"; - } - } - - /** - * Implement the table content for Namespace Detail - * - * @author Jeremiah - * - */ - private static class Model extends TableData { - private NsDetail nd; - - public void set(NsDetail nsDetail) { - nd=nsDetail; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String nsName = trans.get(keySlot, null); - Validator v = new Validator(); - v.ns(nsName); - if(v.err()) { - trans.warn().printf("Error in NsDetail Request: %s", v.errs()); - return Cells.EMPTY; - } - - if(nsName==null) { - return Cells.EMPTY; - } - final ArrayList rv = new ArrayList<>(); - rv.add(new AbsCell[]{new TextCell("Name:"),new TextCell(nsName)}); - - final TimeTaken tt = trans.start("AAF Namespace Details",Env.REMOTE); - try { - gui.clientAsUser(trans.getUserPrincipal(),new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fn = client.read("/authz/nss/"+nsName,gui.getDF(Nss.class)); - - if(fn.get(AAF_GUI.TIMEOUT)) { - tt.done(); - try { -// TimeTaken tt = trans.start("Load Data", Env.SUB); - - for(Ns n : fn.value.getNs()) { - String desc = (n.getDescription()!=null?n.getDescription():BLANK); - rv.add(new AbsCell[]{new TextCell("Description:"),new TextCell(desc)}); - - addField(trans, nsName, rv, n.getAdmin(), NS_FIELD.ADMINS); - addField(trans, nsName, rv, n.getResponsible(), NS_FIELD.OWNERS); - - StringWriter sw = new StringWriter(); - HTMLGen hgen = nd.clone(sw); - hgen.leaf(HTMLGen.A, "class=greenbutton","href="+CredDetail.HREF+"?ns="+nsName).text("Cred Details").end(); - rv.add(new AbsCell[] { - new TextCell("Credentials"), - new TextCell(sw.toString()) - }); - - - Future fr = client.read( - "/authz/roles/ns/"+nsName, - gui.getDF(Roles.class) - ); - List roles = new ArrayList<>(); - if(fr.get(AAFcli.timeout())) { - for (Role r : fr.value.getRole()) { - roles.add(r.getName()); - } - } - addField(trans, nsName, rv, roles, NS_FIELD.ROLES); - - - Future fp = client.read( - "/authz/perms/ns/"+nsName, - gui.getDF(Perms.class) - ); - List perms = new ArrayList<>(); - - if(fp.get(AAFcli.timeout())) { - for (Perm p : fp.value.getPerm()) { - perms.add(p.getType() + "|" + p.getInstance() + "|" + p.getAction()); - } - } - addField(trans, nsName, rv, perms, NS_FIELD.PERMISSIONS); - } - String historyLink = NsHistory.HREF - + "?name=" + nsName; - rv.add(new AbsCell[] {new RefCell("See History",historyLink,false)}); - } finally { - tt.done(); - } - } else { - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); - } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(); - } finally { - tt.done(); - } - return new Cells(rv,null); - } - - private void addField(AuthzTrans trans, String ns, List rv, List values, NS_FIELD field) { - if (!values.isEmpty()) { - switch(field) { - case OWNERS: - case ADMINS: - case CREDS: - for (int i=0; i< values.size(); i++) { - AbsCell label = (i==0?new TextCell(sentenceCase(field)+":"):AbsCell.Null); - String user = values.get(i); - AbsCell userCell = (new TextCell(user)); - rv.add(new AbsCell[] { - label, - userCell - }); - } - break; - case ROLES: - for (int i=0; i< values.size(); i++) { - String role = values.get(i); - AbsCell label = (i==0?new TextCell(sentenceCase(field)+":"):AbsCell.Null); - rv.add(new AbsCell[] { - label, - new RefCell(role,RoleDetail.HREF+"?role="+role+"&ns="+ns,false) - }); - } - break; - case PERMISSIONS: - for (int i=0; i< values.size(); i++) { - AbsCell label = (i==0?new TextCell(sentenceCase(field)+":","style=width:20%"):AbsCell.Null); - String perm = values.get(i); - String[] fields = perm.split("\\|"); - String grantLink = gw_url - + PermGrantForm.HREF - + "?type=" + fields[0].trim() - + "&instance=" + fields[1].trim() - + "&action=" + fields[2].trim(); - - rv.add(new AbsCell[] { - label, - new TextCell(perm,"style=width:60%;"), - new RefCell("Grant", grantLink,false,"class=button","style=width:20%;") - }); - } - break; - } - - } - } - - private String sentenceCase(NS_FIELD field) { - String sField = field.toString(); - return sField.substring(0, 1).toUpperCase() + sField.substring(1).toLowerCase(); - } - - } + + public static final String HREF = "/gui/nsdetail"; + public static final String NAME = "NsDetail"; + public static enum NS_FIELD { OWNERS, ADMINS, ROLES, PERMISSIONS, CREDS}; + private static final String BLANK = ""; + private static Slot keySlot; + private static Model model; + private static String gw_url; + + + public NsDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME, HREF, new String[] {"ns"}, + new BreadCrumbs(breadcrumbs), + new Table("Namespace Details",gui.env.newTransNoAvg(),model=new Model(),"class=detail") + ); + model.set(this); + keySlot = gui.env.slot(NAME+".ns"); + gw_url = gui.env.getProperty(Config.GW_URL); + if(gw_url==null) { + gw_url=""; + } else { + gw_url+="/aaf/2.0"; + } + } + + /** + * Implement the table content for Namespace Detail + * + * @author Jeremiah + * + */ + private static class Model extends TableData { + private NsDetail nd; + + public void set(NsDetail nsDetail) { + nd=nsDetail; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String nsName = trans.get(keySlot, null); + Validator v = new Validator(); + v.ns(nsName); + if(v.err()) { + trans.warn().printf("Error in NsDetail Request: %s", v.errs()); + return Cells.EMPTY; + } + + if(nsName==null) { + return Cells.EMPTY; + } + final ArrayList rv = new ArrayList<>(); + rv.add(new AbsCell[]{new TextCell("Name:"),new TextCell(nsName)}); + + final TimeTaken tt = trans.start("AAF Namespace Details",Env.REMOTE); + try { + gui.clientAsUser(trans.getUserPrincipal(),new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fn = client.read("/authz/nss/"+nsName,gui.getDF(Nss.class)); + + if(fn.get(AAF_GUI.TIMEOUT)) { + tt.done(); + try { +// TimeTaken tt = trans.start("Load Data", Env.SUB); + + for(Ns n : fn.value.getNs()) { + String desc = (n.getDescription()!=null?n.getDescription():BLANK); + rv.add(new AbsCell[]{new TextCell("Description:"),new TextCell(desc)}); + + addField(trans, nsName, rv, n.getAdmin(), NS_FIELD.ADMINS); + addField(trans, nsName, rv, n.getResponsible(), NS_FIELD.OWNERS); + + StringWriter sw = new StringWriter(); + HTMLGen hgen = nd.clone(sw); + hgen.leaf(HTMLGen.A, "class=greenbutton","href="+CredDetail.HREF+"?ns="+nsName).text("Cred Details").end(); + rv.add(new AbsCell[] { + new TextCell("Credentials"), + new TextCell(sw.toString()) + }); + + + Future fr = client.read( + "/authz/roles/ns/"+nsName, + gui.getDF(Roles.class) + ); + List roles = new ArrayList<>(); + if(fr.get(AAFcli.timeout())) { + for (Role r : fr.value.getRole()) { + roles.add(r.getName()); + } + } + addField(trans, nsName, rv, roles, NS_FIELD.ROLES); + + + Future fp = client.read( + "/authz/perms/ns/"+nsName, + gui.getDF(Perms.class) + ); + List perms = new ArrayList<>(); + + if(fp.get(AAFcli.timeout())) { + for (Perm p : fp.value.getPerm()) { + perms.add(p.getType() + "|" + p.getInstance() + "|" + p.getAction()); + } + } + addField(trans, nsName, rv, perms, NS_FIELD.PERMISSIONS); + } + String historyLink = NsHistory.HREF + + "?name=" + nsName; + rv.add(new AbsCell[] {new RefCell("See History",historyLink,false)}); + } finally { + tt.done(); + } + } else { + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); + } + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(); + } finally { + tt.done(); + } + return new Cells(rv,null); + } + + private void addField(AuthzTrans trans, String ns, List rv, List values, NS_FIELD field) { + if (!values.isEmpty()) { + switch(field) { + case OWNERS: + case ADMINS: + case CREDS: + for (int i=0; i< values.size(); i++) { + AbsCell label = (i==0?new TextCell(sentenceCase(field)+":"):AbsCell.Null); + String user = values.get(i); + AbsCell userCell = (new TextCell(user)); + rv.add(new AbsCell[] { + label, + userCell + }); + } + break; + case ROLES: + for (int i=0; i< values.size(); i++) { + String role = values.get(i); + AbsCell label = (i==0?new TextCell(sentenceCase(field)+":"):AbsCell.Null); + rv.add(new AbsCell[] { + label, + new RefCell(role,RoleDetail.HREF+"?role="+role+"&ns="+ns,false) + }); + } + break; + case PERMISSIONS: + for (int i=0; i< values.size(); i++) { + AbsCell label = (i==0?new TextCell(sentenceCase(field)+":","style=width:20%"):AbsCell.Null); + String perm = values.get(i); + String[] fields = perm.split("\\|"); + String grantLink = gw_url + + PermGrantForm.HREF + + "?type=" + fields[0].trim() + + "&instance=" + fields[1].trim() + + "&action=" + fields[2].trim(); + + rv.add(new AbsCell[] { + label, + new TextCell(perm,"style=width:60%;"), + new RefCell("Grant", grantLink,false,"class=button","style=width:20%;") + }); + } + break; + } + + } + } + + private String sentenceCase(NS_FIELD field) { + String sField = field.toString(); + return sField.substring(0, 1).toUpperCase() + sField.substring(1).toLowerCase(); + } + + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java index 6d55858b..7d11e66f 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java @@ -55,174 +55,174 @@ import aaf.v2_0.History; import aaf.v2_0.History.Item; public class NsHistory extends Page { - static final String NAME="NsHistory"; - static final String HREF = "/gui/nsHistory"; - static final String FIELDS[] = {"name","dates"}; - static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; - static enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, - AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; - - public NsHistory(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, FIELDS, - new BreadCrumbs(breadcrumbs), - new Table("History", gui.env.newTransNoAvg(),new Model(gui.env),"class=std"), - new NamedCode(true, "content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final Slot name = gui.env.slot(NAME+".name"); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String obName = trans.get(name, null); - - // Use Javascript to make the table title more descriptive - hgen.js() - .text("var caption = document.querySelector(\".title\");") - .text("caption.innerHTML='History for Namespace [ " + obName + " ]';") - .done(); - - // Use Javascript to change Link Target to our last visited Detail page - String lastPage = NsDetail.HREF + "?name=" + obName; - hgen.js() - .text("alterLink('nsdetail', '"+lastPage + "');") - .done(); - - hgen.br(); - hgen.leaf("a","href=#advanced_search","onclick=divVisibility('advanced_search');").text("Advanced Search").end() - .divID("advanced_search", "style=display:none"); - hgen.incr("table"); - - addDateRow(hgen,"Start Date"); - addDateRow(hgen,"End Date"); - hgen.incr("tr").incr("td"); - hgen.tagOnly("input", "type=button","value=Get History", - "onclick=datesURL('"+HREF+"?name=" + obName+"');"); - hgen.end().end(); - hgen.end(); - hgen.end(); - - } - }); - } - } + static final String NAME="NsHistory"; + static final String HREF = "/gui/nsHistory"; + static final String FIELDS[] = {"name","dates"}; + static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; + static enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, + AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; + + public NsHistory(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, FIELDS, + new BreadCrumbs(breadcrumbs), + new Table("History", gui.env.newTransNoAvg(),new Model(gui.env),"class=std"), + new NamedCode(true, "content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final Slot name = gui.env.slot(NAME+".name"); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String obName = trans.get(name, null); + + // Use Javascript to make the table title more descriptive + hgen.js() + .text("var caption = document.querySelector(\".title\");") + .text("caption.innerHTML='History for Namespace [ " + obName + " ]';") + .done(); + + // Use Javascript to change Link Target to our last visited Detail page + String lastPage = NsDetail.HREF + "?name=" + obName; + hgen.js() + .text("alterLink('nsdetail', '"+lastPage + "');") + .done(); + + hgen.br(); + hgen.leaf("a","href=#advanced_search","onclick=divVisibility('advanced_search');").text("Advanced Search").end() + .divID("advanced_search", "style=display:none"); + hgen.incr("table"); + + addDateRow(hgen,"Start Date"); + addDateRow(hgen,"End Date"); + hgen.incr("tr").incr("td"); + hgen.tagOnly("input", "type=button","value=Get History", + "onclick=datesURL('"+HREF+"?name=" + obName+"');"); + hgen.end().end(); + hgen.end(); + hgen.end(); + + } + }); + } + } - ); - } + ); + } - private static void addDateRow(HTMLGen hgen, String s) { - hgen - .incr("tr") - .incr("td") - .incr("label", "for=month", "required").text(s+"*").end() - .end() - .incr("td") - .incr("select", "name=month"+s.substring(0, s.indexOf(' ')), "id=month"+s.substring(0, s.indexOf(' ')), "required") - .incr("option", "value=").text("Month").end(); - for (Month m : Month.values()) { - if (Calendar.getInstance().get(Calendar.MONTH) == m.ordinal()) { - hgen.incr("option", "selected", "value="+(m.ordinal()+1)).text(m.name()).end(); - } else { - hgen.incr("option", "value="+(m.ordinal()+1)).text(m.name()).end(); - } - } - hgen.end() - .end() - .incr("td") - .tagOnly("input","type=number","id=year"+s.substring(0, s.indexOf(' ')),"required", - "value="+Calendar.getInstance().get(Calendar.YEAR), "min=1900", - "max="+Calendar.getInstance().get(Calendar.YEAR), - "placeholder=Year").end() - .end(); - } - + private static void addDateRow(HTMLGen hgen, String s) { + hgen + .incr("tr") + .incr("td") + .incr("label", "for=month", "required").text(s+"*").end() + .end() + .incr("td") + .incr("select", "name=month"+s.substring(0, s.indexOf(' ')), "id=month"+s.substring(0, s.indexOf(' ')), "required") + .incr("option", "value=").text("Month").end(); + for (Month m : Month.values()) { + if (Calendar.getInstance().get(Calendar.MONTH) == m.ordinal()) { + hgen.incr("option", "selected", "value="+(m.ordinal()+1)).text(m.name()).end(); + } else { + hgen.incr("option", "value="+(m.ordinal()+1)).text(m.name()).end(); + } + } + hgen.end() + .end() + .incr("td") + .tagOnly("input","type=number","id=year"+s.substring(0, s.indexOf(' ')),"required", + "value="+Calendar.getInstance().get(Calendar.YEAR), "min=1900", + "max="+Calendar.getInstance().get(Calendar.YEAR), + "placeholder=Year").end() + .end(); + } + - - - /** - * Implement the Table Content for History - * - * @author Jeremiah - * - */ - private static class Model extends TableData { - private static final String[] headers = new String[] {"Date","User","Memo"}; - private Slot name; - private Slot dates; - - public Model(AuthzEnv env) { - name = env.slot(NAME+".name"); - dates = env.slot(NAME+".dates"); - } - - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String oName = trans.get(name,null); - final String oDates = trans.get(dates,null); - - if(oName==null) { - return Cells.EMPTY; - } - - final ArrayList rv = new ArrayList<>(); - String msg = null; - final TimeTaken tt = trans.start("AAF Get History for Namespace ["+oName+"]",Env.REMOTE); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - if (oDates != null) { - client.setQueryParams("yyyymm="+oDates); - } - Future fh = client.read("/authz/hist/ns/"+oName,gui.getDF(History.class)); - if (fh.get(AAF_GUI.TIMEOUT)) { - tt.done(); - TimeTaken tt2 = trans.start("Load History Data", Env.SUB); - try { - List histItems = fh.value.getItem(); - - java.util.Collections.sort(histItems, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return o2.getTimestamp().compare(o1.getTimestamp()); - } - }); - - for (Item i : histItems) { - String user = i.getUser(); - AbsCell userCell = new TextCell(user); - - String memo = i.getMemo().replace("", "</script>"); - rv.add(new AbsCell[] { - new TextCell(i.getTimestamp().toGregorianCalendar().getTime().toString()), - userCell, - new TextCell(memo) - }); - } - } finally { - tt2.done(); - } - } else { - if (fh.code()==403) { - rv.add(new AbsCell[] {new TextCell("You may not view History of Namespace [" + oName + "]", "colspan = 3", "class=center")}); - } else { - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***", "colspan = 3", "class=center")}); - } - } - return null; - } - }); - } catch (Exception e) { - trans.error().log(e); - } finally { - tt.done(); - } - return new Cells(rv,msg); - } - } + + + /** + * Implement the Table Content for History + * + * @author Jeremiah + * + */ + private static class Model extends TableData { + private static final String[] headers = new String[] {"Date","User","Memo"}; + private Slot name; + private Slot dates; + + public Model(AuthzEnv env) { + name = env.slot(NAME+".name"); + dates = env.slot(NAME+".dates"); + } + + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String oName = trans.get(name,null); + final String oDates = trans.get(dates,null); + + if(oName==null) { + return Cells.EMPTY; + } + + final ArrayList rv = new ArrayList<>(); + String msg = null; + final TimeTaken tt = trans.start("AAF Get History for Namespace ["+oName+"]",Env.REMOTE); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + if (oDates != null) { + client.setQueryParams("yyyymm="+oDates); + } + Future fh = client.read("/authz/hist/ns/"+oName,gui.getDF(History.class)); + if (fh.get(AAF_GUI.TIMEOUT)) { + tt.done(); + TimeTaken tt2 = trans.start("Load History Data", Env.SUB); + try { + List histItems = fh.value.getItem(); + + java.util.Collections.sort(histItems, new Comparator() { + @Override + public int compare(Item o1, Item o2) { + return o2.getTimestamp().compare(o1.getTimestamp()); + } + }); + + for (Item i : histItems) { + String user = i.getUser(); + AbsCell userCell = new TextCell(user); + + String memo = i.getMemo().replace("", "</script>"); + rv.add(new AbsCell[] { + new TextCell(i.getTimestamp().toGregorianCalendar().getTime().toString()), + userCell, + new TextCell(memo) + }); + } + } finally { + tt2.done(); + } + } else { + if (fh.code()==403) { + rv.add(new AbsCell[] {new TextCell("You may not view History of Namespace [" + oName + "]", "colspan = 3", "class=center")}); + } else { + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***", "colspan = 3", "class=center")}); + } + } + return null; + } + }); + } catch (Exception e) { + trans.error().log(e); + } finally { + tt.done(); + } + return new Cells(rv,msg); + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java index 4328653e..8a2da3d3 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java @@ -46,113 +46,113 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; import aaf.v2_0.CredRequest; public class NsInfoAction extends Page { - public NsInfoAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,"Onboard",PassChangeForm.HREF, PassChangeForm.fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - final Slot sID = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[0]); - final Slot sCurrPass = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[1]); - final Slot sPassword = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[2]); - final Slot sPassword2 = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[3]); - final Slot startDate = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[4]); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String id = trans.get(sID,null); - String currPass = trans.get(sCurrPass,null); - final String password = trans.get(sPassword,null); - String password2 = trans.get(sPassword2,null); - - // Run Validations - boolean fail = true; - - if (id==null || id.indexOf('@')<=0) { - hgen.p("Data Entry Failure: Please enter a valid ID, including domain."); - } else if(password == null || password2 == null || currPass == null) { - hgen.p("Data Entry Failure: Both Password Fields need entries."); - } else if(!password.equals(password2)) { - hgen.p("Data Entry Failure: Passwords do not match."); - } else { // everything else is checked by Server - final CredRequest cred = new CredRequest(); - cred.setId(id); - cred.setPassword(currPass); - try { - fail = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client)throws CadiException, ConnectException, APIException { - TimeTaken tt = trans.start("Check Current Password",Env.REMOTE); - try { - Future fcr = client.create( // Note: Need "Post", because of hiding password in SSL Data - "/authn/validate", - gui.getDF(CredRequest.class), - cred - ); - boolean go; - boolean fail = true; - fcr.get(5000); - if(fcr.code() == 200) { - hgen.p("Current Password validated"); - go = true; - } else { - hgen.p(String.format("Invalid Current Password: %d %s",fcr.code(),fcr.body())); - go = false; - } - if(go) { - tt.done(); - tt = trans.start("AAF Change Password",Env.REMOTE); - try { - // Change over Cred to reset mode - cred.setPassword(password); - String start = trans.get(startDate, null); - if(start!=null) { - try { - cred.setStart(Chrono.timeStamp(Chrono.dateOnlyFmt.parse(start))); - } catch (ParseException e) { - throw new CadiException(e); - } - } - - fcr = client.create( - "/authn/cred", - gui.getDF(CredRequest.class), - cred - ); - - if(fcr.get(5000)) { - // Do Remote Call - hgen.p("New Password has been added."); - fail = false; - } else { - gui.writeError(trans, fcr, hgen, 0); - } - } finally { - tt.done(); - } - } - return fail; - } finally { - tt.done(); - } - } - }); + public NsInfoAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,"Onboard",PassChangeForm.HREF, PassChangeForm.fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + final Slot sID = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[0]); + final Slot sCurrPass = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[1]); + final Slot sPassword = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[2]); + final Slot sPassword2 = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[3]); + final Slot startDate = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[4]); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String id = trans.get(sID,null); + String currPass = trans.get(sCurrPass,null); + final String password = trans.get(sPassword,null); + String password2 = trans.get(sPassword2,null); + + // Run Validations + boolean fail = true; + + if (id==null || id.indexOf('@')<=0) { + hgen.p("Data Entry Failure: Please enter a valid ID, including domain."); + } else if(password == null || password2 == null || currPass == null) { + hgen.p("Data Entry Failure: Both Password Fields need entries."); + } else if(!password.equals(password2)) { + hgen.p("Data Entry Failure: Passwords do not match."); + } else { // everything else is checked by Server + final CredRequest cred = new CredRequest(); + cred.setId(id); + cred.setPassword(currPass); + try { + fail = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client)throws CadiException, ConnectException, APIException { + TimeTaken tt = trans.start("Check Current Password",Env.REMOTE); + try { + Future fcr = client.create( // Note: Need "Post", because of hiding password in SSL Data + "/authn/validate", + gui.getDF(CredRequest.class), + cred + ); + boolean go; + boolean fail = true; + fcr.get(5000); + if(fcr.code() == 200) { + hgen.p("Current Password validated"); + go = true; + } else { + hgen.p(String.format("Invalid Current Password: %d %s",fcr.code(),fcr.body())); + go = false; + } + if(go) { + tt.done(); + tt = trans.start("AAF Change Password",Env.REMOTE); + try { + // Change over Cred to reset mode + cred.setPassword(password); + String start = trans.get(startDate, null); + if(start!=null) { + try { + cred.setStart(Chrono.timeStamp(Chrono.dateOnlyFmt.parse(start))); + } catch (ParseException e) { + throw new CadiException(e); + } + } + + fcr = client.create( + "/authn/cred", + gui.getDF(CredRequest.class), + cred + ); + + if(fcr.get(5000)) { + // Do Remote Call + hgen.p("New Password has been added."); + fail = false; + } else { + gui.writeError(trans, fcr, hgen, 0); + } + } finally { + tt.done(); + } + } + return fail; + } finally { + tt.done(); + } + } + }); - } catch (Exception e) { - hgen.p("Unknown Error"); - e.printStackTrace(); - } - } - hgen.br(); - if(fail) { - hgen.incr("a",true,"href="+PassChangeForm.HREF+"?id="+id).text("Try again").end(); - } else { - hgen.incr("a",true,"href="+Home.HREF).text("Home").end(); - } - } - }); - } - }); - } + } catch (Exception e) { + hgen.p("Unknown Error"); + e.printStackTrace(); + } + } + hgen.br(); + if(fail) { + hgen.incr("a",true,"href="+PassChangeForm.HREF+"?id="+id).text("Try again").end(); + } else { + hgen.incr("a",true,"href="+Home.HREF).text("Home").end(); + } + } + }); + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java index 173b9500..2447c98b 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java @@ -51,112 +51,112 @@ import aaf.v2_0.Nss.Ns; public class NsInfoForm extends Page { - // Package on purpose - static final String HREF = "/gui/onboard"; - static final String NAME = "Onboarding"; - static final String fields[] = {"ns","description","mots","owners","admins"}; - - public NsInfoForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { + // Package on purpose + static final String HREF = "/gui/onboard"; + static final String NAME = "Onboarding"; + static final String fields[] = {"ns","description","mots","owners","admins"}; + + public NsInfoForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { - private final Slot sID = gui.env.slot(NsInfoForm.NAME+'.'+NsInfoForm.fields[0]); - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - // p tags not closing right using .p() - causes issues in IE8 password form - so using leaf for the moment - hgen.leaf(HTMLGen.H2).text("Namespace Info").end() - .leaf("p").text("Hover over Fields for Tool Tips, or click ") - .leaf(A,"href="+gui.env.getProperty(AAF_URL_GUI_ONBOARD,"")).text("Here").end() - .text(" for more information") - .end() - .incr("form","method=post"); - Mark table = new Mark(TABLE); - hgen.incr(table); - cache.dynamic(hgen, new DynamicCode() { - @SuppressWarnings("unchecked") - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final String incomingID= trans.get(sID, ""); - final String[] info = new String[fields.length]; - final Object own_adm[] = new Object[2]; - for(int i=0;i0) { - TimeTaken tt = trans.start("AAF Namespace Info",Env.REMOTE); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fn = client.read("/authz/nss/"+incomingID,gui.getDF(Nss.class)); - if(fn.get(AAF_GUI.TIMEOUT)) { - for(Ns ns : fn.value.getNs()) { - info[0]=ns.getName(); - info[1]=ns.getDescription(); - for(Ns.Attrib attr: ns.getAttrib()) { - switch(attr.getKey()) { - case "mots": - info[2]=attr.getValue(); - default: - } - } - own_adm[0]=ns.getResponsible(); - own_adm[1]=ns.getAdmin(); - } - } else { - trans.error().log(fn.body()); - } - return null; - } - }); - } catch (Exception e) { - trans.error().log("Unable to access AAF for NS Info",incomingID); - e.printStackTrace(); - } finally { - tt.done(); - } - } - hgen.input(fields[0],"Namespace",false,"value="+info[0],"title=AAF Namespace") - .input(fields[1],"Description*",true,"value="+info[1],"title=Full Application Name, Tool Name or Group") - .input(fields[2],"MOTS ID",false,"value="+info[2],"title=MOTS ID if this is an Application, and has MOTS"); - Mark endTD = new Mark(),endTR=new Mark(); - // Owners - hgen.incr(endTR,HTMLGen.TR) - .incr(endTD,HTMLGen.TD) - .leaf("label","for="+fields[3]).text("Responsible Party") - .end(endTD) - .incr(endTD,HTMLGen.TD) - .tagOnly("input","id="+fields[3],"title=Owner of App, must be an Non-Bargained Employee"); - if(own_adm[0]!=null) { - for(String s : (List)own_adm[0]) { - hgen.incr("label",true).text(s).end(); - } - } - hgen.end(endTR); + private final Slot sID = gui.env.slot(NsInfoForm.NAME+'.'+NsInfoForm.fields[0]); + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + // p tags not closing right using .p() - causes issues in IE8 password form - so using leaf for the moment + hgen.leaf(HTMLGen.H2).text("Namespace Info").end() + .leaf("p").text("Hover over Fields for Tool Tips, or click ") + .leaf(A,"href="+gui.env.getProperty(AAF_URL_GUI_ONBOARD,"")).text("Here").end() + .text(" for more information") + .end() + .incr("form","method=post"); + Mark table = new Mark(TABLE); + hgen.incr(table); + cache.dynamic(hgen, new DynamicCode() { + @SuppressWarnings("unchecked") + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final String incomingID= trans.get(sID, ""); + final String[] info = new String[fields.length]; + final Object own_adm[] = new Object[2]; + for(int i=0;i0) { + TimeTaken tt = trans.start("AAF Namespace Info",Env.REMOTE); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fn = client.read("/authz/nss/"+incomingID,gui.getDF(Nss.class)); + if(fn.get(AAF_GUI.TIMEOUT)) { + for(Ns ns : fn.value.getNs()) { + info[0]=ns.getName(); + info[1]=ns.getDescription(); + for(Ns.Attrib attr: ns.getAttrib()) { + switch(attr.getKey()) { + case "mots": + info[2]=attr.getValue(); + default: + } + } + own_adm[0]=ns.getResponsible(); + own_adm[1]=ns.getAdmin(); + } + } else { + trans.error().log(fn.body()); + } + return null; + } + }); + } catch (Exception e) { + trans.error().log("Unable to access AAF for NS Info",incomingID); + e.printStackTrace(); + } finally { + tt.done(); + } + } + hgen.input(fields[0],"Namespace",false,"value="+info[0],"title=AAF Namespace") + .input(fields[1],"Description*",true,"value="+info[1],"title=Full Application Name, Tool Name or Group") + .input(fields[2],"MOTS ID",false,"value="+info[2],"title=MOTS ID if this is an Application, and has MOTS"); + Mark endTD = new Mark(),endTR=new Mark(); + // Owners + hgen.incr(endTR,HTMLGen.TR) + .incr(endTD,HTMLGen.TD) + .leaf("label","for="+fields[3]).text("Responsible Party") + .end(endTD) + .incr(endTD,HTMLGen.TD) + .tagOnly("input","id="+fields[3],"title=Owner of App, must be an Non-Bargained Employee"); + if(own_adm[0]!=null) { + for(String s : (List)own_adm[0]) { + hgen.incr("label",true).text(s).end(); + } + } + hgen.end(endTR); - // Admins - hgen.incr(endTR,HTMLGen.TR) - .incr(endTD,HTMLGen.TD) - .leaf("label","for="+fields[4]).text("Administrators") - .end(endTD) - .incr(endTD,HTMLGen.TD) - .tagOnly("input","id="+fields[4],"title=Admins may be employees, contractors or mechIDs"); - if(own_adm[1]!=null) { - for(String s : (List)own_adm[1]) { - hgen.incr(HTMLGen.P,true).text(s).end(); - } - } - hgen.end(endTR) - .end(); - } - }); - hgen.end(); - hgen.tagOnly("input", "type=submit", "value=Submit") - .end(); + // Admins + hgen.incr(endTR,HTMLGen.TR) + .incr(endTD,HTMLGen.TD) + .leaf("label","for="+fields[4]).text("Administrators") + .end(endTD) + .incr(endTD,HTMLGen.TD) + .tagOnly("input","id="+fields[4],"title=Admins may be employees, contractors or mechIDs"); + if(own_adm[1]!=null) { + for(String s : (List)own_adm[1]) { + hgen.incr(HTMLGen.P,true).text(s).end(); + } + } + hgen.end(endTR) + .end(); + } + }); + hgen.end(); + hgen.tagOnly("input", "type=submit", "value=Submit") + .end(); - } - }); - } + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java index fecd2326..b2a6e368 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java @@ -51,92 +51,92 @@ import aaf.v2_0.Nss; import aaf.v2_0.Nss.Ns; public class NssShow extends Page { - public static final String HREF = "/gui/ns"; + public static final String HREF = "/gui/ns"; - public NssShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, "MyNamespaces",HREF, NO_FIELDS, - new BreadCrumbs(breadcrumbs), - new Table("Namespaces I administer",gui.env.newTransNoAvg(),new Model(true,"Administrator",gui.env), - "class=std", "style=display: inline-block; width: 45%; margin: 10px;"), - new Table("Namespaces I own",gui.env.newTransNoAvg(),new Model(false,"Owner",gui.env), - "class=std", "style=display: inline-block; width: 45%; margin: 10px;")); - } - - private static class Model extends TableData { - private String[] headers; - private String privilege = null; - public final Slot sNssByUser; - private boolean isAdmin; + public NssShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, "MyNamespaces",HREF, NO_FIELDS, + new BreadCrumbs(breadcrumbs), + new Table("Namespaces I administer",gui.env.newTransNoAvg(),new Model(true,"Administrator",gui.env), + "class=std", "style=display: inline-block; width: 45%; margin: 10px;"), + new Table("Namespaces I own",gui.env.newTransNoAvg(),new Model(false,"Owner",gui.env), + "class=std", "style=display: inline-block; width: 45%; margin: 10px;")); + } + + private static class Model extends TableData { + private String[] headers; + private String privilege = null; + public final Slot sNssByUser; + private boolean isAdmin; - public Model(boolean admin, String privilege,AuthzEnv env) { - super(); - headers = new String[] {privilege}; - this.privilege = privilege; - isAdmin = admin; - sNssByUser = env.slot("NSS_SHOW_MODEL_DATA"); - } + public Model(boolean admin, String privilege,AuthzEnv env) { + super(); + headers = new String[] {privilege}; + this.privilege = privilege; + isAdmin = admin; + sNssByUser = env.slot("NSS_SHOW_MODEL_DATA"); + } - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - ArrayList rv = new ArrayList<>(); - List nss = trans.get(sNssByUser, null); - if(nss==null) { - TimeTaken tt = trans.start("AAF Nss by User for " + privilege,Env.REMOTE); - try { - nss = gui.clientAsUser(trans.getUserPrincipal(), new Retryable>() { - @Override - public List code(Rcli client) throws CadiException, ConnectException, APIException { - List nss = null; - Future fp = client.read("/authz/nss/either/" + trans.user(),gui.getDF(Nss.class)); - if(fp.get(AAF_GUI.TIMEOUT)) { - TimeTaken tt = trans.start("Load Data for " + privilege, Env.SUB); - try { - if(fp.value!=null) { - nss = fp.value.getNs(); - Collections.sort(nss, new Comparator() { - public int compare(Ns ns1, Ns ns2) { - return ns1.getName().compareToIgnoreCase(ns2.getName()); - } - }); - trans.put(sNssByUser,nss); - } - } finally { - tt.done(); - } - }else { - gui.writeError(trans, fp, null,0); - } - return nss; - } - }); - } catch (Exception e) { - trans.error().log(e); - } finally { - tt.done(); - } - } - - if(nss!=null) { - for(Ns n : nss) { - if((isAdmin && !n.getAdmin().isEmpty()) - || (!isAdmin && !n.getResponsible().isEmpty())) { - AbsCell[] sa = new AbsCell[] { - new RefCell(n.getName(),NsDetail.HREF - +"?ns="+n.getName(),false), - }; - rv.add(sa); - } - } - } + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + ArrayList rv = new ArrayList<>(); + List nss = trans.get(sNssByUser, null); + if(nss==null) { + TimeTaken tt = trans.start("AAF Nss by User for " + privilege,Env.REMOTE); + try { + nss = gui.clientAsUser(trans.getUserPrincipal(), new Retryable>() { + @Override + public List code(Rcli client) throws CadiException, ConnectException, APIException { + List nss = null; + Future fp = client.read("/authz/nss/either/" + trans.user(),gui.getDF(Nss.class)); + if(fp.get(AAF_GUI.TIMEOUT)) { + TimeTaken tt = trans.start("Load Data for " + privilege, Env.SUB); + try { + if(fp.value!=null) { + nss = fp.value.getNs(); + Collections.sort(nss, new Comparator() { + public int compare(Ns ns1, Ns ns2) { + return ns1.getName().compareToIgnoreCase(ns2.getName()); + } + }); + trans.put(sNssByUser,nss); + } + } finally { + tt.done(); + } + }else { + gui.writeError(trans, fp, null,0); + } + return nss; + } + }); + } catch (Exception e) { + trans.error().log(e); + } finally { + tt.done(); + } + } + + if(nss!=null) { + for(Ns n : nss) { + if((isAdmin && !n.getAdmin().isEmpty()) + || (!isAdmin && !n.getResponsible().isEmpty())) { + AbsCell[] sa = new AbsCell[] { + new RefCell(n.getName(),NsDetail.HREF + +"?ns="+n.getName(),false), + }; + rv.add(sa); + } + } + } - return new Cells(rv,null); - } - } - + return new Cells(rv,null); + } + } + } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java index d0d03a7a..aafd0c96 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java @@ -55,157 +55,157 @@ import aaf.v2_0.Users; public class PassChangeAction extends Page { - public PassChangeAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,PassChangeForm.NAME,PassChangeForm.HREF, PassChangeForm.fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - final Slot sID = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[0]); - final Slot sCurrPass = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[1]); - final Slot sPassword = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[2]); - final Slot sPassword2 = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[3]); - final Slot startDate = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[4]); - final Slot sNS = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[5]); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final String id = trans.get(sID,null); - final String currPass = trans.get(sCurrPass,null); - final String password = trans.get(sPassword,null); - final String password2 = trans.get(sPassword2,null); - final String ns = trans.get(sNS, null); - - // Run Validations - boolean fail = true; - - if (id==null || id.indexOf('@')<=0) { - hgen.p("Data Entry Failure: Please enter a valid ID, including domain."); - } else if(password == null || password2 == null) { - hgen.p("Data Entry Failure: Both Password Fields need entries."); - } else if(!password.equals(password2)) { - hgen.p("Data Entry Failure: Passwords do not match."); - } else { // everything else is checked by Server - final CredRequest cred = new CredRequest(); - cred.setId(id); - cred.setPassword("".equals(currPass)?null:currPass); - try { - fail = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client)throws CadiException, ConnectException, APIException { - boolean fail = true; - boolean go = false; - try { - Organization org = OrganizationFactory.obtain(trans.env(), id); - if(org!=null) { - go = PassChangeForm.skipCurrent(trans, org.getIdentity(trans, id)); - } - } catch(OrganizationException e) { - trans.error().log(e); - } + public PassChangeAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,PassChangeForm.NAME,PassChangeForm.HREF, PassChangeForm.fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + final Slot sID = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[0]); + final Slot sCurrPass = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[1]); + final Slot sPassword = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[2]); + final Slot sPassword2 = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[3]); + final Slot startDate = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[4]); + final Slot sNS = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[5]); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final String id = trans.get(sID,null); + final String currPass = trans.get(sCurrPass,null); + final String password = trans.get(sPassword,null); + final String password2 = trans.get(sPassword2,null); + final String ns = trans.get(sNS, null); + + // Run Validations + boolean fail = true; + + if (id==null || id.indexOf('@')<=0) { + hgen.p("Data Entry Failure: Please enter a valid ID, including domain."); + } else if(password == null || password2 == null) { + hgen.p("Data Entry Failure: Both Password Fields need entries."); + } else if(!password.equals(password2)) { + hgen.p("Data Entry Failure: Passwords do not match."); + } else { // everything else is checked by Server + final CredRequest cred = new CredRequest(); + cred.setId(id); + cred.setPassword("".equals(currPass)?null:currPass); + try { + fail = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client)throws CadiException, ConnectException, APIException { + boolean fail = true; + boolean go = false; + try { + Organization org = OrganizationFactory.obtain(trans.env(), id); + if(org!=null) { + go = PassChangeForm.skipCurrent(trans, org.getIdentity(trans, id)); + } + } catch(OrganizationException e) { + trans.error().log(e); + } - if(cred.getPassword()==null) { - try { - if(!go) { - go=gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { - Future fc = client.read("/authn/creds/id/"+id,gui.getDF(Users.class)); - if(fc.get(AAFcli.timeout())) { - GregorianCalendar now = new GregorianCalendar(); - for(aaf.v2_0.Users.User u : fc.value.getUser()) { - if(u.getType()<10 && u.getExpires().toGregorianCalendar().after(now)) { - return false; // an existing, non expired, password type exists - } - } - return true; // no existing, no expired password - } else { - if(fc.code()==404) { // not found... - return true; - } else { - trans.error().log(gui.aafCon.readableErrMsg(fc)); - } - } - return false; - } - }); - } - if(!go) { - hgen.p("Current Password required").br(); - } - } catch (LocatorException e) { - trans.error().log(e); - } + if(cred.getPassword()==null) { + try { + if(!go) { + go=gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { + Future fc = client.read("/authn/creds/id/"+id,gui.getDF(Users.class)); + if(fc.get(AAFcli.timeout())) { + GregorianCalendar now = new GregorianCalendar(); + for(aaf.v2_0.Users.User u : fc.value.getUser()) { + if(u.getType()<10 && u.getExpires().toGregorianCalendar().after(now)) { + return false; // an existing, non expired, password type exists + } + } + return true; // no existing, no expired password + } else { + if(fc.code()==404) { // not found... + return true; + } else { + trans.error().log(gui.aafCon.readableErrMsg(fc)); + } + } + return false; + } + }); + } + if(!go) { + hgen.p("Current Password required").br(); + } + } catch (LocatorException e) { + trans.error().log(e); + } - } else { - TimeTaken tt = trans.start("Check Current Password",Env.REMOTE); - try { - // Note: Need "Post", because of hiding password in SSL Data - Future fcr = client.create("/authn/validate",gui.getDF(CredRequest.class),cred); - fcr.get(5000); - if(fcr.code() == 200) { - hgen.p("Current Password validated").br(); - go = true; - } else { - hgen.p(Cred.ATTEMPT_FAILED_SPECIFICS_WITHELD).br(); - trans.info().log("Failed Validation",fcr.code(),fcr.body()); - go = false; - } - } finally { - tt.done(); - } - } - if(go) { - TimeTaken tt = trans.start("AAF Change Password",Env.REMOTE); - try { - // Change over Cred to reset mode - cred.setPassword(password); - String start = trans.get(startDate, null); - if(start!=null) { - try { - cred.setStart(Chrono.timeStamp(Chrono.dateOnlyFmt.parse(start))); - } catch (ParseException e) { - throw new CadiException(e); - } - } - - Future fcr = gui.clientAsUser(trans.getUserPrincipal()).create("/authn/cred",gui.getDF(CredRequest.class),cred); - if(fcr.get(AAFcli.timeout())) { - // Do Remote Call - hgen.p("New Password has been added. The previous one is still valid until Expiration."); - fail = false; - } else { - hgen.p(Cred.ATTEMPT_FAILED_SPECIFICS_WITHELD).br(); - trans.info().log("Failed Validation",fcr.code(),fcr.body()); - } - } finally { - tt.done(); - } - } - return fail; - } - - }); - } catch (Exception e) { - hgen.p("Unknown Error"); - e.printStackTrace(); - } - - } - hgen.br(); - if(fail) { - hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+PassChangeForm.HREF+"?id="+id).text("Try again").end(); - } else { - if(ns==null) { - hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+Home.HREF).text("Back").end(); - } else { - hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+CredDetail.HREF+"?id="+id+"&ns="+ns).text("Back").end(); - } - } - } - }); - } - }); - } + } else { + TimeTaken tt = trans.start("Check Current Password",Env.REMOTE); + try { + // Note: Need "Post", because of hiding password in SSL Data + Future fcr = client.create("/authn/validate",gui.getDF(CredRequest.class),cred); + fcr.get(5000); + if(fcr.code() == 200) { + hgen.p("Current Password validated").br(); + go = true; + } else { + hgen.p(Cred.ATTEMPT_FAILED_SPECIFICS_WITHELD).br(); + trans.info().log("Failed Validation",fcr.code(),fcr.body()); + go = false; + } + } finally { + tt.done(); + } + } + if(go) { + TimeTaken tt = trans.start("AAF Change Password",Env.REMOTE); + try { + // Change over Cred to reset mode + cred.setPassword(password); + String start = trans.get(startDate, null); + if(start!=null) { + try { + cred.setStart(Chrono.timeStamp(Chrono.dateOnlyFmt.parse(start))); + } catch (ParseException e) { + throw new CadiException(e); + } + } + + Future fcr = gui.clientAsUser(trans.getUserPrincipal()).create("/authn/cred",gui.getDF(CredRequest.class),cred); + if(fcr.get(AAFcli.timeout())) { + // Do Remote Call + hgen.p("New Password has been added. The previous one is still valid until Expiration."); + fail = false; + } else { + hgen.p(Cred.ATTEMPT_FAILED_SPECIFICS_WITHELD).br(); + trans.info().log("Failed Validation",fcr.code(),fcr.body()); + } + } finally { + tt.done(); + } + } + return fail; + } + + }); + } catch (Exception e) { + hgen.p("Unknown Error"); + e.printStackTrace(); + } + + } + hgen.br(); + if(fail) { + hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+PassChangeForm.HREF+"?id="+id).text("Try again").end(); + } else { + if(ns==null) { + hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+Home.HREF).text("Back").end(); + } else { + hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+CredDetail.HREF+"?id="+id+"&ns="+ns).text("Back").end(); + } + } + } + }); + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java index 897796d6..dcaed047 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java @@ -52,154 +52,154 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; import aaf.v2_0.Users; public class PassChangeForm extends Page { - // Package on purpose - static final String HREF = "/gui/passwd"; - static final String NAME = "PassChange"; - static final String fields[] = {"id","current","password","password2","startDate","ns"}; - - public PassChangeForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,NAME) { - private final Slot sID = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[0]); - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - - // p tags not closing right using .p() - causes issues in IE8 password form - so using leaf for the moment - hgen.incr(HTMLGen.H4,true,"style=margin: 0em 0em .4em 0em") - .text("You are adding a New Password in the AAF System.") - .end(); + // Package on purpose + static final String HREF = "/gui/passwd"; + static final String NAME = "PassChange"; + static final String fields[] = {"id","current","password","password2","startDate","ns"}; + + public PassChangeForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,NAME) { + private final Slot sID = gui.env.slot(PassChangeForm.NAME+'.'+PassChangeForm.fields[0]); + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + + // p tags not closing right using .p() - causes issues in IE8 password form - so using leaf for the moment + hgen.incr(HTMLGen.H4,true,"style=margin: 0em 0em .4em 0em") + .text("You are adding a New Password in the AAF System.") + .end(); - Mark form = new Mark(); - hgen.incr(form,"form","method=post"); - - Mark table = new Mark(TABLE); - hgen.incr(table); + Mark form = new Mark(); + hgen.incr(form,"form","method=post"); + + Mark table = new Mark(TABLE); + hgen.incr(table); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String incomingID= trans.get(sID, ""); - boolean skipCurrent = false; - if(incomingID.length()>0) { - try { - Organization org = OrganizationFactory.obtain(trans.env(), incomingID); - if(org==null) { - hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: There is no supported company for ").text(incomingID).end(); - } else { - Identity user = org.getIdentity(trans, incomingID); - if(user==null) { - int at = incomingID.indexOf('@'); - hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: You are not the sponsor of '").text(at<0?incomingID:incomingID.substring(0,at)) - .text("' defined at ").text(org.getName()).end(); - incomingID = ""; - } else { - // Owners/or the IDs themselves are allowed to reset password without previous one - skipCurrent=skipCurrent(trans, user); - - if(!skipCurrent) { - final String id = incomingID; - try { - skipCurrent=gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { - Future fc = client.read("/authn/creds/id/"+id,gui.getDF(Users.class)); - if(fc.get(AAFcli.timeout())) { - GregorianCalendar now = new GregorianCalendar(); - for(aaf.v2_0.Users.User u : fc.value.getUser()) { - if(u.getType()<10 && u.getType()>=1 && u.getExpires().toGregorianCalendar().after(now)) { - return false; // an existing, non expired, password type exists - } - } - return true; // no existing, no expired password - } else { - if(fc.code()==404) { // not found... - return true; - } else { - trans.error().log(gui.aafCon.readableErrMsg(fc)); - } - } - return false; - } - }); - } catch (LocatorException | CadiException e) { - trans.error().log(e); - } - } - } - } - } catch (OrganizationException e) { - hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: ") - .text(e.getMessage()).end(); - } - } - - hgen.input(fields[0],"ID*",true,"value="+incomingID,(incomingID.length()==0?"":"readonly")); - if(!skipCurrent) { - hgen.input(fields[1],"Current Password*",true,"type=password"); - } - if(skipCurrent) { - hgen.input(fields[1],"",false,"type=hidden", "value=").end(); - } + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String incomingID= trans.get(sID, ""); + boolean skipCurrent = false; + if(incomingID.length()>0) { + try { + Organization org = OrganizationFactory.obtain(trans.env(), incomingID); + if(org==null) { + hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: There is no supported company for ").text(incomingID).end(); + } else { + Identity user = org.getIdentity(trans, incomingID); + if(user==null) { + int at = incomingID.indexOf('@'); + hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: You are not the sponsor of '").text(at<0?incomingID:incomingID.substring(0,at)) + .text("' defined at ").text(org.getName()).end(); + incomingID = ""; + } else { + // Owners/or the IDs themselves are allowed to reset password without previous one + skipCurrent=skipCurrent(trans, user); + + if(!skipCurrent) { + final String id = incomingID; + try { + skipCurrent=gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { + Future fc = client.read("/authn/creds/id/"+id,gui.getDF(Users.class)); + if(fc.get(AAFcli.timeout())) { + GregorianCalendar now = new GregorianCalendar(); + for(aaf.v2_0.Users.User u : fc.value.getUser()) { + if(u.getType()<10 && u.getType()>=1 && u.getExpires().toGregorianCalendar().after(now)) { + return false; // an existing, non expired, password type exists + } + } + return true; // no existing, no expired password + } else { + if(fc.code()==404) { // not found... + return true; + } else { + trans.error().log(gui.aafCon.readableErrMsg(fc)); + } + } + return false; + } + }); + } catch (LocatorException | CadiException e) { + trans.error().log(e); + } + } + } + } + } catch (OrganizationException e) { + hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: ") + .text(e.getMessage()).end(); + } + } + + hgen.input(fields[0],"ID*",true,"value="+incomingID,(incomingID.length()==0?"":"readonly")); + if(!skipCurrent) { + hgen.input(fields[1],"Current Password*",true,"type=password"); + } + if(skipCurrent) { + hgen.input(fields[1],"",false,"type=hidden", "value=").end(); + } - hgen.input(fields[2],"New Password*",true, "type=password") - .input(fields[3], "Reenter New Password*",true, "type=password") - // .input(fields[3],"Start Date",false,"type=date", "value="+ - // Chrono.dateOnlyFmt.format(new Date(System.currentTimeMillis())) - // ) - .end(table); + hgen.input(fields[2],"New Password*",true, "type=password") + .input(fields[3], "Reenter New Password*",true, "type=password") + // .input(fields[3],"Start Date",false,"type=date", "value="+ + // Chrono.dateOnlyFmt.format(new Date(System.currentTimeMillis())) + // ) + .end(table); - } + } - }); - hgen.tagOnly("input", "type=submit", "value=Submit") - .end(form) - .br() - .p("All AAF Passwords continue to be valid until their listed expiration dates. ", - "This allows you to migrate services to this new password until the old ones expire.").br().br() - .p("Note: You must be an Admin of the Namespace where the MechID is defined.").br() - ; - - Mark div = hgen.divID("passwordRules"); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - try { - Organization org = OrganizationFactory.obtain(trans.env(),trans.getUserPrincipal().getName()); - if(org!=null) { - hgen.incr(HTMLGen.H4).text("Password Rules for ").text(org.getName()).end() - .incr(HTMLGen.UL); - for(String line : org.getPasswordRules()) { - hgen.leaf(HTMLGen.LI).text(line).end(); - } - hgen.end(); - } - } catch (OrganizationException e) { - hgen.p("No Password Rules can be found for company of ID ",trans.getUserPrincipal().getName()).br(); - } - } - }); - hgen.end(div); - } - } - ); - } + }); + hgen.tagOnly("input", "type=submit", "value=Submit") + .end(form) + .br() + .p("All AAF Passwords continue to be valid until their listed expiration dates. ", + "This allows you to migrate services to this new password until the old ones expire.").br().br() + .p("Note: You must be an Admin of the Namespace where the MechID is defined.").br() + ; + + Mark div = hgen.divID("passwordRules"); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + try { + Organization org = OrganizationFactory.obtain(trans.env(),trans.getUserPrincipal().getName()); + if(org!=null) { + hgen.incr(HTMLGen.H4).text("Password Rules for ").text(org.getName()).end() + .incr(HTMLGen.UL); + for(String line : org.getPasswordRules()) { + hgen.leaf(HTMLGen.LI).text(line).end(); + } + hgen.end(); + } + } catch (OrganizationException e) { + hgen.p("No Password Rules can be found for company of ID ",trans.getUserPrincipal().getName()).br(); + } + } + }); + hgen.end(div); + } + } + ); + } - // Package on Purpose - static boolean skipCurrent(AuthzTrans trans, Identity user) throws OrganizationException { - if(user!=null) { - // Should this be an abstractable Policy? - String tuser = trans.user(); - if(user.fullID().equals(trans.user())) { - return true; - } else { - Identity manager = user.responsibleTo(); - if(tuser.equals(user.fullID()) || manager.isFound()) { - return true; - } - } - } - return false; - } + // Package on Purpose + static boolean skipCurrent(AuthzTrans trans, Identity user) throws OrganizationException { + if(user!=null) { + // Should this be an abstractable Policy? + String tuser = trans.user(); + if(user.fullID().equals(trans.user())) { + return true; + } else { + Identity manager = user.responsibleTo(); + if(tuser.equals(user.fullID()) || manager.isFound()) { + return true; + } + } + } + return false; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java index 49daf022..2ad7ca5e 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java @@ -43,46 +43,46 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; import aaf.v2_0.CredRequest; public class PassDeleteAction extends Page { - public static final String NAME = "PassDeleteAction"; - public static final String HREF = "/gui/passdelete"; - private static enum Params{id,date,ns,type}; - - public PassDeleteAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF,Params.values(), - new BreadCrumbs(breadcrumbs), - new SlotCode(true,gui.env,NAME,Params.values()) { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final CredRequest cr = new CredRequest(); - cr.setId(get(trans,Params.id, "")); - cr.setType(Integer.parseInt(get(trans,Params.type, "0"))); - cr.setEntry(get(trans,Params.date,"1960-01-01")); - try { - String err = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public String code(Rcli client) throws CadiException, ConnectException, APIException { - Future fcr = client.delete("/authn/cred", gui.getDF(CredRequest.class),cr); - if(!fcr.get(AAFcli.timeout())) { - return gui.aafCon.readableErrMsg(fcr); - } - return null; - } - }); - if(err==null) { - hgen.p("Password " + cr.getId() + ", " + cr.getEntry() + " is Deleted"); - } else { - hgen.p(err); - } - } catch (LocatorException | CadiException e) { - throw new APIException(e); - } - } - }); - } - } - ); - } + public static final String NAME = "PassDeleteAction"; + public static final String HREF = "/gui/passdelete"; + private static enum Params{id,date,ns,type}; + + public PassDeleteAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF,Params.values(), + new BreadCrumbs(breadcrumbs), + new SlotCode(true,gui.env,NAME,Params.values()) { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final CredRequest cr = new CredRequest(); + cr.setId(get(trans,Params.id, "")); + cr.setType(Integer.parseInt(get(trans,Params.type, "0"))); + cr.setEntry(get(trans,Params.date,"1960-01-01")); + try { + String err = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public String code(Rcli client) throws CadiException, ConnectException, APIException { + Future fcr = client.delete("/authn/cred", gui.getDF(CredRequest.class),cr); + if(!fcr.get(AAFcli.timeout())) { + return gui.aafCon.readableErrMsg(fcr); + } + return null; + } + }); + if(err==null) { + hgen.p("Password " + cr.getId() + ", " + cr.getEntry() + " is Deleted"); + } else { + hgen.p(err); + } + } catch (LocatorException | CadiException e) { + throw new APIException(e); + } + } + }); + } + } + ); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java index 6e7081bc..a4970e3c 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java @@ -56,131 +56,131 @@ import aaf.v2_0.Approval; import aaf.v2_0.Approvals; public class PendingRequestsShow extends Page { - public static final String HREF = "/gui/myrequests"; - public static final String NAME = "MyRequests"; - static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; - - public PendingRequestsShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME,HREF, NO_FIELDS, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"expedite") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - hgen - .leaf("p", "class=expedite_request").text("These are your submitted Requests that are awaiting Approval. ") - .br() - .text("To Expedite a Request: ") - .leaf("a","href=#expedite_directions","onclick=divVisibility('expedite_directions');") - .text("Click Here").end() - .divID("expedite_directions", "style=display:none"); - hgen - .incr(HTMLGen.OL) - .incr(HTMLGen.LI) - .leaf("a","href="+ApprovalForm.HREF+"?user="+trans.user(), "id=userApprove") - .text("Copy This Link") - .end() - .end() - .incr(HTMLGen.LI) - .text("Send it to the Approver Listed") - .end() - .end() - .text("NOTE: Using this link, the Approver will only see your requests. You only need to send this link once!") - .end() - .end(); - } - }); - } - }, - new Table("Pending Requests",gui.env.newTransNoAvg(),new Model(), "class=std") - ); - + public static final String HREF = "/gui/myrequests"; + public static final String NAME = "MyRequests"; + static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; + + public PendingRequestsShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME,HREF, NO_FIELDS, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"expedite") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + hgen + .leaf("p", "class=expedite_request").text("These are your submitted Requests that are awaiting Approval. ") + .br() + .text("To Expedite a Request: ") + .leaf("a","href=#expedite_directions","onclick=divVisibility('expedite_directions');") + .text("Click Here").end() + .divID("expedite_directions", "style=display:none"); + hgen + .incr(HTMLGen.OL) + .incr(HTMLGen.LI) + .leaf("a","href="+ApprovalForm.HREF+"?user="+trans.user(), "id=userApprove") + .text("Copy This Link") + .end() + .end() + .incr(HTMLGen.LI) + .text("Send it to the Approver Listed") + .end() + .end() + .text("NOTE: Using this link, the Approver will only see your requests. You only need to send this link once!") + .end() + .end(); + } + }); + } + }, + new Table("Pending Requests",gui.env.newTransNoAvg(),new Model(), "class=std") + ); + - } + } - /** - * Implement the Table Content for Requests by User - * - * @author Jeremiah - * - */ - private static class Model extends TableData { - final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; - private static final String[] headers = new String[] {"Request Date","Status","Memo","Approver"}; + /** + * Implement the Table Content for Requests by User + * + * @author Jeremiah + * + */ + private static class Model extends TableData { + final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; + private static final String[] headers = new String[] {"Request Date","Status","Memo","Approver"}; - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final ArrayList rv = new ArrayList<>(); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client)throws CadiException, ConnectException, APIException { - TimeTaken tt = trans.start("AAF Get Approvals by User",Env.REMOTE); - try { - Future fa = client.read("/authz/approval/user/"+trans.user(),gui.getDF(Approvals.class)); - if(fa.get(5000)) { - tt.done(); - tt = trans.start("Load Data", Env.SUB); - if(fa.value!=null) { - List approvals = fa.value.getApprovals(); - Collections.sort(approvals, new Comparator() { - @Override - public int compare(Approval a1, Approval a2) { - UUID id1 = UUID.fromString(a1.getId()); - UUID id2 = UUID.fromString(a2.getId()); - return id1.timestamp()<=id2.timestamp()?1:-1; - } - }); - - String prevTicket = null; - for(Approval a : approvals) { - String approver = a.getApprover(); - String approverShort = approver.substring(0,approver.indexOf('@')); - - AbsCell tsCell = null; - String ticket = a.getTicket(); - if (ticket==null || ticket.equals(prevTicket)) { - tsCell = AbsCell.Null; - } else { - UUID id = UUID.fromString(a.getId()); - // Sonar says SimpleDate should not be static - tsCell = new RefCell(new SimpleDateFormat("yyyy-MM-dd").format((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000), - RequestDetail.HREF + "?ticket=" + ticket,false); - prevTicket = ticket; - } - - AbsCell approverCell = new TextCell(approver); - AbsCell[] sa = new AbsCell[] { - tsCell, - new TextCell(a.getStatus()), - new TextCell(a.getMemo()), - approverCell - }; - rv.add(sa); - } - } - } else { - gui.writeError(trans, fa, null, 0); - } - } finally { - tt.done(); - } + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final ArrayList rv = new ArrayList<>(); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client)throws CadiException, ConnectException, APIException { + TimeTaken tt = trans.start("AAF Get Approvals by User",Env.REMOTE); + try { + Future fa = client.read("/authz/approval/user/"+trans.user(),gui.getDF(Approvals.class)); + if(fa.get(5000)) { + tt.done(); + tt = trans.start("Load Data", Env.SUB); + if(fa.value!=null) { + List approvals = fa.value.getApprovals(); + Collections.sort(approvals, new Comparator() { + @Override + public int compare(Approval a1, Approval a2) { + UUID id1 = UUID.fromString(a1.getId()); + UUID id2 = UUID.fromString(a2.getId()); + return id1.timestamp()<=id2.timestamp()?1:-1; + } + }); + + String prevTicket = null; + for(Approval a : approvals) { + String approver = a.getApprover(); + String approverShort = approver.substring(0,approver.indexOf('@')); + + AbsCell tsCell = null; + String ticket = a.getTicket(); + if (ticket==null || ticket.equals(prevTicket)) { + tsCell = AbsCell.Null; + } else { + UUID id = UUID.fromString(a.getId()); + // Sonar says SimpleDate should not be static + tsCell = new RefCell(new SimpleDateFormat("yyyy-MM-dd").format((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000), + RequestDetail.HREF + "?ticket=" + ticket,false); + prevTicket = ticket; + } + + AbsCell approverCell = new TextCell(approver); + AbsCell[] sa = new AbsCell[] { + tsCell, + new TextCell(a.getStatus()), + new TextCell(a.getMemo()), + approverCell + }; + rv.add(sa); + } + } + } else { + gui.writeError(trans, fa, null, 0); + } + } finally { + tt.done(); + } - return null; - } - }); - } catch (Exception e) { - trans.error().log(e); - } - return new Cells(rv,null); - } - } + return null; + } + }); + } catch (Exception e) { + trans.error().log(e); + } + return new Cells(rv,null); + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java index 01c96a62..750f725f 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java @@ -58,103 +58,103 @@ import aaf.v2_0.Perms; * */ public class PermDetail extends Page { - public static final String HREF = "/gui/permdetail"; - public static final String NAME = "PermDetail"; - private static final String BLANK = ""; + public static final String HREF = "/gui/permdetail"; + public static final String NAME = "PermDetail"; + private static final String BLANK = ""; - public PermDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME, HREF, new String[] {"type","instance","action"}, - new BreadCrumbs(breadcrumbs), - new Table("Permission Details",gui.env.newTransNoAvg(),new Model(gui.env),"class=detail") - ); - } + public PermDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME, HREF, new String[] {"type","instance","action"}, + new BreadCrumbs(breadcrumbs), + new Table("Permission Details",gui.env.newTransNoAvg(),new Model(gui.env),"class=detail") + ); + } - /** - * Implement the table content for Permissions Detail - * - * @author Jonathan - * - */ - private static class Model extends TableData { - private Slot type, instance, action; - public Model(AuthzEnv env) { - type = env.slot(NAME+".type"); - instance = env.slot(NAME+".instance"); - action = env.slot(NAME+".action"); - } + /** + * Implement the table content for Permissions Detail + * + * @author Jonathan + * + */ + private static class Model extends TableData { + private Slot type, instance, action; + public Model(AuthzEnv env) { + type = env.slot(NAME+".type"); + instance = env.slot(NAME+".instance"); + action = env.slot(NAME+".action"); + } - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String pType = trans.get(type, null); - final String pInstance = trans.get(instance, null); - final String pAction = trans.get(action, null); - Validator v = new Validator(); - v.permType(pType) - .permInstance(pInstance) - .permAction(pAction); - - if(v.err()) { - trans.warn().printf("Error in PermDetail Request: %s", v.errs()); - return Cells.EMPTY; - } - final ArrayList rv = new ArrayList<>(); - rv.add(new AbsCell[]{new TextCell("Type:"),new TextCell(pType)}); - rv.add(new AbsCell[]{new TextCell("Instance:"),new TextCell(pInstance)}); - rv.add(new AbsCell[]{new TextCell("Action:"),new TextCell(pAction)}); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client)throws CadiException, ConnectException, APIException { - TimeTaken tt = trans.start("AAF Perm Details",Env.REMOTE); - try { - Future fp= client.read("/authz/perms/"+pType + '/' + pInstance + '/' + pAction,gui.getDF(Perms.class)); - - if(fp.get(AAF_GUI.TIMEOUT)) { - tt.done(); - tt = trans.start("Load Data", Env.SUB); - List ps = fp.value.getPerm(); - if(!ps.isEmpty()) { - Perm perm = fp.value.getPerm().get(0); - String desc = (perm.getDescription()!=null?perm.getDescription():BLANK); - rv.add(new AbsCell[]{new TextCell("Description:"),new TextCell(desc)}); - boolean first=true; - for(String r : perm.getRoles()) { - if(first){ - first=false; - rv.add(new AbsCell[] { - new TextCell("Associated Roles:"), - new TextCell(r) - }); - } else { - rv.add(new AbsCell[] { - AbsCell.Null, - new TextCell(r) - }); - } - } - } - String historyLink = PermHistory.HREF - + "?type=" + pType + "&instance=" + pInstance + "&action=" + pAction; - - rv.add(new AbsCell[] {new RefCell("See History",historyLink,false)}); - } else { - rv.add(new AbsCell[] {new TextCell( - fp.code()==HttpStatus.NOT_FOUND_404? - "*** Implicit Permission ***": - "*** Data Unavailable ***" - )}); - } - } finally { - tt.done(); - } + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String pType = trans.get(type, null); + final String pInstance = trans.get(instance, null); + final String pAction = trans.get(action, null); + Validator v = new Validator(); + v.permType(pType) + .permInstance(pInstance) + .permAction(pAction); + + if(v.err()) { + trans.warn().printf("Error in PermDetail Request: %s", v.errs()); + return Cells.EMPTY; + } + final ArrayList rv = new ArrayList<>(); + rv.add(new AbsCell[]{new TextCell("Type:"),new TextCell(pType)}); + rv.add(new AbsCell[]{new TextCell("Instance:"),new TextCell(pInstance)}); + rv.add(new AbsCell[]{new TextCell("Action:"),new TextCell(pAction)}); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client)throws CadiException, ConnectException, APIException { + TimeTaken tt = trans.start("AAF Perm Details",Env.REMOTE); + try { + Future fp= client.read("/authz/perms/"+pType + '/' + pInstance + '/' + pAction,gui.getDF(Perms.class)); + + if(fp.get(AAF_GUI.TIMEOUT)) { + tt.done(); + tt = trans.start("Load Data", Env.SUB); + List ps = fp.value.getPerm(); + if(!ps.isEmpty()) { + Perm perm = fp.value.getPerm().get(0); + String desc = (perm.getDescription()!=null?perm.getDescription():BLANK); + rv.add(new AbsCell[]{new TextCell("Description:"),new TextCell(desc)}); + boolean first=true; + for(String r : perm.getRoles()) { + if(first){ + first=false; + rv.add(new AbsCell[] { + new TextCell("Associated Roles:"), + new TextCell(r) + }); + } else { + rv.add(new AbsCell[] { + AbsCell.Null, + new TextCell(r) + }); + } + } + } + String historyLink = PermHistory.HREF + + "?type=" + pType + "&instance=" + pInstance + "&action=" + pAction; + + rv.add(new AbsCell[] {new RefCell("See History",historyLink,false)}); + } else { + rv.add(new AbsCell[] {new TextCell( + fp.code()==HttpStatus.NOT_FOUND_404? + "*** Implicit Permission ***": + "*** Data Unavailable ***" + )}); + } + } finally { + tt.done(); + } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - return new Cells(rv,null); - } - } -} - \ No newline at end of file + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + return new Cells(rv,null); + } + } +} + \ No newline at end of file diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java index dd854660..8839ed81 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java @@ -45,91 +45,91 @@ import aaf.v2_0.Pkey; import aaf.v2_0.RolePermRequest; public class PermGrantAction extends Page { - - - public PermGrantAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,PermGrantForm.NAME, PermGrantForm.HREF, PermGrantForm.fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - final Slot sType = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[0]); - final Slot sInstance = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[1]); - final Slot sAction = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[2]); - final Slot sRole = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[3]); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + + + public PermGrantAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,PermGrantForm.NAME, PermGrantForm.HREF, PermGrantForm.fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + final Slot sType = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[0]); + final Slot sInstance = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[1]); + final Slot sAction = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[2]); + final Slot sRole = gui.env.slot(PermGrantForm.NAME+'.'+PermGrantForm.fields[3]); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String type = trans.get(sType,null); - String instance = trans.get(sInstance,null); - String action = trans.get(sAction,null); - String role = trans.get(sRole,null); - - String lastPage = PermGrantForm.HREF - + "?type=" + type + "&instance=" + instance + "&action=" + action; - - // Run Validations - boolean fail = true; - - TimeTaken tt = trans.start("AAF Grant Permission to Role",Env.REMOTE); - try { - - final RolePermRequest grantReq = new RolePermRequest(); - Pkey pkey = new Pkey(); - pkey.setType(type); - pkey.setInstance(instance); - pkey.setAction(action); - grantReq.setPerm(pkey); - grantReq.setRole(role); - - fail = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { - boolean fail = true; - Future fgrant = client.create( - "/authz/role/perm", - gui.getDF(RolePermRequest.class), - grantReq - ); + String type = trans.get(sType,null); + String instance = trans.get(sInstance,null); + String action = trans.get(sAction,null); + String role = trans.get(sRole,null); + + String lastPage = PermGrantForm.HREF + + "?type=" + type + "&instance=" + instance + "&action=" + action; + + // Run Validations + boolean fail = true; + + TimeTaken tt = trans.start("AAF Grant Permission to Role",Env.REMOTE); + try { + + final RolePermRequest grantReq = new RolePermRequest(); + Pkey pkey = new Pkey(); + pkey.setType(type); + pkey.setInstance(instance); + pkey.setAction(action); + grantReq.setPerm(pkey); + grantReq.setRole(role); + + fail = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { + boolean fail = true; + Future fgrant = client.create( + "/authz/role/perm", + gui.getDF(RolePermRequest.class), + grantReq + ); - if(fgrant.get(5000)) { - hgen.p("Permission has been granted to role."); - fail = false; - } else { - if (202==fgrant.code()) { - hgen.p("Permission Grant Request sent, but must be Approved before actualizing"); - fail = false; - } else { - gui.writeError(trans, fgrant, hgen, 0); - } - } - return fail; - } - }); - } catch (Exception e) { - hgen.p("Unknown Error"); - e.printStackTrace(); - } finally { - tt.done(); - } - - hgen.br(); - hgen.incr("a",true,"href="+lastPage); - if (fail) { - hgen.text("Try again"); - } else { - hgen.text("Grant this Permission to Another Role"); - } - hgen.end(); - hgen.js() - .text("alterLink('permgrant', '"+lastPage + "');") - .done(); + if(fgrant.get(5000)) { + hgen.p("Permission has been granted to role."); + fail = false; + } else { + if (202==fgrant.code()) { + hgen.p("Permission Grant Request sent, but must be Approved before actualizing"); + fail = false; + } else { + gui.writeError(trans, fgrant, hgen, 0); + } + } + return fail; + } + }); + } catch (Exception e) { + hgen.p("Unknown Error"); + e.printStackTrace(); + } finally { + tt.done(); + } + + hgen.br(); + hgen.incr("a",true,"href="+lastPage); + if (fail) { + hgen.text("Try again"); + } else { + hgen.text("Grant this Permission to Another Role"); + } + hgen.end(); + hgen.js() + .text("alterLink('permgrant', '"+lastPage + "');") + .done(); - } - }); - } - }); - } + } + }); + } + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java index db3d741b..1ecf3d30 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java @@ -50,108 +50,108 @@ import aaf.v2_0.Role; import aaf.v2_0.Roles; public class PermGrantForm extends Page { - static final String HREF = "/gui/permgrant"; - static final String NAME = "Permission Grant"; - static final String fields[] = {"type","instance","action","role"}; - - public PermGrantForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final Slot type = gui.env.slot(NAME+".type"); - final Slot instance = gui.env.slot(NAME+".instance"); - final Slot action = gui.env.slot(NAME+".action"); - final Slot role = gui.env.slot(NAME+".role"); - // p tags not closing right using .p() - causes issues in IE8 password form - so using leaf for the moment - hgen.leaf("p").text("Choose a role to grant to this permission").end() - .incr("form","method=post"); - Mark table = new Mark(TABLE); - hgen.incr(table); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - - Mark copyRoleJS = new Mark(); - hgen.js(copyRoleJS); - hgen.text("function copyRole(role) {"); - hgen.text("var txtRole = document.querySelector(\"#role\");"); -// hgen.text("if (role==;"); - hgen.text("txtRole.value=role;"); - hgen.text("}"); - hgen.end(copyRoleJS); - - String typeValue = trans.get(type, ""); - String instanceValue = trans.get(instance, ""); - String actionValue = trans.get(action, ""); - String roleValue = trans.get(role,null); - List myRoles = getMyRoles(gui, trans); - hgen - .input(fields[0],"Perm Type",true,"value="+typeValue,"disabled") - .input(fields[1],"Perm Instance",true,"value="+instanceValue,"disabled") - .input(fields[2],"Perm Action",true,"value="+actionValue,"disabled"); - - // select & options are not an input type, so we must create table row & cell tags - Mark selectRow = new Mark(); - hgen - .incr(selectRow, "tr") - .incr("td") - .incr("label", "for=myroles", "required").text("My Roles").end() - .end() - .incr("td") - .incr("select", "name=myroles", "id=myroles", "onchange=copyRole(this.value)") - .incr("option", "value=").text("Select one of my roles").end(); - for (String role : myRoles) { - hgen.incr("option", "value="+role).text(role).end(); - } - hgen - .incr("option", "value=").text("Other").end() - .end(selectRow); - if(roleValue==null) { - hgen.input(fields[3],"Role", true, "placeholder=or type a role here"); - } else { - hgen.input(fields[3],"Role",true, "value="+roleValue); - } - hgen.end(); - } - }); - hgen.end(); - hgen.tagOnly("input", "type=submit", "value=Submit") - .end(); + static final String HREF = "/gui/permgrant"; + static final String NAME = "Permission Grant"; + static final String fields[] = {"type","instance","action","role"}; + + public PermGrantForm(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final Slot type = gui.env.slot(NAME+".type"); + final Slot instance = gui.env.slot(NAME+".instance"); + final Slot action = gui.env.slot(NAME+".action"); + final Slot role = gui.env.slot(NAME+".role"); + // p tags not closing right using .p() - causes issues in IE8 password form - so using leaf for the moment + hgen.leaf("p").text("Choose a role to grant to this permission").end() + .incr("form","method=post"); + Mark table = new Mark(TABLE); + hgen.incr(table); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + + Mark copyRoleJS = new Mark(); + hgen.js(copyRoleJS); + hgen.text("function copyRole(role) {"); + hgen.text("var txtRole = document.querySelector(\"#role\");"); +// hgen.text("if (role==;"); + hgen.text("txtRole.value=role;"); + hgen.text("}"); + hgen.end(copyRoleJS); + + String typeValue = trans.get(type, ""); + String instanceValue = trans.get(instance, ""); + String actionValue = trans.get(action, ""); + String roleValue = trans.get(role,null); + List myRoles = getMyRoles(gui, trans); + hgen + .input(fields[0],"Perm Type",true,"value="+typeValue,"disabled") + .input(fields[1],"Perm Instance",true,"value="+instanceValue,"disabled") + .input(fields[2],"Perm Action",true,"value="+actionValue,"disabled"); + + // select & options are not an input type, so we must create table row & cell tags + Mark selectRow = new Mark(); + hgen + .incr(selectRow, "tr") + .incr("td") + .incr("label", "for=myroles", "required").text("My Roles").end() + .end() + .incr("td") + .incr("select", "name=myroles", "id=myroles", "onchange=copyRole(this.value)") + .incr("option", "value=").text("Select one of my roles").end(); + for (String role : myRoles) { + hgen.incr("option", "value="+role).text(role).end(); + } + hgen + .incr("option", "value=").text("Other").end() + .end(selectRow); + if(roleValue==null) { + hgen.input(fields[3],"Role", true, "placeholder=or type a role here"); + } else { + hgen.input(fields[3],"Role",true, "value="+roleValue); + } + hgen.end(); + } + }); + hgen.end(); + hgen.tagOnly("input", "type=submit", "value=Submit") + .end(); - } - }); - } - - private static List getMyRoles(final AAF_GUI gui, final AuthzTrans trans) { - final List myRoles = new ArrayList<>(); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - TimeTaken tt = trans.start("AAF get my roles",Env.REMOTE); - try { - Future fr = client.read("/authz/roles/user/"+trans.user(),gui.getDF(Roles.class)); - if(fr.get(5000)) { - tt.done(); - tt = trans.start("Load Data", Env.SUB); - if (fr.value != null) for (Role r : fr.value.getRole()) { - myRoles.add(r.getName()); - } - } else { - gui.writeError(trans, fr, null, 0); - } - } finally { - tt.done(); - } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(); - } + } + }); + } + + private static List getMyRoles(final AAF_GUI gui, final AuthzTrans trans) { + final List myRoles = new ArrayList<>(); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + TimeTaken tt = trans.start("AAF get my roles",Env.REMOTE); + try { + Future fr = client.read("/authz/roles/user/"+trans.user(),gui.getDF(Roles.class)); + if(fr.get(5000)) { + tt.done(); + tt = trans.start("Load Data", Env.SUB); + if (fr.value != null) for (Role r : fr.value.getRole()) { + myRoles.add(r.getName()); + } + } else { + gui.writeError(trans, fr, null, 0); + } + } finally { + tt.done(); + } + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(); + } - return myRoles; - } + return myRoles; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java index 37a2c22d..f3464bf9 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java @@ -57,184 +57,184 @@ import aaf.v2_0.History.Item; public class PermHistory extends Page { - static final String NAME="PermHistory"; - static final String HREF = "/gui/permHistory"; - static final String FIELDS[] = {"type","instance","action","dates"}; - static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; - static enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, - AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; - - public PermHistory(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, FIELDS, - new BreadCrumbs(breadcrumbs), - new Table("History", gui.env.newTransNoAvg(),new Model(gui.env),"class=std"), - new NamedCode(true, "content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final Slot sType = gui.env.slot(NAME+".type"); - final Slot sInstance = gui.env.slot(NAME+".instance"); - final Slot sAction = gui.env.slot(NAME+".action"); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String type = trans.get(sType, null); - String instance = trans.get(sInstance,null); - String action = trans.get(sAction,null); - - // Use Javascript to make the table title more descriptive - hgen.js() - .text("var caption = document.querySelector(\".title\");") - .text("caption.innerHTML='History for Permission [ " + type + " ]';") - .done(); - - // Use Javascript to change Link Target to our last visited Detail page - String lastPage = PermDetail.HREF + "?type=" + type - + "&instance=" + instance - + "&action=" + action; - hgen.js() - .text("alterLink('permdetail', '"+lastPage + "');") - .done(); - - hgen.br(); - hgen.leaf("a", "href=#advanced_search", "onclick=divVisibility('advanced_search');").text("Advanced Search").end() - .divID("advanced_search", "style=display:none"); - hgen.incr("table"); - - addDateRow(hgen,"Start Date"); - addDateRow(hgen,"End Date"); - hgen.incr("tr").incr("td"); - hgen.tagOnly("input", "type=button","value=Get History", - "onclick=datesURL('"+HREF+"?type=" + type - + "&instance=" + instance - + "&action=" + action+"');"); - hgen.end().end(); - hgen.end(); - hgen.end(); - } - }); - } - } + static final String NAME="PermHistory"; + static final String HREF = "/gui/permHistory"; + static final String FIELDS[] = {"type","instance","action","dates"}; + static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; + static enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, + AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; + + public PermHistory(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, FIELDS, + new BreadCrumbs(breadcrumbs), + new Table("History", gui.env.newTransNoAvg(),new Model(gui.env),"class=std"), + new NamedCode(true, "content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final Slot sType = gui.env.slot(NAME+".type"); + final Slot sInstance = gui.env.slot(NAME+".instance"); + final Slot sAction = gui.env.slot(NAME+".action"); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String type = trans.get(sType, null); + String instance = trans.get(sInstance,null); + String action = trans.get(sAction,null); + + // Use Javascript to make the table title more descriptive + hgen.js() + .text("var caption = document.querySelector(\".title\");") + .text("caption.innerHTML='History for Permission [ " + type + " ]';") + .done(); + + // Use Javascript to change Link Target to our last visited Detail page + String lastPage = PermDetail.HREF + "?type=" + type + + "&instance=" + instance + + "&action=" + action; + hgen.js() + .text("alterLink('permdetail', '"+lastPage + "');") + .done(); + + hgen.br(); + hgen.leaf("a", "href=#advanced_search", "onclick=divVisibility('advanced_search');").text("Advanced Search").end() + .divID("advanced_search", "style=display:none"); + hgen.incr("table"); + + addDateRow(hgen,"Start Date"); + addDateRow(hgen,"End Date"); + hgen.incr("tr").incr("td"); + hgen.tagOnly("input", "type=button","value=Get History", + "onclick=datesURL('"+HREF+"?type=" + type + + "&instance=" + instance + + "&action=" + action+"');"); + hgen.end().end(); + hgen.end(); + hgen.end(); + } + }); + } + } - ); - - } - - private static void addDateRow(HTMLGen hgen, String s) { - hgen - .incr("tr") - .incr("td") - .incr("label", "for=month", "required").text(s+"*").end() - .end() - .incr("td") - .incr("select", "name=month"+s.substring(0, s.indexOf(' ')), "id=month"+s.substring(0, s.indexOf(' ')), "required") - .incr("option", "value=").text("Month").end(); - for (Month m : Month.values()) { - if (Calendar.getInstance().get(Calendar.MONTH) == m.ordinal()) { - hgen.incr("option", "selected", "value="+(m.ordinal()+1)).text(m.name()).end(); - } else { - hgen.incr("option", "value="+(m.ordinal()+1)).text(m.name()).end(); - } - } - hgen.end() - .end() - .incr("td") - .tagOnly("input","type=number","id=year"+s.substring(0, s.indexOf(' ')),"required", - "value="+Calendar.getInstance().get(Calendar.YEAR), "min=1900", - "max="+Calendar.getInstance().get(Calendar.YEAR), - "placeholder=Year").end() - .end(); - } - - /** - * Implement the Table Content for History - * - * @author Jeremiah - * - */ - private static class Model extends TableData { - private static final String[] headers = new String[] {"Date","User","Memo"}; - private Slot sType; - private Slot sDates; - - public Model(AuthzEnv env) { - sType = env.slot(NAME+".type"); - sDates = env.slot(NAME+".dates"); - } - - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String oName = trans.get(sType,null); - final String oDates = trans.get(sDates,null); - - if(oName==null) { - return Cells.EMPTY; - } - - final ArrayList rv = new ArrayList<>(); - String msg = null; - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - TimeTaken tt = trans.start("AAF Get History for Permission ["+oName+"]",Env.REMOTE); - try { - if (oDates != null) { - client.setQueryParams("yyyymm="+oDates); - } - Future fh = client.read( - "/authz/hist/perm/"+oName, - gui.getDF(History.class) - ); - - - if (fh.get(AAF_GUI.TIMEOUT)) { - tt.done(); - tt = trans.start("Load History Data", Env.SUB); - List histItems = fh.value.getItem(); - - java.util.Collections.sort(histItems, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return o2.getTimestamp().compare(o1.getTimestamp()); - } - }); - - for (Item i : histItems) { - String user = i.getUser(); - AbsCell userCell = new TextCell(user); - String memo = i.getMemo().replace("", "</script>"); - rv.add(new AbsCell[] { - new TextCell(i.getTimestamp().toGregorianCalendar().getTime().toString()), - userCell, - new TextCell(memo) - }); - } - - } else { - if (fh.code()==403) { - rv.add(new AbsCell[] {new TextCell("You may not view History of Permission [" + oName + "]", "colspan = 3", "class=center")}); - } else { - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***", "colspan = 3", "class=center")}); - } - } - } finally { - tt.done(); - } + ); + + } + + private static void addDateRow(HTMLGen hgen, String s) { + hgen + .incr("tr") + .incr("td") + .incr("label", "for=month", "required").text(s+"*").end() + .end() + .incr("td") + .incr("select", "name=month"+s.substring(0, s.indexOf(' ')), "id=month"+s.substring(0, s.indexOf(' ')), "required") + .incr("option", "value=").text("Month").end(); + for (Month m : Month.values()) { + if (Calendar.getInstance().get(Calendar.MONTH) == m.ordinal()) { + hgen.incr("option", "selected", "value="+(m.ordinal()+1)).text(m.name()).end(); + } else { + hgen.incr("option", "value="+(m.ordinal()+1)).text(m.name()).end(); + } + } + hgen.end() + .end() + .incr("td") + .tagOnly("input","type=number","id=year"+s.substring(0, s.indexOf(' ')),"required", + "value="+Calendar.getInstance().get(Calendar.YEAR), "min=1900", + "max="+Calendar.getInstance().get(Calendar.YEAR), + "placeholder=Year").end() + .end(); + } + + /** + * Implement the Table Content for History + * + * @author Jeremiah + * + */ + private static class Model extends TableData { + private static final String[] headers = new String[] {"Date","User","Memo"}; + private Slot sType; + private Slot sDates; + + public Model(AuthzEnv env) { + sType = env.slot(NAME+".type"); + sDates = env.slot(NAME+".dates"); + } + + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String oName = trans.get(sType,null); + final String oDates = trans.get(sDates,null); + + if(oName==null) { + return Cells.EMPTY; + } + + final ArrayList rv = new ArrayList<>(); + String msg = null; + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + TimeTaken tt = trans.start("AAF Get History for Permission ["+oName+"]",Env.REMOTE); + try { + if (oDates != null) { + client.setQueryParams("yyyymm="+oDates); + } + Future fh = client.read( + "/authz/hist/perm/"+oName, + gui.getDF(History.class) + ); + + + if (fh.get(AAF_GUI.TIMEOUT)) { + tt.done(); + tt = trans.start("Load History Data", Env.SUB); + List histItems = fh.value.getItem(); + + java.util.Collections.sort(histItems, new Comparator() { + @Override + public int compare(Item o1, Item o2) { + return o2.getTimestamp().compare(o1.getTimestamp()); + } + }); + + for (Item i : histItems) { + String user = i.getUser(); + AbsCell userCell = new TextCell(user); + String memo = i.getMemo().replace("", "</script>"); + rv.add(new AbsCell[] { + new TextCell(i.getTimestamp().toGregorianCalendar().getTime().toString()), + userCell, + new TextCell(memo) + }); + } + + } else { + if (fh.code()==403) { + rv.add(new AbsCell[] {new TextCell("You may not view History of Permission [" + oName + "]", "colspan = 3", "class=center")}); + } else { + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***", "colspan = 3", "class=center")}); + } + } + } finally { + tt.done(); + } - return null; - } - }); - - } catch (Exception e) { - trans.error().log(e); - } - return new Cells(rv,msg); - } - } + return null; + } + }); + + } catch (Exception e) { + trans.error().log(e); + } + return new Cells(rv,msg); + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java index 9b39945d..22ba95b9 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java @@ -53,69 +53,69 @@ import aaf.v2_0.Perms; * */ public class PermsShow extends Page { - public static final String HREF = "/gui/myperms"; - - public PermsShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, "MyPerms",HREF, NO_FIELDS, - new BreadCrumbs(breadcrumbs), - new Table("Permissions",gui.env.newTransNoAvg(),new Model(), "class=std")); - } + public static final String HREF = "/gui/myperms"; + + public PermsShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, "MyPerms",HREF, NO_FIELDS, + new BreadCrumbs(breadcrumbs), + new Table("Permissions",gui.env.newTransNoAvg(),new Model(), "class=std")); + } - /** - * Implement the Table Content for Permissions by User - * - * @author Jonathan - * - */ - private static class Model extends TableData { - private static final String[] headers = new String[] {"Type","Instance","Action"}; + /** + * Implement the Table Content for Permissions by User + * + * @author Jonathan + * + */ + private static class Model extends TableData { + private static final String[] headers = new String[] {"Type","Instance","Action"}; - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final ArrayList rv = new ArrayList<>(); - TimeTaken tt = trans.start("AAF Perms by User",Env.REMOTE); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fp = client.read("/authz/perms/user/"+trans.user(), gui.getDF(Perms.class)); - if(fp.get(5000)) { - TimeTaken ttld = trans.start("Load Data", Env.SUB); - try { - if(fp.value!=null) { - for(Perm p : fp.value.getPerm()) { - AbsCell[] sa = new AbsCell[] { - new RefCell(p.getType(),PermDetail.HREF - +"?type="+p.getType() - +"&instance="+p.getInstance() - +"&action="+p.getAction(), - false), - new TextCell(p.getInstance()), - new TextCell(p.getAction()) - }; - rv.add(sa); - } - } else { - gui.writeError(trans, fp, null,0); - } - } finally { - ttld.done(); - } - } - return null; - } - }); - } catch (Exception e) { - trans.error().log(e); - } finally { - tt.done(); - } - return new Cells(rv,null); - } - } + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final ArrayList rv = new ArrayList<>(); + TimeTaken tt = trans.start("AAF Perms by User",Env.REMOTE); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fp = client.read("/authz/perms/user/"+trans.user(), gui.getDF(Perms.class)); + if(fp.get(5000)) { + TimeTaken ttld = trans.start("Load Data", Env.SUB); + try { + if(fp.value!=null) { + for(Perm p : fp.value.getPerm()) { + AbsCell[] sa = new AbsCell[] { + new RefCell(p.getType(),PermDetail.HREF + +"?type="+p.getType() + +"&instance="+p.getInstance() + +"&action="+p.getAction(), + false), + new TextCell(p.getInstance()), + new TextCell(p.getAction()) + }; + rv.add(sa); + } + } else { + gui.writeError(trans, fp, null,0); + } + } finally { + ttld.done(); + } + } + return null; + } + }); + } catch (Exception e) { + trans.error().log(e); + } finally { + tt.done(); + } + return new Cells(rv,null); + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java index 3e959ef5..0d0d03ad 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java @@ -51,124 +51,124 @@ import aaf.v2_0.Approval; import aaf.v2_0.Approvals; public class RequestDetail extends Page { - public static final String HREF = "/gui/requestdetail"; - public static final String NAME = "RequestDetail"; - private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; - public static final String[] FIELDS = {"ticket"}; + public static final String HREF = "/gui/requestdetail"; + public static final String NAME = "RequestDetail"; + private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; + public static final String[] FIELDS = {"ticket"}; - public RequestDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME, HREF, FIELDS, - new BreadCrumbs(breadcrumbs), - new Table("Request Details",gui.env.newTransNoAvg(),new Model(gui.env),"class=detail") - ); - } + public RequestDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME, HREF, FIELDS, + new BreadCrumbs(breadcrumbs), + new Table("Request Details",gui.env.newTransNoAvg(),new Model(gui.env),"class=detail") + ); + } - /** - * Implement the table content for Request Detail - * - * @author Jeremiah - * - */ - private static class Model extends TableData { - final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; - private Slot sTicket; - public Model(AuthzEnv env) { - sTicket = env.slot(NAME+".ticket"); - } + /** + * Implement the table content for Request Detail + * + * @author Jeremiah + * + */ + private static class Model extends TableData { + final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; + private Slot sTicket; + public Model(AuthzEnv env) { + sTicket = env.slot(NAME+".ticket"); + } - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - Cells rv=Cells.EMPTY; - final String ticket = trans.get(sTicket, null); - if(ticket!=null) { - try { - rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Cells code(Rcli client) throws CadiException, ConnectException, APIException { - TimeTaken tt = trans.start("AAF Approval Details",Env.REMOTE); - ArrayList rv = new ArrayList<>(); - try { - Future fa = client.read( - "/authz/approval/ticket/"+ticket, - gui.getDF(Approvals.class) - ); - - if(fa.get(AAF_GUI.TIMEOUT)) { - if (!trans.user().equals(fa.value.getApprovals().get(0).getUser())) { - return Cells.EMPTY; - } - tt.done(); - tt = trans.start("Load Data", Env.SUB); - boolean first = true; - for ( Approval approval : fa.value.getApprovals()) { - AbsCell[] approverLine = new AbsCell[4]; - // only print common elements once - if (first) { - DateFormat createdDF = new SimpleDateFormat(DATE_TIME_FORMAT); - UUID id = UUID.fromString(approval.getId()); - - rv.add(new AbsCell[]{new TextCell("Ticket ID:"),new TextCell(approval.getTicket(),"colspan=3")}); - rv.add(new AbsCell[]{new TextCell("Memo:"),new TextCell(approval.getMemo(),"colspan=3")}); - rv.add(new AbsCell[]{new TextCell("Requested On:"), - new TextCell(createdDF.format((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000),"colspan=3") - }); - rv.add(new AbsCell[]{new TextCell("Operation:"),new TextCell(decodeOp(approval.getOperation()),"colspan=3")}); - String user = approval.getUser(); - rv.add(new AbsCell[]{new TextCell("User:"),new TextCell(user,"colspan=3")}); - - // headers for listing each approver - rv.add(new AbsCell[]{new TextCell(" ","colspan=4","class=blank_line")}); - rv.add(new AbsCell[]{AbsCell.Null, - new TextCell("Approver","class=bold"), - new TextCell("Type","class=bold"), - new TextCell("Status","class=bold")}); - approverLine[0] = new TextCell("Approvals:"); - - first = false; - } else { - approverLine[0] = AbsCell.Null; - } - - approverLine[1] = new TextCell(approval.getApprover()); - String type = approval.getType(); - if ("owner".equalsIgnoreCase(type)) { - type = "resource owner"; - } - - approverLine[2] = new TextCell(type); - approverLine[3] = new TextCell(approval.getStatus()); - rv.add(approverLine); - - } - } else { - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); - } - } finally { - tt.done(); - } - return new Cells(rv,null); - } - }); - } catch (Exception e) { - trans.error().log(e); - } - } - return rv; - } + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + Cells rv=Cells.EMPTY; + final String ticket = trans.get(sTicket, null); + if(ticket!=null) { + try { + rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Cells code(Rcli client) throws CadiException, ConnectException, APIException { + TimeTaken tt = trans.start("AAF Approval Details",Env.REMOTE); + ArrayList rv = new ArrayList<>(); + try { + Future fa = client.read( + "/authz/approval/ticket/"+ticket, + gui.getDF(Approvals.class) + ); + + if(fa.get(AAF_GUI.TIMEOUT)) { + if (!trans.user().equals(fa.value.getApprovals().get(0).getUser())) { + return Cells.EMPTY; + } + tt.done(); + tt = trans.start("Load Data", Env.SUB); + boolean first = true; + for ( Approval approval : fa.value.getApprovals()) { + AbsCell[] approverLine = new AbsCell[4]; + // only print common elements once + if (first) { + DateFormat createdDF = new SimpleDateFormat(DATE_TIME_FORMAT); + UUID id = UUID.fromString(approval.getId()); + + rv.add(new AbsCell[]{new TextCell("Ticket ID:"),new TextCell(approval.getTicket(),"colspan=3")}); + rv.add(new AbsCell[]{new TextCell("Memo:"),new TextCell(approval.getMemo(),"colspan=3")}); + rv.add(new AbsCell[]{new TextCell("Requested On:"), + new TextCell(createdDF.format((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000),"colspan=3") + }); + rv.add(new AbsCell[]{new TextCell("Operation:"),new TextCell(decodeOp(approval.getOperation()),"colspan=3")}); + String user = approval.getUser(); + rv.add(new AbsCell[]{new TextCell("User:"),new TextCell(user,"colspan=3")}); + + // headers for listing each approver + rv.add(new AbsCell[]{new TextCell(" ","colspan=4","class=blank_line")}); + rv.add(new AbsCell[]{AbsCell.Null, + new TextCell("Approver","class=bold"), + new TextCell("Type","class=bold"), + new TextCell("Status","class=bold")}); + approverLine[0] = new TextCell("Approvals:"); + + first = false; + } else { + approverLine[0] = AbsCell.Null; + } + + approverLine[1] = new TextCell(approval.getApprover()); + String type = approval.getType(); + if ("owner".equalsIgnoreCase(type)) { + type = "resource owner"; + } + + approverLine[2] = new TextCell(type); + approverLine[3] = new TextCell(approval.getStatus()); + rv.add(approverLine); + + } + } else { + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); + } + } finally { + tt.done(); + } + return new Cells(rv,null); + } + }); + } catch (Exception e) { + trans.error().log(e); + } + } + return rv; + } - private String decodeOp(String operation) { - if ("C".equalsIgnoreCase(operation)) { - return "Create"; - } else if ("D".equalsIgnoreCase(operation)) { - return "Delete"; - } else if ("U".equalsIgnoreCase(operation)) { - return "Update"; - } else if ("G".equalsIgnoreCase(operation)) { - return "Grant"; - } else if ("UG".equalsIgnoreCase(operation)) { - return "Un-Grant"; - } - return operation; - } - } + private String decodeOp(String operation) { + if ("C".equalsIgnoreCase(operation)) { + return "Create"; + } else if ("D".equalsIgnoreCase(operation)) { + return "Delete"; + } else if ("U".equalsIgnoreCase(operation)) { + return "Update"; + } else if ("G".equalsIgnoreCase(operation)) { + return "Grant"; + } else if ("UG".equalsIgnoreCase(operation)) { + return "Un-Grant"; + } + return operation; + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java index d7b0da0f..d5a89c2c 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java @@ -68,232 +68,232 @@ import aaf.v2_0.UserRoles; * */ public class RoleDetail extends Page { - public static final String HREF = "/gui/roledetail"; - public static final String NAME = "RoleDetail"; - private static final String BLANK = ""; + public static final String HREF = "/gui/roledetail"; + public static final String NAME = "RoleDetail"; + private static final String BLANK = ""; - public RoleDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, NAME, HREF, new String[] {"role","ns"}, - new BreadCrumbs(breadcrumbs), - new Table("Role Details",gui.env.newTransNoAvg(), - new Model(gui.env),"class=detail") - ); - } + public RoleDetail(final AAF_GUI gui, Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, NAME, HREF, new String[] {"role","ns"}, + new BreadCrumbs(breadcrumbs), + new Table("Role Details",gui.env.newTransNoAvg(), + new Model(gui.env),"class=detail") + ); + } - /** - * Implement the table content for Permissions Detail - * - * @author Jonathan - * - */ - private static class Model extends TableData { - private static final String ACCESS = "access"; - private Slot sRoleName,sRole,sUserRole,sMayWrite,sMayApprove,sMark,sNS; - public Model(AuthzEnv env) { - sRoleName = env.slot(NAME+".role"); - sRole = env.slot(NAME+".data.role"); - sUserRole = env.slot(NAME+".data.userrole"); - sMayWrite = env.slot(NAME+"mayWrite"); - sMayApprove = env.slot(NAME+"mayApprove"); - sMark = env.slot(NAME+"mark"); - sNS = env.slot(NAME+".ns"); - } + /** + * Implement the table content for Permissions Detail + * + * @author Jonathan + * + */ + private static class Model extends TableData { + private static final String ACCESS = "access"; + private Slot sRoleName,sRole,sUserRole,sMayWrite,sMayApprove,sMark,sNS; + public Model(AuthzEnv env) { + sRoleName = env.slot(NAME+".role"); + sRole = env.slot(NAME+".data.role"); + sUserRole = env.slot(NAME+".data.userrole"); + sMayWrite = env.slot(NAME+"mayWrite"); + sMayApprove = env.slot(NAME+"mayApprove"); + sMark = env.slot(NAME+"mark"); + sNS = env.slot(NAME+".ns"); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.gui.table.TableData#prefix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) - */ - @Override - public void prefix(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) { - final String pRole = trans.get(sRoleName, null); - Validator v = new Validator(); - v.role(pRole); - if(v.err()) { - trans.warn().printf("Error in PermDetail Request: %s", v.errs()); - return; - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.gui.table.TableData#prefix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) + */ + @Override + public void prefix(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) { + final String pRole = trans.get(sRoleName, null); + Validator v = new Validator(); + v.role(pRole); + if(v.err()) { + trans.warn().printf("Error in PermDetail Request: %s", v.errs()); + return; + } - - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { - TimeTaken tt = trans.start("AAF Role Details",Env.REMOTE); - try { - Future fr = client.read("/authz/roles/"+pRole+"?ns",gui.getDF(Roles.class)); - Future fur = client.read("/authz/userRoles/role/"+pRole,gui.getDF(UserRoles.class)); - if(fr.get(AAF_GUI.TIMEOUT)) { - List roles = fr.value.getRole(); - if(!roles.isEmpty()) { - Role role = fr.value.getRole().get(0); - trans.put(sRole, role); - Boolean mayWrite = trans.fish(new AAFPermission(role.getNs(),ACCESS,":role:"+role.getName(),"write")); - trans.put(sMayWrite,mayWrite); - Boolean mayApprove = trans.fish(new AAFPermission(role.getNs(),ACCESS,":role:"+role.getName(),"approve")); - trans.put(sMayApprove, mayApprove); - - if(mayWrite || mayApprove) { - Mark js = new Mark(); - Mark fn = new Mark(); - hgen.js(js) - .function(fn,"touchedDesc") - .li("d=document.getElementById('descText');", - "if (d.orig == undefined ) {", - " d.orig = d.value;", - " d.addEventListener('keyup',changedDesc);", - " d.removeEventListener('keypress',touchedDesc);", - "}").end(fn) - .function(fn,"changedDesc") - .li( - "dcb=document.getElementById('descCB');", - "d=document.getElementById('descText');", - "dcb.checked= (d.orig != d.value)" - ).end(fn) - .end(js); - - Mark mark = new Mark(); - hgen.incr(mark,"form","method=post"); - trans.put(sMark, mark); - } - } - } else { - trans.error().printf("Error calling AAF for Roles in GUI, Role Detail %d: %s",fr.code(),fr.body()); - return false; - } - - if(fur.get(AAF_GUI.TIMEOUT)) { - trans.put(sUserRole, fur.value.getUserRole()); - } else { - trans.error().printf("Error calling AAF for UserRoles in GUI, Role Detail %d: %s",fr.code(),fr.body()); - return false; - } + + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { + TimeTaken tt = trans.start("AAF Role Details",Env.REMOTE); + try { + Future fr = client.read("/authz/roles/"+pRole+"?ns",gui.getDF(Roles.class)); + Future fur = client.read("/authz/userRoles/role/"+pRole,gui.getDF(UserRoles.class)); + if(fr.get(AAF_GUI.TIMEOUT)) { + List roles = fr.value.getRole(); + if(!roles.isEmpty()) { + Role role = fr.value.getRole().get(0); + trans.put(sRole, role); + Boolean mayWrite = trans.fish(new AAFPermission(role.getNs(),ACCESS,":role:"+role.getName(),"write")); + trans.put(sMayWrite,mayWrite); + Boolean mayApprove = trans.fish(new AAFPermission(role.getNs(),ACCESS,":role:"+role.getName(),"approve")); + trans.put(sMayApprove, mayApprove); + + if(mayWrite || mayApprove) { + Mark js = new Mark(); + Mark fn = new Mark(); + hgen.js(js) + .function(fn,"touchedDesc") + .li("d=document.getElementById('descText');", + "if (d.orig == undefined ) {", + " d.orig = d.value;", + " d.addEventListener('keyup',changedDesc);", + " d.removeEventListener('keypress',touchedDesc);", + "}").end(fn) + .function(fn,"changedDesc") + .li( + "dcb=document.getElementById('descCB');", + "d=document.getElementById('descText');", + "dcb.checked= (d.orig != d.value)" + ).end(fn) + .end(js); + + Mark mark = new Mark(); + hgen.incr(mark,"form","method=post"); + trans.put(sMark, mark); + } + } + } else { + trans.error().printf("Error calling AAF for Roles in GUI, Role Detail %d: %s",fr.code(),fr.body()); + return false; + } + + if(fur.get(AAF_GUI.TIMEOUT)) { + trans.put(sUserRole, fur.value.getUserRole()); + } else { + trans.error().printf("Error calling AAF for UserRoles in GUI, Role Detail %d: %s",fr.code(),fr.body()); + return false; + } - return true; - } finally { - tt.done(); - } - } - }); - } catch (Exception e) { - trans.error().log(e); - } - } + return true; + } finally { + tt.done(); + } + } + }); + } catch (Exception e) { + trans.error().log(e); + } + } - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String pRole = trans.get(sRoleName, null); - final Role role = trans.get(sRole,null); - ArrayList rv = new ArrayList<>(); - - if(role!=null) { - boolean mayWrite = trans.get(sMayWrite, false); - boolean mayApprove = trans.get(sMayApprove, false); + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String pRole = trans.get(sRoleName, null); + final Role role = trans.get(sRole,null); + ArrayList rv = new ArrayList<>(); + + if(role!=null) { + boolean mayWrite = trans.get(sMayWrite, false); + boolean mayApprove = trans.get(sMayApprove, false); - String desc = (role.getDescription()!=null?role.getDescription():BLANK); - rv.add(new AbsCell[]{ - new TextCell("Role:","width=45%"), - new TextCell(pRole)}); - if(mayWrite) { - rv.add(new AbsCell[]{ - new TextCell("Description:","width=45%"), - new TextInputCell("description","textInput",desc,"id=descText","onkeypress=touchedDesc()"), - new CheckBoxCell("desc",ALIGN.left, "changed","id=descCB", "style=visibility: hidden"), - }); - rv.add(AbsCell.HLINE); - rv.add(new AbsCell[] { - new TextCell("Associated Permissions:","width=25%"), - new TextCell("UnGrant","width=10%"), - }); - } else { - rv.add(new AbsCell[]{ - new TextCell("Description:","width=45%"), - new TextCell(desc)}); - } - boolean protectedRole = role.getName().endsWith(".owner") || - role.getName().endsWith(".admin"); - boolean first = true; - for(Pkey r : role.getPerms()) { - String key=r.getType() + '|' + r.getInstance() + '|' + r.getAction(); - if(mayWrite) { - rv.add(new AbsCell[] { - AbsCell.Null, - protectedRole && r.getType().endsWith(".access") - ?new TextCell("protected","class=protected") // Do not allow ungranting of basic NS perms - :new CheckBoxCell("perm.ungrant",key), - new TextCell("","width=10%"), - new TextCell(key) - }); - } else { - if(first) { - rv.add(new AbsCell[] { - new TextCell("Associated Permissions:","width=45%"), - new TextCell(key) - }); - first=false; - } else { - rv.add(new AbsCell[] { - AbsCell.Null, - new TextCell(key) - }); - } - } - } - - if(mayApprove) { - rv.add(AbsCell.HLINE); + String desc = (role.getDescription()!=null?role.getDescription():BLANK); + rv.add(new AbsCell[]{ + new TextCell("Role:","width=45%"), + new TextCell(pRole)}); + if(mayWrite) { + rv.add(new AbsCell[]{ + new TextCell("Description:","width=45%"), + new TextInputCell("description","textInput",desc,"id=descText","onkeypress=touchedDesc()"), + new CheckBoxCell("desc",ALIGN.left, "changed","id=descCB", "style=visibility: hidden"), + }); + rv.add(AbsCell.HLINE); + rv.add(new AbsCell[] { + new TextCell("Associated Permissions:","width=25%"), + new TextCell("UnGrant","width=10%"), + }); + } else { + rv.add(new AbsCell[]{ + new TextCell("Description:","width=45%"), + new TextCell(desc)}); + } + boolean protectedRole = role.getName().endsWith(".owner") || + role.getName().endsWith(".admin"); + boolean first = true; + for(Pkey r : role.getPerms()) { + String key=r.getType() + '|' + r.getInstance() + '|' + r.getAction(); + if(mayWrite) { + rv.add(new AbsCell[] { + AbsCell.Null, + protectedRole && r.getType().endsWith(".access") + ?new TextCell("protected","class=protected") // Do not allow ungranting of basic NS perms + :new CheckBoxCell("perm.ungrant",key), + new TextCell("","width=10%"), + new TextCell(key) + }); + } else { + if(first) { + rv.add(new AbsCell[] { + new TextCell("Associated Permissions:","width=45%"), + new TextCell(key) + }); + first=false; + } else { + rv.add(new AbsCell[] { + AbsCell.Null, + new TextCell(key) + }); + } + } + } + + if(mayApprove) { + rv.add(AbsCell.HLINE); - // - rv.add(new AbsCell[] { - new TextCell("Users in Role:","width=25%"), - new TextCell("Delete","width=10%"), - new TextCell("Extend","width=10%") - }); + // + rv.add(new AbsCell[] { + new TextCell("Users in Role:","width=25%"), + new TextCell("Delete","width=10%"), + new TextCell("Extend","width=10%") + }); - List userroles = trans.get(sUserRole,null); - if(userroles!=null) { - for(UserRole ur : userroles) { - String tag = "userrole"; - - rv.add(new AbsCell[] { - AbsCell.Null, - new CheckBoxCell(tag+".delete", ur.getUser()), - new CheckBoxCell(tag+".extend", ur.getUser()), - new TextCell(ur.getUser()), - new TextCell(Chrono.dateOnlyStamp(ur.getExpires()) - )}); - } - } - } - - // History - rv.add(new AbsCell[] { - new RefCell("See History",RoleHistory.HREF + "?role=" + pRole,false) - }); - } else { - rv.add(new AbsCell[]{ - new TextCell("Role:"), - new TextCell(pRole)}); + List userroles = trans.get(sUserRole,null); + if(userroles!=null) { + for(UserRole ur : userroles) { + String tag = "userrole"; + + rv.add(new AbsCell[] { + AbsCell.Null, + new CheckBoxCell(tag+".delete", ur.getUser()), + new CheckBoxCell(tag+".extend", ur.getUser()), + new TextCell(ur.getUser()), + new TextCell(Chrono.dateOnlyStamp(ur.getExpires()) + )}); + } + } + } + + // History + rv.add(new AbsCell[] { + new RefCell("See History",RoleHistory.HREF + "?role=" + pRole,false) + }); + } else { + rv.add(new AbsCell[]{ + new TextCell("Role:"), + new TextCell(pRole)}); - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); - } - return new Cells(rv, null); - } + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***")}); + } + return new Cells(rv, null); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.gui.table.TableData#postfix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) - */ - @Override - public void postfix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { - final Mark mark = trans.get(sMark, null); - if(mark!=null) { - hgen.tagOnly("input", "type=submit", "value=Submit"); - final String pNS = trans.get(sNS, null); - if(pNS!=null && pNS.length()>0) { - hgen.leaf(mark,HTMLGen.A,"href="+NsDetail.HREF+"?ns="+pNS,"class=greenbutton").text("Back").end(mark); - } - hgen.end(mark); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.gui.table.TableData#postfix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) + */ + @Override + public void postfix(AAF_GUI state, AuthzTrans trans, final Cache cache, final HTMLGen hgen) { + final Mark mark = trans.get(sMark, null); + if(mark!=null) { + hgen.tagOnly("input", "type=submit", "value=Submit"); + final String pNS = trans.get(sNS, null); + if(pNS!=null && pNS.length()>0) { + hgen.leaf(mark,HTMLGen.A,"href="+NsDetail.HREF+"?ns="+pNS,"class=greenbutton").text("Back").end(mark); + } + hgen.end(mark); + } - } - } -} - \ No newline at end of file + } + } +} + \ No newline at end of file diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java index f9f919a2..1f00d955 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java @@ -54,135 +54,135 @@ import aaf.v2_0.RolePermRequest; import aaf.v2_0.RoleRequest; public class RoleDetailAction extends Page { - public RoleDetailAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,RoleDetail.NAME, RoleDetail.HREF, TableData.headers, - new BreadCrumbs(breadcrumbs), - new NamedCode(true,"content") { - final Slot sReq = gui.env.slot(AAF_GUI.HTTP_SERVLET_REQUEST); - - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final HttpServletRequest req = trans.get(sReq, null); - final String role = getSingleParam(req,"role"); - if(role==null) { - hgen.text("Parameter 'role' is required").end(); - } else { - // Run Validations -// boolean fail; - try { - /*fail =*/ gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { - List ltf = new ArrayList<>(); - String text; - Map pm = (Map)req.getParameterMap(); - for(final Entry es : pm.entrySet()) { - for(final String v : es.getValue()) { - TimeTaken tt = null; - try { - switch(es.getKey()) { - case "desc": // Check box set - String desc = getSingleParam(req, "description"); - if(desc!=null) { - text = "Setting Description on " + role + " to " + desc; - tt = trans.start(text, Env.REMOTE); - RoleRequest rr = new RoleRequest(); - rr.setName(role); - rr.setDescription(desc); - ltf.add(new TypedFuture(ActionType.desc, text, - client.update("/authz/role", - gui.getDF(RoleRequest.class),rr - ))); - } - break; - case "perm.ungrant": - text = "Ungranting Permission '" + v + "' from '" + role + '\''; - tt = trans.start(text, Env.REMOTE); - String[] pf = Split.splitTrim('|', v); - if(pf.length==3) { - Pkey perm = new Pkey(); - perm.setType(pf[0]); - perm.setInstance(pf[1]); - perm.setAction(pf[2]); - RolePermRequest rpr = new RolePermRequest(); - rpr.setPerm(perm); - rpr.setRole(role); - ltf.add(new TypedFuture(ActionType.ungrant,text, - client.delete("/authz/role/" + role + "/perm", - gui.getDF(RolePermRequest.class),rpr - ))); - } else { - hgen.p(v + " is not a valid Perm for ungranting"); - } - break; - case "userrole.extend": - text = "Extending " + v + " in " + role; - tt = trans.start(text, Env.REMOTE); - ltf.add(new TypedFuture(ActionType.extendUR,text, - client.update("/authz/userRole/extend/" + v + '/' + role))); - break; - case "userrole.delete": - text = "Deleting " + v + " from " + role; - tt = trans.start(text, Env.REMOTE); - ltf.add(new TypedFuture(ActionType.deleteUR,text, - client.delete("/authz/userRole/" + v + '/' + role, Void.class))); - break; + public RoleDetailAction(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,RoleDetail.NAME, RoleDetail.HREF, TableData.headers, + new BreadCrumbs(breadcrumbs), + new NamedCode(true,"content") { + final Slot sReq = gui.env.slot(AAF_GUI.HTTP_SERVLET_REQUEST); + + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final HttpServletRequest req = trans.get(sReq, null); + final String role = getSingleParam(req,"role"); + if(role==null) { + hgen.text("Parameter 'role' is required").end(); + } else { + // Run Validations +// boolean fail; + try { + /*fail =*/ gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Boolean code(Rcli client) throws CadiException, ConnectException, APIException { + List ltf = new ArrayList<>(); + String text; + Map pm = (Map)req.getParameterMap(); + for(final Entry es : pm.entrySet()) { + for(final String v : es.getValue()) { + TimeTaken tt = null; + try { + switch(es.getKey()) { + case "desc": // Check box set + String desc = getSingleParam(req, "description"); + if(desc!=null) { + text = "Setting Description on " + role + " to " + desc; + tt = trans.start(text, Env.REMOTE); + RoleRequest rr = new RoleRequest(); + rr.setName(role); + rr.setDescription(desc); + ltf.add(new TypedFuture(ActionType.desc, text, + client.update("/authz/role", + gui.getDF(RoleRequest.class),rr + ))); + } + break; + case "perm.ungrant": + text = "Ungranting Permission '" + v + "' from '" + role + '\''; + tt = trans.start(text, Env.REMOTE); + String[] pf = Split.splitTrim('|', v); + if(pf.length==3) { + Pkey perm = new Pkey(); + perm.setType(pf[0]); + perm.setInstance(pf[1]); + perm.setAction(pf[2]); + RolePermRequest rpr = new RolePermRequest(); + rpr.setPerm(perm); + rpr.setRole(role); + ltf.add(new TypedFuture(ActionType.ungrant,text, + client.delete("/authz/role/" + role + "/perm", + gui.getDF(RolePermRequest.class),rpr + ))); + } else { + hgen.p(v + " is not a valid Perm for ungranting"); + } + break; + case "userrole.extend": + text = "Extending " + v + " in " + role; + tt = trans.start(text, Env.REMOTE); + ltf.add(new TypedFuture(ActionType.extendUR,text, + client.update("/authz/userRole/extend/" + v + '/' + role))); + break; + case "userrole.delete": + text = "Deleting " + v + " from " + role; + tt = trans.start(text, Env.REMOTE); + ltf.add(new TypedFuture(ActionType.deleteUR,text, + client.delete("/authz/userRole/" + v + '/' + role, Void.class))); + break; - default: -// System.out.println(es.getKey() + "=" + v); - } - } finally { - if(tt!=null) { - tt.done(); - tt=null; - } - } - } - } - - if(ltf.isEmpty()) { - hgen.p("No Changes"); - } else { - for(TypedFuture tf : ltf) { - if(tf.future.get(5000)) { - hgen.p("Success: " + tf.text); - } else { - // Note: if handling of special Error codes is required, use - // switch(tf.type) { - // } - hgen.p(tf.text); - gui.writeError(trans, tf.future, hgen,4); - } - } - } - return true; - } - }); - } catch (Exception e) { - hgen.p("Unknown Error"); - e.printStackTrace(); - } - } - } + default: +// System.out.println(es.getKey() + "=" + v); + } + } finally { + if(tt!=null) { + tt.done(); + tt=null; + } + } + } + } + + if(ltf.isEmpty()) { + hgen.p("No Changes"); + } else { + for(TypedFuture tf : ltf) { + if(tf.future.get(5000)) { + hgen.p("Success: " + tf.text); + } else { + // Note: if handling of special Error codes is required, use + // switch(tf.type) { + // } + hgen.p(tf.text); + gui.writeError(trans, tf.future, hgen,4); + } + } + } + return true; + } + }); + } catch (Exception e) { + hgen.p("Unknown Error"); + e.printStackTrace(); + } + } + } - }); - } - }); - } - - enum ActionType {desc, ungrant, deleteUR, extendUR}; - private static class TypedFuture { -// public final ActionType type; - public final Future future; - public final String text; - - public TypedFuture(ActionType type, String text, Future future) { -// this.type = type; - this.future = future; - this.text = text; - } - } + }); + } + }); + } + + enum ActionType {desc, ungrant, deleteUR, extendUR}; + private static class TypedFuture { +// public final ActionType type; + public final Future future; + public final String text; + + public TypedFuture(ActionType type, String text, Future future) { +// this.type = type; + this.future = future; + this.text = text; + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java index 4a9bd362..234b82c2 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java @@ -57,170 +57,170 @@ import aaf.v2_0.History.Item; public class RoleHistory extends Page { - static final String NAME="RoleHistory"; - static final String HREF = "/gui/roleHistory"; - static final String FIELDS[] = {"role","dates"}; - static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; - static enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, - AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; - - public RoleHistory(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME,HREF, FIELDS, - new BreadCrumbs(breadcrumbs), - new Table("History", gui.env.newTransNoAvg(),new Model(gui.env),"class=std"), - new NamedCode(true, "content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final Slot role = gui.env.slot(NAME+".role"); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - String obRole = trans.get(role, null); - - // Use Javascript to make the table title more descriptive - hgen.js() - .text("var caption = document.querySelector(\".title\");") - .text("caption.innerHTML='History for Role [ " + obRole + " ]';") - .done(); - - // Use Javascript to change Link Target to our last visited Detail page - String lastPage = RoleDetail.HREF + "?role=" + obRole; - hgen.js() - .text("alterLink('roledetail', '"+lastPage + "');") - .done(); - - hgen.br(); - hgen.leaf("a", "href=#advanced_search","onclick=divVisibility('advanced_search');").text("Advanced Search").end() - .divID("advanced_search", "style=display:none"); - hgen.incr("table"); - - addDateRow(hgen,"Start Date"); - addDateRow(hgen,"End Date"); - hgen.incr("tr").incr("td"); - hgen.tagOnly("input", "type=button","value=Get History", - "onclick=datesURL('"+HREF+"?role=" + obRole+"');"); - hgen.end().end(); - hgen.end(); - hgen.end(); - } - }); - } - } + static final String NAME="RoleHistory"; + static final String HREF = "/gui/roleHistory"; + static final String FIELDS[] = {"role","dates"}; + static final String WEBPHONE = "http://webphone.att.com/cgi-bin/webphones.pl?id="; + static enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, + AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; + + public RoleHistory(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME,HREF, FIELDS, + new BreadCrumbs(breadcrumbs), + new Table("History", gui.env.newTransNoAvg(),new Model(gui.env),"class=std"), + new NamedCode(true, "content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final Slot role = gui.env.slot(NAME+".role"); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + String obRole = trans.get(role, null); + + // Use Javascript to make the table title more descriptive + hgen.js() + .text("var caption = document.querySelector(\".title\");") + .text("caption.innerHTML='History for Role [ " + obRole + " ]';") + .done(); + + // Use Javascript to change Link Target to our last visited Detail page + String lastPage = RoleDetail.HREF + "?role=" + obRole; + hgen.js() + .text("alterLink('roledetail', '"+lastPage + "');") + .done(); + + hgen.br(); + hgen.leaf("a", "href=#advanced_search","onclick=divVisibility('advanced_search');").text("Advanced Search").end() + .divID("advanced_search", "style=display:none"); + hgen.incr("table"); + + addDateRow(hgen,"Start Date"); + addDateRow(hgen,"End Date"); + hgen.incr("tr").incr("td"); + hgen.tagOnly("input", "type=button","value=Get History", + "onclick=datesURL('"+HREF+"?role=" + obRole+"');"); + hgen.end().end(); + hgen.end(); + hgen.end(); + } + }); + } + } - ); - - } - - private static void addDateRow(HTMLGen hgen, String s) { - hgen - .incr("tr") - .incr("td") - .incr("label", "for=month", "required").text(s+"*").end() - .end() - .incr("td") - .incr("select", "name=month"+s.substring(0, s.indexOf(' ')), "id=month"+s.substring(0, s.indexOf(' ')), "required") - .incr("option", "value=").text("Month").end(); - for (Month m : Month.values()) { - if (Calendar.getInstance().get(Calendar.MONTH) == m.ordinal()) { - hgen.incr("option", "selected", "value="+(m.ordinal()+1)).text(m.name()).end(); - } else { - hgen.incr("option", "value="+(m.ordinal()+1)).text(m.name()).end(); - } - } - hgen.end() - .end() - .incr("td") - .tagOnly("input","type=number","id=year"+s.substring(0, s.indexOf(' ')),"required", - "value="+Calendar.getInstance().get(Calendar.YEAR), "min=1900", - "max="+Calendar.getInstance().get(Calendar.YEAR), - "placeholder=Year").end() - .end(); - } - - - /** - * Implement the Table Content for History - * - * @author Jeremiah - * - */ - private static class Model extends TableData { - private static final String[] headers = new String[] {"Date","User","Memo"}; - private Slot role; - private Slot dates; - - public Model(AuthzEnv env) { - role = env.slot(NAME+".role"); - dates = env.slot(NAME+".dates"); - } - - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - final String oName = trans.get(role,null); - final String oDates = trans.get(dates,null); - - Cells rv = Cells.EMPTY; - if(oName!=null) { - - try { - rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Cells code(Rcli client) throws CadiException, ConnectException, APIException { - ArrayList rv = new ArrayList<>(); - TimeTaken tt = trans.start("AAF Get History for Namespace ["+oName+"]",Env.REMOTE); - String msg = null; - try { - if (oDates != null) { - client.setQueryParams("yyyymm="+oDates); - } - Future fh = client.read("/authz/hist/role/"+oName,gui.getDF(History.class)); - if (fh.get(AAF_GUI.TIMEOUT)) { - tt.done(); - tt = trans.start("Load History Data", Env.SUB); - List histItems = fh.value.getItem(); - - java.util.Collections.sort(histItems, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return o2.getTimestamp().compare(o1.getTimestamp()); - } - }); - - for (Item i : histItems) { - String user = i.getUser(); - AbsCell userCell = new TextCell(user); + ); + + } + + private static void addDateRow(HTMLGen hgen, String s) { + hgen + .incr("tr") + .incr("td") + .incr("label", "for=month", "required").text(s+"*").end() + .end() + .incr("td") + .incr("select", "name=month"+s.substring(0, s.indexOf(' ')), "id=month"+s.substring(0, s.indexOf(' ')), "required") + .incr("option", "value=").text("Month").end(); + for (Month m : Month.values()) { + if (Calendar.getInstance().get(Calendar.MONTH) == m.ordinal()) { + hgen.incr("option", "selected", "value="+(m.ordinal()+1)).text(m.name()).end(); + } else { + hgen.incr("option", "value="+(m.ordinal()+1)).text(m.name()).end(); + } + } + hgen.end() + .end() + .incr("td") + .tagOnly("input","type=number","id=year"+s.substring(0, s.indexOf(' ')),"required", + "value="+Calendar.getInstance().get(Calendar.YEAR), "min=1900", + "max="+Calendar.getInstance().get(Calendar.YEAR), + "placeholder=Year").end() + .end(); + } + + + /** + * Implement the Table Content for History + * + * @author Jeremiah + * + */ + private static class Model extends TableData { + private static final String[] headers = new String[] {"Date","User","Memo"}; + private Slot role; + private Slot dates; + + public Model(AuthzEnv env) { + role = env.slot(NAME+".role"); + dates = env.slot(NAME+".dates"); + } + + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + final String oName = trans.get(role,null); + final String oDates = trans.get(dates,null); + + Cells rv = Cells.EMPTY; + if(oName!=null) { + + try { + rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Cells code(Rcli client) throws CadiException, ConnectException, APIException { + ArrayList rv = new ArrayList<>(); + TimeTaken tt = trans.start("AAF Get History for Namespace ["+oName+"]",Env.REMOTE); + String msg = null; + try { + if (oDates != null) { + client.setQueryParams("yyyymm="+oDates); + } + Future fh = client.read("/authz/hist/role/"+oName,gui.getDF(History.class)); + if (fh.get(AAF_GUI.TIMEOUT)) { + tt.done(); + tt = trans.start("Load History Data", Env.SUB); + List histItems = fh.value.getItem(); + + java.util.Collections.sort(histItems, new Comparator() { + @Override + public int compare(Item o1, Item o2) { + return o2.getTimestamp().compare(o1.getTimestamp()); + } + }); + + for (Item i : histItems) { + String user = i.getUser(); + AbsCell userCell = new TextCell(user); - String memo = i.getMemo().replace("", "</script>"); - rv.add(new AbsCell[] { - new TextCell(i.getTimestamp().toGregorianCalendar().getTime().toString()), - userCell, - new TextCell(memo) - }); - } - } else { - if (fh.code()==403) { - rv.add(new AbsCell[] {new TextCell("You may not view History of Permission [" + oName + "]", "colspan = 3", "class=center")}); - } else { - rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***", "colspan = 3", "class=center")}); - } - } - } finally { - tt.done(); - } - return new Cells(rv,msg); - } - }); - } catch (Exception e) { - trans.error().log(e); - } - } - return rv; - } - } + String memo = i.getMemo().replace("", "</script>"); + rv.add(new AbsCell[] { + new TextCell(i.getTimestamp().toGregorianCalendar().getTime().toString()), + userCell, + new TextCell(memo) + }); + } + } else { + if (fh.code()==403) { + rv.add(new AbsCell[] {new TextCell("You may not view History of Permission [" + oName + "]", "colspan = 3", "class=center")}); + } else { + rv.add(new AbsCell[] {new TextCell("*** Data Unavailable ***", "colspan = 3", "class=center")}); + } + } + } finally { + tt.done(); + } + return new Cells(rv,msg); + } + }); + } catch (Exception e) { + trans.error().log(e); + } + } + return rv; + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java index 80ff9409..ffa8e3c2 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java @@ -56,85 +56,85 @@ import aaf.v2_0.UserRoles; * */ public class RolesShow extends Page { - public static final String HREF = "/gui/myroles"; - private static final String DATE_TIME_FORMAT = "yyyy-MM-dd"; - - public RolesShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, "MyRoles",HREF, NO_FIELDS, - new BreadCrumbs(breadcrumbs), - new Table("Roles",gui.env.newTransNoAvg(),new Model(), "class=std")); - } + public static final String HREF = "/gui/myroles"; + private static final String DATE_TIME_FORMAT = "yyyy-MM-dd"; + + public RolesShow(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, "MyRoles",HREF, NO_FIELDS, + new BreadCrumbs(breadcrumbs), + new Table("Roles",gui.env.newTransNoAvg(),new Model(), "class=std")); + } - /** - * Implement the Table Content for Permissions by User - * - * @author Jonathan - * - */ - private static class Model extends TableData { - private static final String[] headers = new String[] {"Role","Expires","Remediation","Actions"}; - private static final String ROLE = "&role="; - private static final String USER = "?user="; - private static final String CLASS_EXPIRED = "class=expired"; + /** + * Implement the Table Content for Permissions by User + * + * @author Jonathan + * + */ + private static class Model extends TableData { + private static final String[] headers = new String[] {"Role","Expires","Remediation","Actions"}; + private static final String ROLE = "&role="; + private static final String USER = "?user="; + private static final String CLASS_EXPIRED = "class=expired"; - @Override - public String[] headers() { - return headers; - } - - @Override - public Cells get(final AuthzTrans trans, final AAF_GUI gui) { - Cells rv = Cells.EMPTY; + @Override + public String[] headers() { + return headers; + } + + @Override + public Cells get(final AuthzTrans trans, final AAF_GUI gui) { + Cells rv = Cells.EMPTY; - try { - rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Cells code(Rcli client) throws CadiException, ConnectException, APIException { - ArrayList rv = new ArrayList<>(); - TimeTaken tt = trans.start("AAF Roles by User",Env.REMOTE); - try { - Future fur = client.read("/authz/userRoles/user/"+trans.user(),gui.getDF(UserRoles.class)); - if (fur.get(5000) && fur.value != null) for (UserRole u : fur.value.getUserRole()) { - if(u.getExpires().compare(Chrono.timeStamp()) < 0) { - AbsCell[] sa = new AbsCell[] { - new TextCell(u.getRole() + "*", CLASS_EXPIRED), - new TextCell(new SimpleDateFormat(DATE_TIME_FORMAT).format(u.getExpires().toGregorianCalendar().getTime()),CLASS_EXPIRED), - new RefCell("Extend", - UserRoleExtend.HREF+USER+trans.user()+ROLE+u.getRole(), - false, - new String[]{CLASS_EXPIRED}), - new RefCell("Remove", - UserRoleRemove.HREF+USER +trans.user()+ROLE+u.getRole(), - false, - new String[]{CLASS_EXPIRED}) - - }; - rv.add(sa); - } else { - AbsCell[] sa = new AbsCell[] { - new RefCell(u.getRole(), - RoleDetail.HREF+"?role="+u.getRole(), - false), - new TextCell(new SimpleDateFormat(DATE_TIME_FORMAT).format(u.getExpires().toGregorianCalendar().getTime())), - AbsCell.Null, - new RefCell("Remove", - UserRoleRemove.HREF+USER+trans.user()+ROLE+u.getRole(), - false) - }; - rv.add(sa); - } - } - - } finally { - tt.done(); - } - return new Cells(rv,null); - } - }); - } catch (Exception e) { - trans.error().log(e); - } - return rv; - } - } + try { + rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Cells code(Rcli client) throws CadiException, ConnectException, APIException { + ArrayList rv = new ArrayList<>(); + TimeTaken tt = trans.start("AAF Roles by User",Env.REMOTE); + try { + Future fur = client.read("/authz/userRoles/user/"+trans.user(),gui.getDF(UserRoles.class)); + if (fur.get(5000) && fur.value != null) for (UserRole u : fur.value.getUserRole()) { + if(u.getExpires().compare(Chrono.timeStamp()) < 0) { + AbsCell[] sa = new AbsCell[] { + new TextCell(u.getRole() + "*", CLASS_EXPIRED), + new TextCell(new SimpleDateFormat(DATE_TIME_FORMAT).format(u.getExpires().toGregorianCalendar().getTime()),CLASS_EXPIRED), + new RefCell("Extend", + UserRoleExtend.HREF+USER+trans.user()+ROLE+u.getRole(), + false, + new String[]{CLASS_EXPIRED}), + new RefCell("Remove", + UserRoleRemove.HREF+USER +trans.user()+ROLE+u.getRole(), + false, + new String[]{CLASS_EXPIRED}) + + }; + rv.add(sa); + } else { + AbsCell[] sa = new AbsCell[] { + new RefCell(u.getRole(), + RoleDetail.HREF+"?role="+u.getRole(), + false), + new TextCell(new SimpleDateFormat(DATE_TIME_FORMAT).format(u.getExpires().toGregorianCalendar().getTime())), + AbsCell.Null, + new RefCell("Remove", + UserRoleRemove.HREF+USER+trans.user()+ROLE+u.getRole(), + false) + }; + rv.add(sa); + } + } + + } finally { + tt.done(); + } + return new Cells(rv,null); + } + }); + } catch (Exception e) { + trans.error().log(e); + } + return rv; + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java index 8a78fd74..04e0e845 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java @@ -42,58 +42,58 @@ import org.onap.aaf.misc.xgen.DynamicCode; import org.onap.aaf.misc.xgen.html.HTMLGen; public class UserRoleExtend extends Page { - public static final String HREF = "/gui/urExtend"; - static final String NAME = "Extend User Role"; - static final String fields[] = {"user","role"}; + public static final String HREF = "/gui/urExtend"; + static final String NAME = "Extend User Role"; + static final String fields[] = {"user","role"}; - public UserRoleExtend(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME, HREF, fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true, "content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final Slot sUser = gui.env.slot(NAME+".user"); - final Slot sRole = gui.env.slot(NAME+".role"); - - - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final String user = trans.get(sUser, ""); - final String role = trans.get(sRole, ""); + public UserRoleExtend(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME, HREF, fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true, "content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final Slot sUser = gui.env.slot(NAME+".user"); + final Slot sRole = gui.env.slot(NAME+".role"); + + + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final String user = trans.get(sUser, ""); + final String role = trans.get(sRole, ""); - TimeTaken tt = trans.start("Request to extend user role",Env.REMOTE); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client)throws CadiException, ConnectException, APIException { - Future fv = client.update("/authz/userRole/extend/"+user+"/"+role+"?request=true"); - if(fv.get(5000)) { - // not sure if we'll ever hit this - hgen.p("Extended User ["+ user+"] in Role [" +role+"]"); - } else { - if (fv.code() == 202 ) { - hgen.p("User ["+ user+"] in Role [" +role+"] Extension sent for Approval"); - } else { - gui.writeError(trans, fv, hgen,0); - } - } - return null; - } - }); - } catch (Exception e) { - trans.error().log(e); - e.printStackTrace(); - } finally { - tt.done(); - } - - - } - }); - } - - }); - } + TimeTaken tt = trans.start("Request to extend user role",Env.REMOTE); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client)throws CadiException, ConnectException, APIException { + Future fv = client.update("/authz/userRole/extend/"+user+"/"+role+"?request=true"); + if(fv.get(5000)) { + // not sure if we'll ever hit this + hgen.p("Extended User ["+ user+"] in Role [" +role+"]"); + } else { + if (fv.code() == 202 ) { + hgen.p("User ["+ user+"] in Role [" +role+"] Extension sent for Approval"); + } else { + gui.writeError(trans, fv, hgen,0); + } + } + return null; + } + }); + } catch (Exception e) { + trans.error().log(e); + e.printStackTrace(); + } finally { + tt.done(); + } + + + } + }); + } + + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java index 84f3640d..73aa3e9f 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java @@ -42,56 +42,56 @@ import org.onap.aaf.misc.xgen.DynamicCode; import org.onap.aaf.misc.xgen.html.HTMLGen; public class UserRoleRemove extends Page { - public static final String HREF = "/gui/urRemove"; - static final String NAME = "Remove User Role"; - static final String fields[] = {"user","role"}; + public static final String HREF = "/gui/urRemove"; + static final String NAME = "Remove User Role"; + static final String fields[] = {"user","role"}; - public UserRoleRemove(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env,NAME, HREF, fields, - new BreadCrumbs(breadcrumbs), - new NamedCode(true, "content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final Slot sUser = gui.env.slot(NAME+".user"); - final Slot sRole = gui.env.slot(NAME+".role"); - - - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { - final String user = trans.get(sUser, ""); - final String role = trans.get(sRole, ""); + public UserRoleRemove(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env,NAME, HREF, fields, + new BreadCrumbs(breadcrumbs), + new NamedCode(true, "content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final Slot sUser = gui.env.slot(NAME+".user"); + final Slot sRole = gui.env.slot(NAME+".role"); + + + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache cache, final HTMLGen hgen) throws APIException, IOException { + final String user = trans.get(sUser, ""); + final String role = trans.get(sRole, ""); - TimeTaken tt = trans.start("Request a user role delete",Env.REMOTE); - try { - gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fv = client.delete( - "/authz/userRole/"+user+"/"+role+"?request=true",Void.class); - - if(fv.get(5000)) { - // not sure if we'll ever hit this - hgen.p("User ["+ user+"] Removed from Role [" +role+"]"); - } else { - if (fv.code() == 202 ) { - hgen.p("User ["+ user+"] Removal from Role [" +role+"] sent for Approval"); - } else { - gui.writeError(trans, fv, hgen, 0); - } - } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(); - } finally { - tt.done(); - } - } - }); - } - - }); - } + TimeTaken tt = trans.start("Request a user role delete",Env.REMOTE); + try { + gui.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fv = client.delete( + "/authz/userRole/"+user+"/"+role+"?request=true",Void.class); + + if(fv.get(5000)) { + // not sure if we'll ever hit this + hgen.p("User ["+ user+"] Removed from Role [" +role+"]"); + } else { + if (fv.code() == 202 ) { + hgen.p("User ["+ user+"] Removal from Role [" +role+"] sent for Approval"); + } else { + gui.writeError(trans, fv, hgen, 0); + } + } + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(); + } finally { + tt.done(); + } + } + }); + } + + }); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java index f9c57d0f..6ad95e51 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java @@ -35,84 +35,84 @@ import org.onap.aaf.misc.xgen.Mark; import org.onap.aaf.misc.xgen.html.HTMLGen; public class WebCommand extends Page { - public static final String HREF = "/gui/cui"; - - public WebCommand(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { - super(gui.env, "Web Command Client",HREF, NO_FIELDS, - new BreadCrumbs(breadcrumbs), - new NamedCode(true, "content") { - @Override - public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - hgen.leaf("p","id=help_msg") - .text("Questions about this page? ") - .leaf("a", "href="+gui.env.getProperty(AAF_URL_CUIGUI,""), "target=_blank") - .text("Click here") - .end() - .text(". Type 'help' below for a list of AAF commands") - .end() - - .divID("console_and_options"); - hgen.divID("console_area"); - hgen.end(); //console_area - - hgen.divID("options_link", "class=closed"); - hgen.img("src=../../"+gui.theme + "/options_down.png", "onclick=handleDivHiding('options',this);", - "id=options_img", "alt=Options", "title=Options") - .end(); //options_link - - hgen.divID("options"); - cache.dynamic(hgen, new DynamicCode() { - @Override - public void code(AAF_GUI state, AuthzTrans trans, Cache cache, HTMLGen xgen) - throws APIException, IOException { - switch(browser(trans,trans.env().slot(getBrowserType()))) { - case ie: - case ieOld: - // IE doesn't support file save - break; - default: - xgen.img("src=../../"+gui.theme+"/AAFdownload.png", "onclick=saveToFile();", - "alt=Save log to file", "title=Save log to file"); - } -// xgen.img("src=../../"+gui.theme+"/AAFemail.png", "onclick=emailLog();", -// "alt=Email log to me", "title=Email log to me"); - xgen.img("src=../../"+gui.theme+"/AAF_font_size.png", "onclick=handleDivHiding('text_slider',this);", - "id=fontsize_img", "alt=Change text size", "title=Change text size"); - xgen.img("src=../../"+gui.theme+"/AAF_details.png", "onclick=selectOption(this,0);", - "id=details_img", "alt=Turn on/off details mode", "title=Turn on/off details mode"); - xgen.img("src=../../"+gui.theme+"/AAF_maximize.png", "onclick=maximizeConsole(this);", - "id=maximize_img", "alt=Maximize Console Window", "title=Maximize Console Window"); - } - }); - hgen.divID("text_slider"); - hgen.tagOnly("input", "type=button", "class=change_font", "onclick=buttonChangeFontSize('dec')", "value=-") - .tagOnly("input", "id=text_size_slider", "type=range", "min=75", "max=200", "value=100", - "oninput=changeFontSize(this.value)", "onchange=changeFontSize(this.value)", "title=Change Text Size") - .tagOnly("input", "type=button", "class=change_font", "onclick=buttonChangeFontSize('inc')", "value=+") - .end(); //text_slider + public static final String HREF = "/gui/cui"; + + public WebCommand(final AAF_GUI gui, final Page ... breadcrumbs) throws APIException, IOException { + super(gui.env, "Web Command Client",HREF, NO_FIELDS, + new BreadCrumbs(breadcrumbs), + new NamedCode(true, "content") { + @Override + public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { + hgen.leaf("p","id=help_msg") + .text("Questions about this page? ") + .leaf("a", "href="+gui.env.getProperty(AAF_URL_CUIGUI,""), "target=_blank") + .text("Click here") + .end() + .text(". Type 'help' below for a list of AAF commands") + .end() + + .divID("console_and_options"); + hgen.divID("console_area"); + hgen.end(); //console_area + + hgen.divID("options_link", "class=closed"); + hgen.img("src=../../"+gui.theme + "/options_down.png", "onclick=handleDivHiding('options',this);", + "id=options_img", "alt=Options", "title=Options") + .end(); //options_link + + hgen.divID("options"); + cache.dynamic(hgen, new DynamicCode() { + @Override + public void code(AAF_GUI state, AuthzTrans trans, Cache cache, HTMLGen xgen) + throws APIException, IOException { + switch(browser(trans,trans.env().slot(getBrowserType()))) { + case ie: + case ieOld: + // IE doesn't support file save + break; + default: + xgen.img("src=../../"+gui.theme+"/AAFdownload.png", "onclick=saveToFile();", + "alt=Save log to file", "title=Save log to file"); + } +// xgen.img("src=../../"+gui.theme+"/AAFemail.png", "onclick=emailLog();", +// "alt=Email log to me", "title=Email log to me"); + xgen.img("src=../../"+gui.theme+"/AAF_font_size.png", "onclick=handleDivHiding('text_slider',this);", + "id=fontsize_img", "alt=Change text size", "title=Change text size"); + xgen.img("src=../../"+gui.theme+"/AAF_details.png", "onclick=selectOption(this,0);", + "id=details_img", "alt=Turn on/off details mode", "title=Turn on/off details mode"); + xgen.img("src=../../"+gui.theme+"/AAF_maximize.png", "onclick=maximizeConsole(this);", + "id=maximize_img", "alt=Maximize Console Window", "title=Maximize Console Window"); + } + }); + hgen.divID("text_slider"); + hgen.tagOnly("input", "type=button", "class=change_font", "onclick=buttonChangeFontSize('dec')", "value=-") + .tagOnly("input", "id=text_size_slider", "type=range", "min=75", "max=200", "value=100", + "oninput=changeFontSize(this.value)", "onchange=changeFontSize(this.value)", "title=Change Text Size") + .tagOnly("input", "type=button", "class=change_font", "onclick=buttonChangeFontSize('inc')", "value=+") + .end(); //text_slider - hgen.end(); //options - hgen.end(); //console_and_options - - hgen.divID("input_area"); - hgen.tagOnly("input", "type=text", "id=command_field", - "autocomplete=off", "autocorrect=off", "autocapitalize=off", "spellcheck=false", - "onkeypress=keyPressed()", "placeholder=Type your AAFCLI commands here", "autofocus") - .tagOnly("input", "id=submit", "type=button", "value=Submit", - "onclick=http('put','../../gui/cui',getCommand(),callCUI);") - .end(); + hgen.end(); //options + hgen.end(); //console_and_options + + hgen.divID("input_area"); + hgen.tagOnly("input", "type=text", "id=command_field", + "autocomplete=off", "autocorrect=off", "autocapitalize=off", "spellcheck=false", + "onkeypress=keyPressed()", "placeholder=Type your AAFCLI commands here", "autofocus") + .tagOnly("input", "id=submit", "type=button", "value=Submit", + "onclick=http('put','../../gui/cui',getCommand(),callCUI);") + .end(); - Mark callCUI = new Mark(); - hgen.js(callCUI); - hgen.text("function callCUI(resp) {") - .text("moveCommandToDiv();") - .text("printResponse(resp);") - .text("}"); - hgen.end(callCUI); - - } - }); + Mark callCUI = new Mark(); + hgen.js(callCUI); + hgen.text("function callCUI(resp) {") + .text("moveCommandToDiv();") + .text("printResponse(resp);") + .text("}"); + hgen.end(callCUI); + + } + }); - } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/AbsCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/AbsCell.java index 6d95d7d8..e461cf54 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/AbsCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/AbsCell.java @@ -24,25 +24,25 @@ package org.onap.aaf.auth.gui.table; import org.onap.aaf.misc.xgen.html.HTMLGen; public abstract class AbsCell { - public static final AbsCell[] HLINE = new AbsCell[0]; - private static final String[] NONE = new String[0]; - protected static final String[] CENTER = new String[]{"class=center"}; - protected static final String[] LEFT = new String[]{"class=left"}; - protected static final String[] RIGHT = new String[]{"class=right"}; + public static final AbsCell[] HLINE = new AbsCell[0]; + private static final String[] NONE = new String[0]; + protected static final String[] CENTER = new String[]{"class=center"}; + protected static final String[] LEFT = new String[]{"class=left"}; + protected static final String[] RIGHT = new String[]{"class=right"}; - /** - * Write Cell Data with HTMLGen generator - * @param hgen - */ - public abstract void write(HTMLGen hgen); - - public final static AbsCell Null = new AbsCell() { - @Override - public void write(final HTMLGen hgen) { - } - }; - - public String[] attrs() { - return NONE; - } + /** + * Write Cell Data with HTMLGen generator + * @param hgen + */ + public abstract void write(HTMLGen hgen); + + public final static AbsCell Null = new AbsCell() { + @Override + public void write(final HTMLGen hgen) { + } + }; + + public String[] attrs() { + return NONE; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/ButtonCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/ButtonCell.java index 986c90af..2443eb98 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/ButtonCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/ButtonCell.java @@ -24,22 +24,22 @@ package org.onap.aaf.auth.gui.table; import org.onap.aaf.misc.xgen.html.HTMLGen; public class ButtonCell extends AbsCell { - private String[] attrs; - - public ButtonCell(String value, String ... attributes) { - attrs = new String[2+attributes.length]; - attrs[0]="type=button"; - attrs[1]="value="+value; - System.arraycopy(attributes, 0, attrs, 2, attributes.length); - } - @Override - public void write(HTMLGen hgen) { - hgen.incr("input",true,attrs).end(); + private String[] attrs; + + public ButtonCell(String value, String ... attributes) { + attrs = new String[2+attributes.length]; + attrs[0]="type=button"; + attrs[1]="value="+value; + System.arraycopy(attributes, 0, attrs, 2, attributes.length); + } + @Override + public void write(HTMLGen hgen) { + hgen.incr("input",true,attrs).end(); - } - - @Override - public String[] attrs() { - return AbsCell.CENTER; - } + } + + @Override + public String[] attrs() { + return AbsCell.CENTER; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/CheckBoxCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/CheckBoxCell.java index 4c723d4a..91abfa42 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/CheckBoxCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/CheckBoxCell.java @@ -24,43 +24,43 @@ package org.onap.aaf.auth.gui.table; import org.onap.aaf.misc.xgen.html.HTMLGen; public class CheckBoxCell extends AbsCell { - public enum ALIGN{ left, right, center }; - private String[] attrs; - private ALIGN align; - - public CheckBoxCell(String name, ALIGN align, String value, String ... attributes) { - this.align = align; - attrs = new String[3 + attributes.length]; - attrs[0]="type=checkbox"; - attrs[1]="name="+name; - attrs[2]="value="+value; - System.arraycopy(attributes, 0, attrs, 3, attributes.length); - } + public enum ALIGN{ left, right, center }; + private String[] attrs; + private ALIGN align; + + public CheckBoxCell(String name, ALIGN align, String value, String ... attributes) { + this.align = align; + attrs = new String[3 + attributes.length]; + attrs[0]="type=checkbox"; + attrs[1]="name="+name; + attrs[2]="value="+value; + System.arraycopy(attributes, 0, attrs, 3, attributes.length); + } - public CheckBoxCell(String name, String value, String ... attributes) { - this.align = ALIGN.center; - attrs = new String[3 + attributes.length]; - attrs[0]="type=checkbox"; - attrs[1]="name="+name; - attrs[2]="value="+value; - System.arraycopy(attributes, 0, attrs, 3, attributes.length); - } + public CheckBoxCell(String name, String value, String ... attributes) { + this.align = ALIGN.center; + attrs = new String[3 + attributes.length]; + attrs[0]="type=checkbox"; + attrs[1]="name="+name; + attrs[2]="value="+value; + System.arraycopy(attributes, 0, attrs, 3, attributes.length); + } - @Override - public void write(HTMLGen hgen) { - hgen.tagOnly("input",attrs); - } + @Override + public void write(HTMLGen hgen) { + hgen.tagOnly("input",attrs); + } - @Override - public String[] attrs() { - switch(align) { - case left: - return AbsCell.LEFT; - case right: - return AbsCell.RIGHT; - case center: - default: - return AbsCell.CENTER; - } - } + @Override + public String[] attrs() { + switch(align) { + case left: + return AbsCell.LEFT; + case right: + return AbsCell.RIGHT; + case center: + default: + return AbsCell.CENTER; + } + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RadioCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RadioCell.java index 9f092105..9f21fac8 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RadioCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RadioCell.java @@ -24,25 +24,25 @@ package org.onap.aaf.auth.gui.table; import org.onap.aaf.misc.xgen.html.HTMLGen; public class RadioCell extends AbsCell { - private String[] attrs; - - public RadioCell(String name, String radioClass, String value, String ... attributes) { - attrs = new String[4 + attributes.length]; - attrs[0]="type=radio"; - attrs[1]="name="+name; - attrs[2]="class="+radioClass; - attrs[3]="value="+value; - System.arraycopy(attributes, 0, attrs, 4, attributes.length); + private String[] attrs; + + public RadioCell(String name, String radioClass, String value, String ... attributes) { + attrs = new String[4 + attributes.length]; + attrs[0]="type=radio"; + attrs[1]="name="+name; + attrs[2]="class="+radioClass; + attrs[3]="value="+value; + System.arraycopy(attributes, 0, attrs, 4, attributes.length); - } - - @Override - public void write(HTMLGen hgen) { - hgen.tagOnly("input",attrs); - } + } + + @Override + public void write(HTMLGen hgen) { + hgen.tagOnly("input",attrs); + } - @Override - public String[] attrs() { - return AbsCell.CENTER; - } + @Override + public String[] attrs() { + return AbsCell.CENTER; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java index 7dc14c81..5fc82140 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java @@ -31,24 +31,24 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; * */ public class RefCell extends AbsCell { - public final String name; - public final String[] str; - - public RefCell(String name, String href, boolean newWindow, String... attributes) { - this.name = name; - if(newWindow) { - str = new String[attributes.length+2]; - str[attributes.length]="target=_blank"; - } else { - str = new String[attributes.length+1]; - } - str[0]="href="+href; - System.arraycopy(attributes, 0, str, 1, attributes.length); + public final String name; + public final String[] str; + + public RefCell(String name, String href, boolean newWindow, String... attributes) { + this.name = name; + if(newWindow) { + str = new String[attributes.length+2]; + str[attributes.length]="target=_blank"; + } else { + str = new String[attributes.length+1]; + } + str[0]="href="+href; + System.arraycopy(attributes, 0, str, 1, attributes.length); - } - - @Override - public void write(HTMLGen hgen) { - hgen.leaf(A,str).text(name); - } + } + + @Override + public void write(HTMLGen hgen) { + hgen.leaf(A,str).text(name); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TableData.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TableData.java index 731d425e..d202ffa0 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TableData.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TableData.java @@ -29,28 +29,28 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; import org.onap.aaf.misc.xgen.html.State; public abstract class TableData, TRANS extends Trans> implements Table.Data{ - public static final String[] headers = new String[0]; + public static final String[] headers = new String[0]; - /* (non-Javadoc) - * @see org.onap.aaf.auth.gui.Table.Data#prefix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) - */ - @Override - public void prefix(final S state, final TRANS trans, final Cache cache, final HTMLGen hgen) { - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.gui.Table.Data#prefix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) + */ + @Override + public void prefix(final S state, final TRANS trans, final Cache cache, final HTMLGen hgen) { + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.gui.Table.Data#postfix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) - */ - @Override - public void postfix(final S state, final TRANS trans, final Cache cache, final HTMLGen hgen) { - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.gui.Table.Data#postfix(org.onap.aaf.misc.xgen.html.State, com.att.inno.env.Trans, org.onap.aaf.misc.xgen.Cache, org.onap.aaf.misc.xgen.html.HTMLGen) + */ + @Override + public void postfix(final S state, final TRANS trans, final Cache cache, final HTMLGen hgen) { + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.gui.Table.Data#headers() - */ - @Override - public String[] headers() { - return headers; - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.gui.Table.Data#headers() + */ + @Override + public String[] headers() { + return headers; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextAndRefCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextAndRefCell.java index 036c8b7f..aefb3a46 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextAndRefCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextAndRefCell.java @@ -27,17 +27,17 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; public class TextAndRefCell extends RefCell { - private String text; - - public TextAndRefCell(String text, String name, String href, boolean newWindow, String[] attributes) { - super(name, href, newWindow, attributes); - this.text = text; - } + private String text; + + public TextAndRefCell(String text, String name, String href, boolean newWindow, String[] attributes) { + super(name, href, newWindow, attributes); + this.text = text; + } - @Override - public void write(HTMLGen hgen) { - hgen.text(text); - hgen.leaf(A,str).text(name); - } + @Override + public void write(HTMLGen hgen) { + hgen.text(text); + hgen.leaf(A,str).text(name); + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextCell.java index e20367a7..5d2a7262 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextCell.java @@ -29,21 +29,21 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; * */ public class TextCell extends AbsCell { - public final String name; - private String[] attrs; - - public TextCell(String name, String... attributes) { - attrs = attributes; - this.name = name; - } - - @Override - public void write(HTMLGen hgen) { - hgen.text(name); - } - - @Override - public String[] attrs() { - return attrs; - } + public final String name; + private String[] attrs; + + public TextCell(String name, String... attributes) { + attrs = attributes; + this.name = name; + } + + @Override + public void write(HTMLGen hgen) { + hgen.text(name); + } + + @Override + public String[] attrs() { + return attrs; + } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextInputCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextInputCell.java index 4a4f757c..c55759ea 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextInputCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextInputCell.java @@ -29,26 +29,26 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; * */ public class TextInputCell extends AbsCell { - private static final String[] NULL_ATTRS=new String[0]; - private String[] attrs; - - public TextInputCell(String name, String textClass, String value, String ... attributes) { - attrs = new String[5 + attributes.length]; - attrs[0]="type=text"; - attrs[1]="name="+name; - attrs[2]="class="+textClass; - attrs[3]="value="+value; - attrs[4]="style=font-size:100%;"; - System.arraycopy(attributes, 0, attrs, 5, attributes.length); - } - - @Override - public void write(HTMLGen hgen) { - hgen.tagOnly("input",attrs); - } - - @Override - public String[] attrs() { - return NULL_ATTRS; - } + private static final String[] NULL_ATTRS=new String[0]; + private String[] attrs; + + public TextInputCell(String name, String textClass, String value, String ... attributes) { + attrs = new String[5 + attributes.length]; + attrs[0]="type=text"; + attrs[1]="name="+name; + attrs[2]="class="+textClass; + attrs[3]="value="+value; + attrs[4]="style=font-size:100%;"; + System.arraycopy(attributes, 0, attrs, 5, attributes.length); + } + + @Override + public void write(HTMLGen hgen) { + hgen.tagOnly("input",attrs); + } + + @Override + public String[] attrs() { + return NULL_ATTRS; + } } diff --git a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java index 9617f191..34371a1f 100644 --- a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java +++ b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java @@ -48,85 +48,85 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.Env; public class AAF_Hello extends AbsService { - public enum API{TOKEN_REQ, TOKEN,INTROSPECT, ERROR,VOID}; - public Map cacheUser; - public AAFAuthn aafAuthn; - public AAFLurPerm aafLurPerm; - - /** - * Construct AuthzAPI with all the Context Supporting Routes that Authz needs - * - * @param env - * @param si - * @param dm - * @param decryptor - * @throws APIException - */ - public AAF_Hello(final AuthzEnv env) throws Exception { - super(env.access(), env); - - aafLurPerm = aafCon().newLur(); - // Note: If you need both Authn and Authz construct the following: - aafAuthn = aafCon().newAuthn(aafLurPerm); + public enum API{TOKEN_REQ, TOKEN,INTROSPECT, ERROR,VOID}; + public Map cacheUser; + public AAFAuthn aafAuthn; + public AAFLurPerm aafLurPerm; + + /** + * Construct AuthzAPI with all the Context Supporting Routes that Authz needs + * + * @param env + * @param si + * @param dm + * @param decryptor + * @throws APIException + */ + public AAF_Hello(final AuthzEnv env) throws Exception { + super(env.access(), env); + + aafLurPerm = aafCon().newLur(); + // Note: If you need both Authn and Authz construct the following: + aafAuthn = aafCon().newAuthn(aafLurPerm); - String aaf_env = env.getProperty(Config.AAF_ENV); - if(aaf_env==null) { - throw new APIException("aaf_env needs to be set"); - } - - // Initialize Facade for all uses - AuthzTrans trans = env.newTrans(); - StringBuilder sb = new StringBuilder(); - trans.auditTrail(2, sb); - trans.init().log(sb); - - API_Hello.init(this); + String aaf_env = env.getProperty(Config.AAF_ENV); + if(aaf_env==null) { + throw new APIException("aaf_env needs to be set"); + } + + // Initialize Facade for all uses + AuthzTrans trans = env.newTrans(); + StringBuilder sb = new StringBuilder(); + trans.auditTrail(2, sb); + trans.init().log(sb); + + API_Hello.init(this); } - - /** - * Setup XML and JSON implementations for each supported Version type - * - * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties - * to do Versions and Content switches - * - */ - public void route(HttpMethods meth, String path, API api, HttpCode code) throws Exception { - String version = "1.0"; - // Get Correct API Class from Mapper - route(env,meth,path,code,"text/plain;version="+version,"*/*"); - } - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - try { - return new Filter[] { - new AuthzTransFilter(env,aafCon(), - new AAFTrustChecker((Env)env), - additionalTafLurs) - }; - } catch (NumberFormatException e) { - throw new CadiException("Invalid Property information", e); - } - } + + /** + * Setup XML and JSON implementations for each supported Version type + * + * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties + * to do Versions and Content switches + * + */ + public void route(HttpMethods meth, String path, API api, HttpCode code) throws Exception { + String version = "1.0"; + // Get Correct API Class from Mapper + route(env,meth,path,code,"text/plain;version="+version,"*/*"); + } + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + try { + return new Filter[] { + new AuthzTransFilter(env,aafCon(), + new AAFTrustChecker((Env)env), + additionalTafLurs) + }; + } catch (NumberFormatException e) { + throw new CadiException("Invalid Property information", e); + } + } - @SuppressWarnings("unchecked") - @Override - public Registrant[] registrants(final int port) throws CadiException, LocatorException { - return new Registrant[] { - new RemoteRegistrant(aafCon(),app_name,app_version,port) - }; - } + @SuppressWarnings("unchecked") + @Override + public Registrant[] registrants(final int port) throws CadiException, LocatorException { + return new Registrant[] { + new RemoteRegistrant(aafCon(),app_name,app_version,port) + }; + } - public static void main(final String[] args) { - try { - Log4JLogIt logIt = new Log4JLogIt(args, "hello"); - PropAccess propAccess = new PropAccess(logIt,args); + public static void main(final String[] args) { + try { + Log4JLogIt logIt = new Log4JLogIt(args, "hello"); + PropAccess propAccess = new PropAccess(logIt,args); - AAF_Hello service = new AAF_Hello(new AuthzEnv(propAccess)); - JettyServiceStarter jss = new JettyServiceStarter(service); - jss.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + AAF_Hello service = new AAF_Hello(new AuthzEnv(propAccess)); + JettyServiceStarter jss = new JettyServiceStarter(service); + jss.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java index 97727abd..234dfe14 100644 --- a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java +++ b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java @@ -43,146 +43,146 @@ import org.onap.aaf.misc.env.TimeTaken; public class API_Hello { - private static final String APPLICATION_JSON = "application/json"; - protected static final byte[] NOT_JSON = "Data does not look like JSON".getBytes(); + private static final String APPLICATION_JSON = "application/json"; + protected static final byte[] NOT_JSON = "Data does not look like JSON".getBytes(); - // Hide Public Constructor - private API_Hello() {} - - /** - * Normal Init level APIs - * - * @param oauthHello - * @param facade - * @throws Exception - */ - public static void init(final AAF_Hello oauthHello) throws Exception { - //////// - // Simple "GET" API - /////// - - oauthHello.route(HttpMethods.GET,"/hello/:perm*",API.TOKEN,new HttpCode(oauthHello,"Hello OAuth"){ - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - resp.setStatus(200 /* OK */); - ServletOutputStream os = resp.getOutputStream(); - os.print("Hello AAF "); - String perm = pathParam(req, "perm"); - if(perm!=null && perm.length()>0) { - os.print('('); - os.print(req.getUserPrincipal().getName()); - TimeTaken tt = trans.start("Authorize perm", Env.REMOTE); - try { - if(req.isUserInRole(perm)) { - os.print(" has "); - } else { - os.print(" does not have "); - } - } finally { - tt.done(); - } - os.print("Permission: "); - os.print(perm); - os.print(')'); - } - os.println(); - - trans.info().printf("Said 'Hello' to %s, Authentication type: %s",trans.getUserPrincipal().getName(),trans.getUserPrincipal().getClass().getSimpleName()); - } - }); + // Hide Public Constructor + private API_Hello() {} + + /** + * Normal Init level APIs + * + * @param oauthHello + * @param facade + * @throws Exception + */ + public static void init(final AAF_Hello oauthHello) throws Exception { + //////// + // Simple "GET" API + /////// + + oauthHello.route(HttpMethods.GET,"/hello/:perm*",API.TOKEN,new HttpCode(oauthHello,"Hello OAuth"){ + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + resp.setStatus(200 /* OK */); + ServletOutputStream os = resp.getOutputStream(); + os.print("Hello AAF "); + String perm = pathParam(req, "perm"); + if(perm!=null && perm.length()>0) { + os.print('('); + os.print(req.getUserPrincipal().getName()); + TimeTaken tt = trans.start("Authorize perm", Env.REMOTE); + try { + if(req.isUserInRole(perm)) { + os.print(" has "); + } else { + os.print(" does not have "); + } + } finally { + tt.done(); + } + os.print("Permission: "); + os.print(perm); + os.print(')'); + } + os.println(); + + trans.info().printf("Said 'Hello' to %s, Authentication type: %s",trans.getUserPrincipal().getName(),trans.getUserPrincipal().getClass().getSimpleName()); + } + }); //////////////// // REST APIs //////////////// - //////////////// - // CREATE/POST - //////////////// - oauthHello.route(oauthHello.env,HttpMethods.POST,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Create") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); - StringBuilder sb = new StringBuilder(); - while(br.ready()) { - sb.append(br.readLine()); - } - String content = sb.toString(); - trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content); - if(content.startsWith("{") && content.endsWith("}")) { - resp.setStatus(201 /* OK */); - } else { - resp.getOutputStream().write(NOT_JSON); - resp.setStatus(406); - } - } - },APPLICATION_JSON); + //////////////// + // CREATE/POST + //////////////// + oauthHello.route(oauthHello.env,HttpMethods.POST,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Create") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); + StringBuilder sb = new StringBuilder(); + while(br.ready()) { + sb.append(br.readLine()); + } + String content = sb.toString(); + trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content); + if(content.startsWith("{") && content.endsWith("}")) { + resp.setStatus(201 /* OK */); + } else { + resp.getOutputStream().write(NOT_JSON); + resp.setStatus(406); + } + } + },APPLICATION_JSON); - //////////////// - // READ/GET - //////////////// - oauthHello.route(oauthHello.env,HttpMethods.GET,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Read") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - resp.setStatus(200 /* OK */); - StringBuilder sb = new StringBuilder("{\"resp\": \"Hello REST AAF\",\"principal\": \""); - sb.append(req.getUserPrincipal().getName()); - sb.append('"'); - String perm = pathParam(req, "perm"); - trans.info().printf("Read request from %s: %s\n", pathParam(req, ":id"),perm); - if(perm!=null && perm.length()>0) { - TimeTaken tt = trans.start("Authorize perm", Env.REMOTE); - try { - sb.append(",\"validation\": { \"permission\" : \""); - sb.append(perm); - sb.append("\",\"has\" : \""); - sb.append(req.isUserInRole(perm)); - sb.append("\"}"); - } finally { - tt.done(); - } - } - sb.append("}"); - ServletOutputStream os = resp.getOutputStream(); - os.println(sb.toString()); - trans.info().printf("Said 'RESTful Hello' to %s, Authentication type: %s",trans.getUserPrincipal().getName(),trans.getUserPrincipal().getClass().getSimpleName()); - } - },APPLICATION_JSON); - - //////////////// - // UPDATE/PUT - //////////////// - oauthHello.route(oauthHello.env,HttpMethods.PUT,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Update") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); - StringBuilder sb = new StringBuilder(); - while(br.ready()) { - sb.append(br.readLine()); - } - String content = sb.toString(); - trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content); - if(content.startsWith("{") && content.endsWith("}")) { - resp.setStatus(200 /* OK */); - resp.getOutputStream().print(content); - } else { - resp.getOutputStream().write(NOT_JSON); - resp.setStatus(406); - } - } - },APPLICATION_JSON); + //////////////// + // READ/GET + //////////////// + oauthHello.route(oauthHello.env,HttpMethods.GET,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Read") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + resp.setStatus(200 /* OK */); + StringBuilder sb = new StringBuilder("{\"resp\": \"Hello REST AAF\",\"principal\": \""); + sb.append(req.getUserPrincipal().getName()); + sb.append('"'); + String perm = pathParam(req, "perm"); + trans.info().printf("Read request from %s: %s\n", pathParam(req, ":id"),perm); + if(perm!=null && perm.length()>0) { + TimeTaken tt = trans.start("Authorize perm", Env.REMOTE); + try { + sb.append(",\"validation\": { \"permission\" : \""); + sb.append(perm); + sb.append("\",\"has\" : \""); + sb.append(req.isUserInRole(perm)); + sb.append("\"}"); + } finally { + tt.done(); + } + } + sb.append("}"); + ServletOutputStream os = resp.getOutputStream(); + os.println(sb.toString()); + trans.info().printf("Said 'RESTful Hello' to %s, Authentication type: %s",trans.getUserPrincipal().getName(),trans.getUserPrincipal().getClass().getSimpleName()); + } + },APPLICATION_JSON); + + //////////////// + // UPDATE/PUT + //////////////// + oauthHello.route(oauthHello.env,HttpMethods.PUT,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Update") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); + StringBuilder sb = new StringBuilder(); + while(br.ready()) { + sb.append(br.readLine()); + } + String content = sb.toString(); + trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content); + if(content.startsWith("{") && content.endsWith("}")) { + resp.setStatus(200 /* OK */); + resp.getOutputStream().print(content); + } else { + resp.getOutputStream().write(NOT_JSON); + resp.setStatus(406); + } + } + },APPLICATION_JSON); - //////////////// - // DELETE - //////////////// - oauthHello.route(oauthHello.env,HttpMethods.DELETE,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Delete") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - trans.info().printf("Delete requested on %s\n", pathParam(req, ":id")); - resp.setStatus(200 /* OK */); - } - },APPLICATION_JSON); + //////////////// + // DELETE + //////////////// + oauthHello.route(oauthHello.env,HttpMethods.DELETE,"/resthello/:id",new HttpCode(oauthHello,"REST Hello Delete") { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + trans.info().printf("Delete requested on %s\n", pathParam(req, ":id")); + resp.setStatus(200 /* OK */); + } + },APPLICATION_JSON); - } + } } diff --git a/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java b/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java index 84625281..f41826d9 100644 --- a/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java +++ b/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java @@ -40,42 +40,42 @@ import org.onap.aaf.misc.env.APIException; public class HelloTester { - public static void main(String[] args) { - // Do Once and ONLY once - PropAccess access = new PropAccess(args); - try { - Define.set(access); - String uriPrefix = access.getProperty("locatorURI","https://aaftest.test.att.com"); - - SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); - AAFLocator loc = new AAFLocator(si,new URI(uriPrefix+"/locate/"+Define.ROOT_NS()+".hello:1.0")); - AAFConHttp aafcon = new AAFConHttp(access,loc,si); - - // - String pathinfo = "/hello"; - final int iterations = Integer.parseInt(access.getProperty("iterations","5")); - System.out.println("Calling " + loc + " with Path " + pathinfo + ' ' + iterations + " time" + (iterations==1?"":"s")); - for(int i=0;i () { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fs = client.read("/hello","text/plain"); - if(fs.get(5000)) { - System.out.print(fs.body()); - } else { - System.err.println("Ooops, missed one: " + fs.code() + ": " + fs.body()); - } - return null; - - } - }); - Thread.sleep(500L); - } - } catch (CadiException | LocatorException | URISyntaxException | APIException | InterruptedException e) { - e.printStackTrace(); - } - - - } - + public static void main(String[] args) { + // Do Once and ONLY once + PropAccess access = new PropAccess(args); + try { + Define.set(access); + String uriPrefix = access.getProperty("locatorURI",null); + if(uriPrefix==null) { + System.out.println("You must add \"locatorURI=\" to the command line or VM_Args"); + } else { + SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); + AAFLocator loc = new AAFLocator(si,new URI(uriPrefix+"/locate/"+Define.ROOT_NS()+".hello:1.0")); + AAFConHttp aafcon = new AAFConHttp(access,loc,si); + + // + String pathinfo = "/hello"; + final int iterations = Integer.parseInt(access.getProperty("iterations","5")); + System.out.println("Calling " + loc + " with Path " + pathinfo + ' ' + iterations + " time" + (iterations==1?"":"s")); + for(int i=0;i () { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fs = client.read("/hello","text/plain"); + if(fs.get(5000)) { + System.out.print(fs.body()); + } else { + System.err.println("Ooops, missed one: " + fs.code() + ": " + fs.body()); + } + return null; + + } + }); + Thread.sleep(500L); + } + } + } catch (CadiException | LocatorException | URISyntaxException | APIException | InterruptedException e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java index 9f25eab7..545b6b47 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java @@ -67,183 +67,183 @@ import org.onap.aaf.misc.rosetta.env.RosettaEnv; import com.datastax.driver.core.Cluster; public class AAF_Locate extends AbsService { - private static final String DOT_LOCATOR = ".locator"; - - private static final String USER_PERMS = "userPerms"; - private LocateFacade_1_1 facade; // this is the default Facade - private LocateFacade_1_1 facade_1_1_XML; - public Map cacheUser; - public final AAFAuthn aafAuthn; - public final AAFLurPerm aafLurPerm; - private Locator gui_locator; - public final long expireIn; - private final Cluster cluster; - public final LocateDAO locateDAO; - public final ConfigDAO configDAO; - private Locator dal; - private final String aaf_service_name; - private final String aaf_gui_name; - - - /** - * Construct AuthzAPI with all the Context Supporting Routes that Authz needs - * - * @param env - * @param si - * @param dm - * @param decryptor - * @throws APIException - */ - public AAF_Locate(final AuthzEnv env) throws Exception { - super(env.access(), env); - aaf_service_name = app_name.replace(DOT_LOCATOR, ".service"); - aaf_gui_name = app_name.replace(DOT_LOCATOR, ".gui"); - - expireIn = Long.parseLong(env.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF)); - - // Initialize Facade for all uses - AuthzTrans trans = env.newTransNoAvg(); - - cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); - locateDAO = new LocateDAO(trans,cluster,CassAccess.KEYSPACE); - configDAO = new ConfigDAO(trans,locateDAO); // same stuff - - // Have AAFLocator object Create DirectLocators for Location needs - AbsAAFLocator.setCreator(new DirectLocatorCreator(env, locateDAO)); - - aafLurPerm = aafCon().newLur(); - // Note: If you need both Authn and Authz construct the following: - aafAuthn = aafCon().newAuthn(aafLurPerm); - - - facade = LocateFacadeFactory.v1_1(env,this,trans,Data.TYPE.JSON); // Default Facade - facade_1_1_XML = LocateFacadeFactory.v1_1(env,this,trans,Data.TYPE.XML); - - synchronized(env) { - if(cacheUser == null) { - cacheUser = Cache.obtain(USER_PERMS); - Cache.startCleansing(env, USER_PERMS); - } - } - - - //////////////////////////////////////////////////////////////////////////// - // Time Critical - // These will always be evaluated first - //////////////////////////////////////////////////////////////////////// - API_AAFAccess.init(this,facade); - API_Find.init(this, facade); - API_Proxy.init(this, facade); - - //////////////////////////////////////////////////////////////////////// - // Management APIs - //////////////////////////////////////////////////////////////////////// - // There are several APIs around each concept, and it gets a bit too - // long in this class to create. The initialization of these Management - // APIs have therefore been pushed to StandAlone Classes with static - // init functions - API_Api.init(this, facade); - - //////////////////////////////////////////////////////////////////////// - // Default Function - //////////////////////////////////////////////////////////////////////// - API_AAFAccess.initDefault(this,facade); - - } - - - /** - * Setup XML and JSON implementations for each supported Version type - * - * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties - * to do Versions and Content switches - * - */ - public void route(HttpMethods meth, String path, API api, LocateCode code) throws Exception { - String version = "1.0"; - // Get Correct API Class from Mapper - Class respCls = facade.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); - // setup Application API HTML ContentTypes for JSON and Route - String application = applicationJSON(respCls, version); - route(env,meth,path,code,application,"application/json;version="+version,"*/*","*"); - - // setup Application API HTML ContentTypes for XML and Route - application = applicationXML(respCls, version); - route(env,meth,path,code.clone(facade_1_1_XML,false),application,"text/xml;version="+version); - - // Add other Supported APIs here as created - } - - public void routeAll(HttpMethods meth, String path, API api, LocateCode code) throws Exception { - route(env,meth,path,code,""); // this will always match - } - - - /* (non-Javadoc) - * @see org.onap.aaf.auth.server.AbsServer#_newAAFConHttp() - */ - @Override - protected AAFConHttp _newAAFConHttp() throws CadiException { - try { - if(dal==null) { - dal = AbsAAFLocator.create(aaf_service_name,Config.AAF_DEFAULT_VERSION); - } - // utilize pre-constructed DirectAAFLocator - return new AAFConHttp(env.access(),dal); - } catch (LocatorException e) { - throw new CadiException(e); - } - } - - public Locator getGUILocator() throws LocatorException { - if(gui_locator==null) { - gui_locator = AbsAAFLocator.create(aaf_gui_name,Config.AAF_DEFAULT_VERSION); - } - return gui_locator; - } - - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - try { - return new Filter[] { - new AuthzTransFilter(env, aafCon(), - new AAFTrustChecker((Env)env) - ,additionalTafLurs - )}; - } catch (NumberFormatException e) { - throw new CadiException("Invalid Property information", e); - } - } - - @SuppressWarnings("unchecked") - @Override - public Registrant[] registrants(final int port) throws CadiException { - return new Registrant[] { - new DirectRegistrar(access,locateDAO,app_name,app_version,port) - }; - } - - @Override - public void destroy() { - Cache.stopTimer(); - if(cluster!=null) { - cluster.close(); - } - super.destroy(); - } - - public static void main(final String[] args) { - try { - Log4JLogIt logIt = new Log4JLogIt(args, "locate"); - PropAccess propAccess = new PropAccess(logIt,args); - - AAF_Locate service = new AAF_Locate(new AuthzEnv(propAccess)); - JettyServiceStarter jss = new JettyServiceStarter(service); - jss.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + private static final String DOT_LOCATOR = ".locator"; + + private static final String USER_PERMS = "userPerms"; + private LocateFacade_1_1 facade; // this is the default Facade + private LocateFacade_1_1 facade_1_1_XML; + public Map cacheUser; + public final AAFAuthn aafAuthn; + public final AAFLurPerm aafLurPerm; + private Locator gui_locator; + public final long expireIn; + private final Cluster cluster; + public final LocateDAO locateDAO; + public final ConfigDAO configDAO; + private Locator dal; + private final String aaf_service_name; + private final String aaf_gui_name; + + + /** + * Construct AuthzAPI with all the Context Supporting Routes that Authz needs + * + * @param env + * @param si + * @param dm + * @param decryptor + * @throws APIException + */ + public AAF_Locate(final AuthzEnv env) throws Exception { + super(env.access(), env); + aaf_service_name = app_name.replace(DOT_LOCATOR, ".service"); + aaf_gui_name = app_name.replace(DOT_LOCATOR, ".gui"); + + expireIn = Long.parseLong(env.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF)); + + // Initialize Facade for all uses + AuthzTrans trans = env.newTransNoAvg(); + + cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); + locateDAO = new LocateDAO(trans,cluster,CassAccess.KEYSPACE); + configDAO = new ConfigDAO(trans,locateDAO); // same stuff + + // Have AAFLocator object Create DirectLocators for Location needs + AbsAAFLocator.setCreator(new DirectLocatorCreator(env, locateDAO)); + + aafLurPerm = aafCon().newLur(); + // Note: If you need both Authn and Authz construct the following: + aafAuthn = aafCon().newAuthn(aafLurPerm); + + + facade = LocateFacadeFactory.v1_1(env,this,trans,Data.TYPE.JSON); // Default Facade + facade_1_1_XML = LocateFacadeFactory.v1_1(env,this,trans,Data.TYPE.XML); + + synchronized(env) { + if(cacheUser == null) { + cacheUser = Cache.obtain(USER_PERMS); + Cache.startCleansing(env, USER_PERMS); + } + } + + + //////////////////////////////////////////////////////////////////////////// + // Time Critical + // These will always be evaluated first + //////////////////////////////////////////////////////////////////////// + API_AAFAccess.init(this,facade); + API_Find.init(this, facade); + API_Proxy.init(this, facade); + + //////////////////////////////////////////////////////////////////////// + // Management APIs + //////////////////////////////////////////////////////////////////////// + // There are several APIs around each concept, and it gets a bit too + // long in this class to create. The initialization of these Management + // APIs have therefore been pushed to StandAlone Classes with static + // init functions + API_Api.init(this, facade); + + //////////////////////////////////////////////////////////////////////// + // Default Function + //////////////////////////////////////////////////////////////////////// + API_AAFAccess.initDefault(this,facade); + + } + + + /** + * Setup XML and JSON implementations for each supported Version type + * + * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties + * to do Versions and Content switches + * + */ + public void route(HttpMethods meth, String path, API api, LocateCode code) throws Exception { + String version = "1.0"; + // Get Correct API Class from Mapper + Class respCls = facade.mapper().getClass(api); + if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + // setup Application API HTML ContentTypes for JSON and Route + String application = applicationJSON(respCls, version); + route(env,meth,path,code,application,"application/json;version="+version,"*/*","*"); + + // setup Application API HTML ContentTypes for XML and Route + application = applicationXML(respCls, version); + route(env,meth,path,code.clone(facade_1_1_XML,false),application,"text/xml;version="+version); + + // Add other Supported APIs here as created + } + + public void routeAll(HttpMethods meth, String path, API api, LocateCode code) throws Exception { + route(env,meth,path,code,""); // this will always match + } + + + /* (non-Javadoc) + * @see org.onap.aaf.auth.server.AbsServer#_newAAFConHttp() + */ + @Override + protected AAFConHttp _newAAFConHttp() throws CadiException { + try { + if(dal==null) { + dal = AbsAAFLocator.create(aaf_service_name,Config.AAF_DEFAULT_VERSION); + } + // utilize pre-constructed DirectAAFLocator + return new AAFConHttp(env.access(),dal); + } catch (LocatorException e) { + throw new CadiException(e); + } + } + + public Locator getGUILocator() throws LocatorException { + if(gui_locator==null) { + gui_locator = AbsAAFLocator.create(aaf_gui_name,Config.AAF_DEFAULT_VERSION); + } + return gui_locator; + } + + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + try { + return new Filter[] { + new AuthzTransFilter(env, aafCon(), + new AAFTrustChecker((Env)env) + ,additionalTafLurs + )}; + } catch (NumberFormatException e) { + throw new CadiException("Invalid Property information", e); + } + } + + @SuppressWarnings("unchecked") + @Override + public Registrant[] registrants(final int port) throws CadiException { + return new Registrant[] { + new DirectRegistrar(access,locateDAO,app_name,app_version,port) + }; + } + + @Override + public void destroy() { + Cache.stopTimer(); + if(cluster!=null) { + cluster.close(); + } + super.destroy(); + } + + public static void main(final String[] args) { + try { + Log4JLogIt logIt = new Log4JLogIt(args, "locate"); + PropAccess propAccess = new PropAccess(logIt,args); + + AAF_Locate service = new AAF_Locate(new AuthzEnv(propAccess)); + JettyServiceStarter jss = new JettyServiceStarter(service); + jss.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java index ac348f3f..c5239a5a 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java @@ -35,43 +35,43 @@ import org.onap.aaf.cadi.principal.BasicPrincipal; import org.onap.aaf.cadi.principal.X509Principal; public class BasicAuthCode extends LocateCode { - private AAFAuthn authn; + private AAFAuthn authn; - public BasicAuthCode(AAFAuthn authn, LocateFacade facade) { - super(facade, "AAF Basic Auth",true); - this.authn = authn; - } + public BasicAuthCode(AAFAuthn authn, LocateFacade facade) { + super(facade, "AAF Basic Auth",true); + this.authn = authn; + } - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Principal p = trans.getUserPrincipal(); - if(p == null) { - trans.error().log("Transaction not Authenticated... no Principal"); - } else if (p instanceof BasicPrincipal) { - // the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok - // otherwise, it wouldn't have gotten here. - resp.setStatus(HttpStatus.OK_200); - return; - } else if (p instanceof X509Principal) { - // Since X509Principal has priority, BasicAuth Info might be there, but not validated. - String ba; - if((ba=req.getHeader("Authorization"))!=null && ba.startsWith("Basic ")) { - ba = Symm.base64noSplit.decode(ba.substring(6)); - int colon = ba.indexOf(':'); - if(colon>=0) { - String err; - if((err=authn.validate(ba.substring(0, colon), ba.substring(colon+1),trans))==null) { - resp.setStatus(HttpStatus.OK_200); - } else { - trans.audit().log(ba.substring(0,colon),": ",err); - resp.setStatus(HttpStatus.UNAUTHORIZED_401); - } - return; - } - } - } - trans.checkpoint("Basic Auth Check Failed: This wasn't a Basic Auth Trans"); - // For Auth Security questions, we don't give any info to client on why failed - resp.setStatus(HttpStatus.FORBIDDEN_403); - } + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Principal p = trans.getUserPrincipal(); + if(p == null) { + trans.error().log("Transaction not Authenticated... no Principal"); + } else if (p instanceof BasicPrincipal) { + // the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok + // otherwise, it wouldn't have gotten here. + resp.setStatus(HttpStatus.OK_200); + return; + } else if (p instanceof X509Principal) { + // Since X509Principal has priority, BasicAuth Info might be there, but not validated. + String ba; + if((ba=req.getHeader("Authorization"))!=null && ba.startsWith("Basic ")) { + ba = Symm.base64noSplit.decode(ba.substring(6)); + int colon = ba.indexOf(':'); + if(colon>=0) { + String err; + if((err=authn.validate(ba.substring(0, colon), ba.substring(colon+1),trans))==null) { + resp.setStatus(HttpStatus.OK_200); + } else { + trans.audit().log(ba.substring(0,colon),": ",err); + resp.setStatus(HttpStatus.UNAUTHORIZED_401); + } + return; + } + } + } + trans.checkpoint("Basic Auth Check Failed: This wasn't a Basic Auth Trans"); + // For Auth Security questions, we don't give any info to client on why failed + resp.setStatus(HttpStatus.FORBIDDEN_403); + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/LocateCode.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/LocateCode.java index b1aa23cc..214c9d80 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/LocateCode.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/LocateCode.java @@ -26,19 +26,19 @@ import org.onap.aaf.auth.locate.facade.LocateFacade; import org.onap.aaf.auth.rserv.HttpCode; public abstract class LocateCode extends HttpCode implements Cloneable { - public boolean useJSON; + public boolean useJSON; - public LocateCode(LocateFacade facade, String description, boolean useJSON, String ... roles) { - super(facade, description, roles); - this.useJSON = useJSON; - } - - public D clone(LocateFacade facade, boolean useJSON) throws Exception { - @SuppressWarnings("unchecked") - D d = (D)clone(); - d.useJSON = useJSON; - d.context = facade; - return d; - } - + public LocateCode(LocateFacade facade, String description, boolean useJSON, String ... roles) { + super(facade, description, roles); + this.useJSON = useJSON; + } + + public D clone(LocateFacade facade, boolean useJSON) throws Exception { + @SuppressWarnings("unchecked") + D d = (D)clone(); + d.useJSON = useJSON; + d.context = facade; + return d; + } + } \ No newline at end of file diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java index 802c1b55..85cee82f 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java @@ -55,237 +55,237 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.TimeTaken; public class API_AAFAccess { -// private static String service, version, envContext; +// private static String service, version, envContext; - private static final String GET_PERMS_BY_USER = "Get Perms by User"; - private static final String USER_HAS_PERM ="User Has Perm"; -// private static final String USER_IN_ROLE ="User Has Role"; - - /** - * Normal Init level APIs - * - * @param gwAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { - - - gwAPI.route(HttpMethods.GET,"/authz/perms/user/:user",API.VOID,new LocateCode(facade,GET_PERMS_BY_USER, true) { - @Override - public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { - TimeTaken tt = trans.start(GET_PERMS_BY_USER, Env.SUB); - try { - final String accept = req.getHeader("ACCEPT"); - final String user = pathParam(req,":user"); - if(!user.contains("@")) { - context.error(trans,resp,Result.ERR_BadData,"User [%s] must be fully qualified with domain",user); - return; - } - final String key = trans.user() + user + (accept!=null&&accept.contains("xml")?"-xml":"-json"); - TimeTaken tt2 = trans.start("Cache Lookup",Env.SUB); - Dated d; - try { - d = gwAPI.cacheUser.get(key); - } finally { - tt2.done(); - } - - if(d==null || d.data.isEmpty()) { - tt2 = trans.start("AAF Service Call",Env.REMOTE); - try { - gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fp = client.read("/authz/perms/user/"+user,accept); - if(fp.get(5000)) { - gwAPI.cacheUser.put(key, new Dated(new User(fp.code(),fp.body()),gwAPI.expireIn)); - resp.setStatus(HttpStatus.OK_200); - ServletOutputStream sos; - try { - sos = resp.getOutputStream(); - sos.print(fp.value); - } catch (IOException e) { - throw new CadiException(e); - } - } else { - gwAPI.cacheUser.put(key, new Dated(new User(fp.code(),fp.body()),gwAPI.expireIn)); - context.error(trans,resp,fp.code(),fp.body()); - } - return null; - } - }); - } finally { - tt2.done(); - } - } else { - User u = (User)d.data.get(0); - resp.setStatus(u.code); - ServletOutputStream sos = resp.getOutputStream(); - sos.print(u.resp); - } - } finally { - tt.done(); - } - } - }); + private static final String GET_PERMS_BY_USER = "Get Perms by User"; + private static final String USER_HAS_PERM ="User Has Perm"; +// private static final String USER_IN_ROLE ="User Has Role"; + + /** + * Normal Init level APIs + * + * @param gwAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { + + + gwAPI.route(HttpMethods.GET,"/authz/perms/user/:user",API.VOID,new LocateCode(facade,GET_PERMS_BY_USER, true) { + @Override + public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { + TimeTaken tt = trans.start(GET_PERMS_BY_USER, Env.SUB); + try { + final String accept = req.getHeader("ACCEPT"); + final String user = pathParam(req,":user"); + if(!user.contains("@")) { + context.error(trans,resp,Result.ERR_BadData,"User [%s] must be fully qualified with domain",user); + return; + } + final String key = trans.user() + user + (accept!=null&&accept.contains("xml")?"-xml":"-json"); + TimeTaken tt2 = trans.start("Cache Lookup",Env.SUB); + Dated d; + try { + d = gwAPI.cacheUser.get(key); + } finally { + tt2.done(); + } + + if(d==null || d.data.isEmpty()) { + tt2 = trans.start("AAF Service Call",Env.REMOTE); + try { + gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fp = client.read("/authz/perms/user/"+user,accept); + if(fp.get(5000)) { + gwAPI.cacheUser.put(key, new Dated(new User(fp.code(),fp.body()),gwAPI.expireIn)); + resp.setStatus(HttpStatus.OK_200); + ServletOutputStream sos; + try { + sos = resp.getOutputStream(); + sos.print(fp.value); + } catch (IOException e) { + throw new CadiException(e); + } + } else { + gwAPI.cacheUser.put(key, new Dated(new User(fp.code(),fp.body()),gwAPI.expireIn)); + context.error(trans,resp,fp.code(),fp.body()); + } + return null; + } + }); + } finally { + tt2.done(); + } + } else { + User u = (User)d.data.get(0); + resp.setStatus(u.code); + ServletOutputStream sos = resp.getOutputStream(); + sos.print(u.resp); + } + } finally { + tt.done(); + } + } + }); - gwAPI.route(gwAPI.env,HttpMethods.GET,"/authn/basicAuth",new BasicAuthCode(gwAPI.aafAuthn,facade) - ,"text/plain","*/*","*"); + gwAPI.route(gwAPI.env,HttpMethods.GET,"/authn/basicAuth",new BasicAuthCode(gwAPI.aafAuthn,facade) + ,"text/plain","*/*","*"); - /** - * Query User Has Perm is DEPRECATED - * - * Need to move towards NS declaration... is this even being used? - * @deprecated - */ - gwAPI.route(HttpMethods.GET,"/ask/:user/has/:type/:instance/:action",API.VOID,new LocateCode(facade,USER_HAS_PERM, true) { - @Override - public void handle(final AuthzTrans trans, final HttpServletRequest req, HttpServletResponse resp) throws Exception { - try { - String type = pathParam(req,":type"); - int idx = type.lastIndexOf('.'); - String ns = type.substring(0,idx); - type = type.substring(idx+1); - resp.getOutputStream().print( - gwAPI.aafLurPerm.fish(new Principal() { - public String getName() { - return pathParam(req,":user"); - }; - }, new AAFPermission( - ns, - type, - pathParam(req,":instance"), - pathParam(req,":action")))); - resp.setStatus(HttpStatus.OK_200); - } catch(Exception e) { - context.error(trans, resp, Result.ERR_General, e.getMessage()); - } - } - }); + /** + * Query User Has Perm is DEPRECATED + * + * Need to move towards NS declaration... is this even being used? + * @deprecated + */ + gwAPI.route(HttpMethods.GET,"/ask/:user/has/:type/:instance/:action",API.VOID,new LocateCode(facade,USER_HAS_PERM, true) { + @Override + public void handle(final AuthzTrans trans, final HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + String type = pathParam(req,":type"); + int idx = type.lastIndexOf('.'); + String ns = type.substring(0,idx); + type = type.substring(idx+1); + resp.getOutputStream().print( + gwAPI.aafLurPerm.fish(new Principal() { + public String getName() { + return pathParam(req,":user"); + }; + }, new AAFPermission( + ns, + type, + pathParam(req,":instance"), + pathParam(req,":action")))); + resp.setStatus(HttpStatus.OK_200); + } catch(Exception e) { + context.error(trans, resp, Result.ERR_General, e.getMessage()); + } + } + }); - gwAPI.route(HttpMethods.GET,"/gui/:path*",API.VOID,new LocateCode(facade,"Short Access PROD GUI for AAF", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - try { - redirect(trans, req, resp, context, - gwAPI.getGUILocator(), - "gui/"+pathParam(req,":path")); - } catch (LocatorException e) { - context.error(trans, resp, Result.ERR_BadData, e.getMessage()); - } catch (Exception e) { - context.error(trans, resp, Result.ERR_General, e.getMessage()); - } - } - }); + gwAPI.route(HttpMethods.GET,"/gui/:path*",API.VOID,new LocateCode(facade,"Short Access PROD GUI for AAF", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + redirect(trans, req, resp, context, + gwAPI.getGUILocator(), + "gui/"+pathParam(req,":path")); + } catch (LocatorException e) { + context.error(trans, resp, Result.ERR_BadData, e.getMessage()); + } catch (Exception e) { + context.error(trans, resp, Result.ERR_General, e.getMessage()); + } + } + }); - gwAPI.route(HttpMethods.GET,"/aaf/:version/:path*",API.VOID,new LocateCode(facade,"Access PROD GUI for AAF", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - try { - redirect(trans, req, resp, context, - gwAPI.getGUILocator(), - pathParam(req,":path")); - } catch (LocatorException e) { - context.error(trans, resp, Result.ERR_BadData, e.getMessage()); - } catch (Exception e) { - context.error(trans, resp, Result.ERR_General, e.getMessage()); - } - } - }); - } - - public static void initDefault(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { + gwAPI.route(HttpMethods.GET,"/aaf/:version/:path*",API.VOID,new LocateCode(facade,"Access PROD GUI for AAF", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + redirect(trans, req, resp, context, + gwAPI.getGUILocator(), + pathParam(req,":path")); + } catch (LocatorException e) { + context.error(trans, resp, Result.ERR_BadData, e.getMessage()); + } catch (Exception e) { + context.error(trans, resp, Result.ERR_General, e.getMessage()); + } + } + }); + } + + public static void initDefault(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { - /** - * "login" url - */ - gwAPI.route(HttpMethods.GET,"/login",API.VOID,new LocateCode(facade,"Access Login GUI for AAF", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - try { - redirect(trans, req, resp, context, - gwAPI.getGUILocator(), - "login"); - } catch (LocatorException e) { - context.error(trans, resp, Result.ERR_BadData, e.getMessage()); - } catch (Exception e) { - context.error(trans, resp, Result.ERR_General, e.getMessage()); - } - } - }); + /** + * "login" url + */ + gwAPI.route(HttpMethods.GET,"/login",API.VOID,new LocateCode(facade,"Access Login GUI for AAF", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + redirect(trans, req, resp, context, + gwAPI.getGUILocator(), + "login"); + } catch (LocatorException e) { + context.error(trans, resp, Result.ERR_BadData, e.getMessage()); + } catch (Exception e) { + context.error(trans, resp, Result.ERR_General, e.getMessage()); + } + } + }); - - /** - * Default URL - */ - gwAPI.route(HttpMethods.GET,"/",API.VOID,new LocateCode(facade,"Access GUI for AAF", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - try { - redirect(trans, req, resp, context, - gwAPI.getGUILocator(), - "gui/home"); - } catch (Exception e) { - context.error(trans, resp, Result.ERR_General, e.getMessage()); - } - } - }); - - /** - * Configuration - */ - gwAPI.route(HttpMethods.GET,"/configure/:id/:type",API.CONFIG,new LocateCode(facade,"Deliver Configuration Properties to AAF", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - try { - Result r = facade.getConfig(trans, req, resp, pathParam(req, ":id"),pathParam(req,":type")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } + + /** + * Default URL + */ + gwAPI.route(HttpMethods.GET,"/",API.VOID,new LocateCode(facade,"Access GUI for AAF", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + redirect(trans, req, resp, context, + gwAPI.getGUILocator(), + "gui/home"); + } catch (Exception e) { + context.error(trans, resp, Result.ERR_General, e.getMessage()); + } + } + }); + + /** + * Configuration + */ + gwAPI.route(HttpMethods.GET,"/configure/:id/:type",API.CONFIG,new LocateCode(facade,"Deliver Configuration Properties to AAF", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + Result r = facade.getConfig(trans, req, resp, pathParam(req, ":id"),pathParam(req,":type")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } - } catch (Exception e) { - context.error(trans, resp, Result.ERR_General, e.getMessage()); - } - } - }); - } + } catch (Exception e) { + context.error(trans, resp, Result.ERR_General, e.getMessage()); + } + } + }); + } - private static void redirect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, LocateFacade context, Locator loc, String path) throws IOException { - try { - if(loc.hasItems()) { - Item item = loc.best(); - URI uri = loc.get(item); - StringBuilder redirectURL = new StringBuilder(uri.toString()); - redirectURL.append('/'); - redirectURL.append(path); - String str = req.getQueryString(); - if(str!=null) { - redirectURL.append('?'); - redirectURL.append(str); - } - trans.info().log("Redirect to",redirectURL); - resp.sendRedirect(redirectURL.toString()); - } else { - context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Locations found for redirection")); - } - } catch (LocatorException e) { - context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Endpoints found for %s",req.getPathInfo())); - } - } + private static void redirect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, LocateFacade context, Locator loc, String path) throws IOException { + try { + if(loc.hasItems()) { + Item item = loc.best(); + URI uri = loc.get(item); + StringBuilder redirectURL = new StringBuilder(uri.toString()); + redirectURL.append('/'); + redirectURL.append(path); + String str = req.getQueryString(); + if(str!=null) { + redirectURL.append('?'); + redirectURL.append(str); + } + trans.info().log("Redirect to",redirectURL); + resp.sendRedirect(redirectURL.toString()); + } else { + context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Locations found for redirection")); + } + } catch (LocatorException e) { + context.error(trans, resp, Result.err(Result.ERR_NotFound,"No Endpoints found for %s",req.getPathInfo())); + } + } - private static class User { - public final int code; - public final String resp; - - public User(int code, String resp) { - this.code = code; - this.resp = resp; - } - } + private static class User { + public final int code; + public final String resp; + + public User(int code, String resp) { + this.code = code; + this.resp = resp; + } + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Api.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Api.java index 8e3fab56..1e60e796 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Api.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Api.java @@ -42,56 +42,56 @@ import org.onap.aaf.cadi.Symm; * */ public class API_Api { - /** - * Normal Init level APIs - * - * @param gwAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { - //////// - // Overall APIs - /////// - gwAPI.route(HttpMethods.GET,"/api",API.VOID,new LocateCode(facade,"Document API", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getAPI(trans,resp,gwAPI); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } + /** + * Normal Init level APIs + * + * @param gwAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { + //////// + // Overall APIs + /////// + gwAPI.route(HttpMethods.GET,"/api",API.VOID,new LocateCode(facade,"Document API", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getAPI(trans,resp,gwAPI); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } - } - }); + } + }); - //////// - // Overall Examples - /////// - gwAPI.route(HttpMethods.GET,"/api/example/*",API.VOID,new LocateCode(facade,"Document API", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String pathInfo = req.getPathInfo(); - int question = pathInfo.lastIndexOf('?'); - - pathInfo = pathInfo.substring(13, question<0?pathInfo.length():question);// IMPORTANT, this is size of "/api/example/" - String nameOrContextType=Symm.base64noSplit.decode(pathInfo); -// String param = req.getParameter("optional"); - Result r = context.getAPIExample(trans,resp,nameOrContextType, - question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1)) - ); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + //////// + // Overall Examples + /////// + gwAPI.route(HttpMethods.GET,"/api/example/*",API.VOID,new LocateCode(facade,"Document API", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String pathInfo = req.getPathInfo(); + int question = pathInfo.lastIndexOf('?'); + + pathInfo = pathInfo.substring(13, question<0?pathInfo.length():question);// IMPORTANT, this is size of "/api/example/" + String nameOrContextType=Symm.base64noSplit.decode(pathInfo); +// String param = req.getParameter("optional"); + Result r = context.getAPIExample(trans,resp,nameOrContextType, + question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1)) + ); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - } + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java index 27bd8c3a..7ff1fceb 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java @@ -44,89 +44,89 @@ import org.onap.aaf.misc.env.util.Split; * */ public class API_Find { - /** - * Normal Init level APIs - * - * @param gwAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { - //////// - // Overall APIs - /////// - - final LocateCode locationInfo = new LocateCode(facade,"Location Information", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String service = pathParam(req, ":service"); - String version = pathParam(req, ":version"); - String other = pathParam(req, ":other"); - if(service.indexOf(':')>=0) { - String split[] = Split.split(':', service); - switch(split.length) { - case 3: - other=split[2]; - case 2: - version = split[1]; - service = split[0]; - } - } - service=Define.varReplace(service); - Result r = context.getEndpoints(trans,resp, - req.getPathInfo(), // use as Key - service,version,other - ); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }; + /** + * Normal Init level APIs + * + * @param gwAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { + //////// + // Overall APIs + /////// + + final LocateCode locationInfo = new LocateCode(facade,"Location Information", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String service = pathParam(req, ":service"); + String version = pathParam(req, ":version"); + String other = pathParam(req, ":other"); + if(service.indexOf(':')>=0) { + String split[] = Split.split(':', service); + switch(split.length) { + case 3: + other=split[2]; + case 2: + version = split[1]; + service = split[0]; + } + } + service=Define.varReplace(service); + Result r = context.getEndpoints(trans,resp, + req.getPathInfo(), // use as Key + service,version,other + ); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }; - gwAPI.route(HttpMethods.GET,"/locate/:service/:version",API.ENDPOINTS,locationInfo); - gwAPI.route(HttpMethods.GET,"/locate/:service/:version/:other",API.ENDPOINTS,locationInfo); - gwAPI.route(HttpMethods.GET,"/locate/:service",API.ENDPOINTS,locationInfo); - - - gwAPI.route(HttpMethods.GET,"/download/agent", API.VOID, new LocateCode(facade,"Redirect to latest Agent",false) { - @Override - public void handle(AuthzTrans arg0, HttpServletRequest arg1, HttpServletResponse arg2) throws Exception { - } - }); + gwAPI.route(HttpMethods.GET,"/locate/:service/:version",API.ENDPOINTS,locationInfo); + gwAPI.route(HttpMethods.GET,"/locate/:service/:version/:other",API.ENDPOINTS,locationInfo); + gwAPI.route(HttpMethods.GET,"/locate/:service",API.ENDPOINTS,locationInfo); + + + gwAPI.route(HttpMethods.GET,"/download/agent", API.VOID, new LocateCode(facade,"Redirect to latest Agent",false) { + @Override + public void handle(AuthzTrans arg0, HttpServletRequest arg1, HttpServletResponse arg2) throws Exception { + } + }); - gwAPI.route(HttpMethods.PUT,"/registration",API.MGMT_ENDPOINTS,new LocateCode(facade,"Put Location Information", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.putMgmtEndpoints(trans,req,resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } + gwAPI.route(HttpMethods.PUT,"/registration",API.MGMT_ENDPOINTS,new LocateCode(facade,"Put Location Information", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.putMgmtEndpoints(trans,req,resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } - } - }); + } + }); - gwAPI.route(HttpMethods.DELETE,"/registration",API.MGMT_ENDPOINTS,new LocateCode(facade,"Remove Location Information", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.removeMgmtEndpoints(trans,req,resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } + gwAPI.route(HttpMethods.DELETE,"/registration",API.MGMT_ENDPOINTS,new LocateCode(facade,"Remove Location Information", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.removeMgmtEndpoints(trans,req,resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } - } - }); + } + }); - } + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java index d2e4583c..8bdf479f 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java @@ -52,112 +52,112 @@ import org.onap.aaf.misc.env.TimeTaken; */ public class API_Proxy { - /** - * Normal Init level APIs - * - * @param gwAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { - - String aafurl = gwAPI.access.getProperty(Config.AAF_URL,null); - if(aafurl==null) { - } else { - //////// - // Transferring APIs - // But DO NOT transfer BasicAuth case... wastes resources. - /////// - final BasicAuthCode bac = new BasicAuthCode(gwAPI.aafAuthn,facade); - - gwAPI.routeAll(HttpMethods.GET,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy GET", true) { - @Override - public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { - if("/proxy/authn/basicAuth".equals(req.getPathInfo()) && !(req.getUserPrincipal() instanceof OAuth2Principal)) { - bac.handle(trans, req, resp); - } else { - TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); - try { - gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.OK_200); - ft.get(10000); // Covers return codes and err messages - return null; - } - }); - - } catch (CadiException | APIException e) { - trans.error().log(e); - } finally { - tt.done(); - } - } - } - }); - - gwAPI.routeAll(HttpMethods.POST,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy POST", true) { - @Override - public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { - TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); - try { - gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.CREATED_201); - ft.get(10000); // Covers return codes and err messages - return null; - } - }); - } catch (CadiException | APIException e) { - trans.error().log(e); - } finally { - tt.done(); - } - } - }); - - gwAPI.routeAll(HttpMethods.PUT,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy PUT", true) { - @Override - public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { - TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); - try { - gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.OK_200); - ft.get(10000); // Covers return codes and err messages - return null; - } - }); - } catch (CadiException | APIException e) { - trans.error().log(e); - } finally { - tt.done(); - } - } - }); - - gwAPI.routeAll(HttpMethods.DELETE,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy DELETE", true) { - @Override - public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { - TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); - try { - gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.OK_200); - ft.get(10000); // Covers return codes and err messages - return null; - } - }); - } catch (CadiException | APIException e) { - trans.error().log(e); - } finally { - tt.done(); - } - } - }); - } - } + /** + * Normal Init level APIs + * + * @param gwAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { + + String aafurl = gwAPI.access.getProperty(Config.AAF_URL,null); + if(aafurl==null) { + } else { + //////// + // Transferring APIs + // But DO NOT transfer BasicAuth case... wastes resources. + /////// + final BasicAuthCode bac = new BasicAuthCode(gwAPI.aafAuthn,facade); + + gwAPI.routeAll(HttpMethods.GET,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy GET", true) { + @Override + public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { + if("/proxy/authn/basicAuth".equals(req.getPathInfo()) && !(req.getUserPrincipal() instanceof OAuth2Principal)) { + bac.handle(trans, req, resp); + } else { + TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); + try { + gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.OK_200); + ft.get(10000); // Covers return codes and err messages + return null; + } + }); + + } catch (CadiException | APIException e) { + trans.error().log(e); + } finally { + tt.done(); + } + } + } + }); + + gwAPI.routeAll(HttpMethods.POST,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy POST", true) { + @Override + public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { + TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); + try { + gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.CREATED_201); + ft.get(10000); // Covers return codes and err messages + return null; + } + }); + } catch (CadiException | APIException e) { + trans.error().log(e); + } finally { + tt.done(); + } + } + }); + + gwAPI.routeAll(HttpMethods.PUT,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy PUT", true) { + @Override + public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { + TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); + try { + gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.OK_200); + ft.get(10000); // Covers return codes and err messages + return null; + } + }); + } catch (CadiException | APIException e) { + trans.error().log(e); + } finally { + tt.done(); + } + } + }); + + gwAPI.routeAll(HttpMethods.DELETE,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy DELETE", true) { + @Override + public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { + TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); + try { + gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future ft = client.transfer(req,resp,pathParam(req, ":path"),HttpStatus.OK_200); + ft.get(10000); // Covers return codes and err messages + return null; + } + }); + } catch (CadiException | APIException e) { + trans.error().log(e); + } finally { + tt.done(); + } + } + }); + } + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade.java index 8fb719fe..4a2afa58 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade.java @@ -37,79 +37,79 @@ import org.onap.aaf.auth.rserv.RServlet; public interface LocateFacade { ///////////////////// STANDARD ELEMENTS ////////////////// - /** - * @param trans - * @param response - * @param result - */ - void error(AuthzTrans trans, HttpServletResponse response, Result result); + /** + * @param trans + * @param response + * @param result + */ + void error(AuthzTrans trans, HttpServletResponse response, Result result); - /** - * - * @param trans - * @param response - * @param status - */ - void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... detail); + /** + * + * @param trans + * @param response + * @param status + */ + void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... detail); - /** - * - * @param trans - * @param resp - * @param rservlet - * @return - */ - public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet); + /** + * + * @param trans + * @param resp + * @param rservlet + * @return + */ + public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet); - /** - * - * @param trans - * @param resp - * @param typeCode - * @param optional - * @return - */ - public abstract Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional); + /** + * + * @param trans + * @param resp + * @param typeCode + * @param optional + * @return + */ + public abstract Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional); - /** - * - * @param trans - * @param resp - * @param service - * @param version - * @param other - * @param string - * @return - */ - public abstract Result getEndpoints(AuthzTrans trans, HttpServletResponse resp, String key, - String service, String version, String other); + /** + * + * @param trans + * @param resp + * @param service + * @param version + * @param other + * @param string + * @return + */ + public abstract Result getEndpoints(AuthzTrans trans, HttpServletResponse resp, String key, + String service, String version, String other); - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - public abstract Result putMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + public abstract Result putMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - public abstract Result removeMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + public abstract Result removeMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - /** - * - * @param trans - * @param req - * @param resp - * @return - */ - public Result getConfig(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id, String type); + /** + * + * @param trans + * @param req + * @param resp + * @return + */ + public Result getConfig(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id, String type); } \ No newline at end of file diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeFactory.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeFactory.java index 84fc20a5..0bb9fbdb 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeFactory.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeFactory.java @@ -36,14 +36,14 @@ import locate_local.v1_0.Error;; public class LocateFacadeFactory { - public static LocateFacade_1_1 v1_1(AuthzEnv env, AAF_Locate locate, AuthzTrans trans, Data.TYPE type) throws APIException { - return new LocateFacade_1_1( - env, - new LocateServiceImpl< - InRequest, - Out, - Error>(trans,locate,new Mapper_1_1()), - type); - } + public static LocateFacade_1_1 v1_1(AuthzEnv env, AAF_Locate locate, AuthzTrans trans, Data.TYPE type) throws APIException { + return new LocateFacade_1_1( + env, + new LocateServiceImpl< + InRequest, + Out, + Error>(trans,locate,new Mapper_1_1()), + type); + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java index f655657b..f41fcd91 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java @@ -73,7 +73,7 @@ import locate_local.v1_0.Api; * 1) Interact with the Service Implementation (which might be supported by various kinds of Backend Storage) * 2) Validate incoming data (if applicable) * 3) Convert the Service response into the right Format, and mark the Content Type - * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. + * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. * 4) Log Service info, warnings and exceptions as necessary * 5) When asked by the API layer, this will create and write Error content to the OutputStream * @@ -84,336 +84,336 @@ import locate_local.v1_0.Api; * */ public abstract class LocateFacadeImpl extends FacadeImpl implements LocateFacade - { - private LocateService service; + { + private LocateService service; - private final RosettaDF errDF; - private final RosettaDF apiDF; - private final RosettaDF epDF; - private final RosettaDF mepDF; - private final RosettaDF confDF; + private final RosettaDF errDF; + private final RosettaDF apiDF; + private final RosettaDF epDF; + private final RosettaDF mepDF; + private final RosettaDF confDF; - private static long cacheClear = 0L, emptyCheck=0L; - private final static Map epsCache = new HashMap<>(); // protected manually, in getEndpoints + private static long cacheClear = 0L, emptyCheck=0L; + private final static Map epsCache = new HashMap<>(); // protected manually, in getEndpoints - public LocateFacadeImpl(AuthzEnv env, LocateService service, Data.TYPE dataType) throws APIException { - this.service = service; - (errDF = env.newDataFactory(mapper().getClass(API.ERROR))).in(dataType).out(dataType); - (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType); - (epDF = env.newDataFactory(mapper().getClass(API.ENDPOINTS))).in(dataType).out(dataType); - (mepDF = env.newDataFactory(mapper().getClass(API.MGMT_ENDPOINTS))).in(dataType).out(dataType); - (confDF = env.newDataFactory(mapper().getClass(API.CONFIG))).in(dataType).out(dataType); - } - - public Mapper mapper() { - return service.mapper(); - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) - * - * Note: Conforms to AT&T TSS RESTful Error Structure - */ - @Override - public void error(AuthzTrans trans, HttpServletResponse response, Result result) { - String msg = result.details==null?"":result.details.trim(); - String[] detail; - if(result.variables==null) { - detail = new String[1]; - } else { - int l = result.variables.length; - detail=new String[l+1]; - System.arraycopy(result.variables, 0, detail, 1, l); - } - error(trans, response, result.status,msg,detail); - } - - @Override - public void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... _detail) { - String[] detail = _detail; - if(detail.length==0) { - detail=new String[1]; - } - boolean hidemsg = false; - String msgId; - switch(status) { - case 202: - case ERR_ActionNotCompleted: - msgId = "SVC1202"; - detail[0] = "Accepted, Action not complete"; - response.setStatus(/*httpstatus=*/202); - break; + public LocateFacadeImpl(AuthzEnv env, LocateService service, Data.TYPE dataType) throws APIException { + this.service = service; + (errDF = env.newDataFactory(mapper().getClass(API.ERROR))).in(dataType).out(dataType); + (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType); + (epDF = env.newDataFactory(mapper().getClass(API.ENDPOINTS))).in(dataType).out(dataType); + (mepDF = env.newDataFactory(mapper().getClass(API.MGMT_ENDPOINTS))).in(dataType).out(dataType); + (confDF = env.newDataFactory(mapper().getClass(API.CONFIG))).in(dataType).out(dataType); + } + + public Mapper mapper() { + return service.mapper(); + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) + * + * Note: Conforms to AT&T TSS RESTful Error Structure + */ + @Override + public void error(AuthzTrans trans, HttpServletResponse response, Result result) { + String msg = result.details==null?"":result.details.trim(); + String[] detail; + if(result.variables==null) { + detail = new String[1]; + } else { + int l = result.variables.length; + detail=new String[l+1]; + System.arraycopy(result.variables, 0, detail, 1, l); + } + error(trans, response, result.status,msg,detail); + } + + @Override + public void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... _detail) { + String[] detail = _detail; + if(detail.length==0) { + detail=new String[1]; + } + boolean hidemsg = false; + String msgId; + switch(status) { + case 202: + case ERR_ActionNotCompleted: + msgId = "SVC1202"; + detail[0] = "Accepted, Action not complete"; + response.setStatus(/*httpstatus=*/202); + break; - case 403: - case ERR_Policy: - case ERR_Security: - case ERR_Denied: - msgId = "SVC1403"; - detail[0] = "Forbidden"; - response.setStatus(/*httpstatus=*/403); - break; - - case 404: - case ERR_NotFound: - msgId = "SVC1404"; - detail[0] = "Not Found"; - response.setStatus(/*httpstatus=*/404); - break; + case 403: + case ERR_Policy: + case ERR_Security: + case ERR_Denied: + msgId = "SVC1403"; + detail[0] = "Forbidden"; + response.setStatus(/*httpstatus=*/403); + break; + + case 404: + case ERR_NotFound: + msgId = "SVC1404"; + detail[0] = "Not Found"; + response.setStatus(/*httpstatus=*/404); + break; - case 406: - case ERR_BadData: - msgId="SVC1406"; - detail[0] = "Not Acceptable"; - response.setStatus(/*httpstatus=*/406); - break; - - case 409: - case ERR_ConflictAlreadyExists: - msgId = "SVC1409"; - detail[0] = "Conflict Already Exists"; - response.setStatus(/*httpstatus=*/409); - break; - - case 501: - case ERR_NotImplemented: - msgId = "SVC1501"; - detail[0] = "Not Implemented"; - response.setStatus(/*httpstatus=*/501); - break; - - default: - msgId = "SVC1500"; - detail[0] = "General Service Error"; - response.setStatus(/*httpstatus=*/500); - hidemsg = true; - break; - } + case 406: + case ERR_BadData: + msgId="SVC1406"; + detail[0] = "Not Acceptable"; + response.setStatus(/*httpstatus=*/406); + break; + + case 409: + case ERR_ConflictAlreadyExists: + msgId = "SVC1409"; + detail[0] = "Conflict Already Exists"; + response.setStatus(/*httpstatus=*/409); + break; + + case 501: + case ERR_NotImplemented: + msgId = "SVC1501"; + detail[0] = "Not Implemented"; + response.setStatus(/*httpstatus=*/501); + break; + + default: + msgId = "SVC1500"; + detail[0] = "General Service Error"; + response.setStatus(/*httpstatus=*/500); + hidemsg = true; + break; + } - try { - StringBuilder holder = new StringBuilder(); - ERROR em = mapper().errorFromMessage(holder,msgId,msg,detail); - trans.checkpoint( - "ErrResp [" + - msgId + - "] " + - holder.toString(), - Env.ALWAYS); - if(hidemsg) { - holder.setLength(0); - em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); - } - errDF.newData(trans).load(em).to(response.getOutputStream()); - - } catch (Exception e) { - trans.error().log(e,"unable to send response for",msg); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getAPI(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse) - */ - public final static String API_REPORT = "apiReport"; - @Override - public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet) { - TimeTaken tt = trans.start(API_REPORT, Env.SUB); - try { - Api api = new Api(); - Api.Route ar; - Method[] meths = LocateServiceImpl.class.getDeclaredMethods(); - for(RouteReport rr : rservlet.routeReport()) { - api.getRoute().add(ar = new Api.Route()); - ar.setMeth(rr.meth.name()); - ar.setPath(rr.path); - ar.setDesc(rr.desc); - ar.getContentType().addAll(rr.contextTypes); - for(Method m : meths) { - ApiDoc ad; - if((ad = m.getAnnotation(ApiDoc.class))!=null && - rr.meth.equals(ad.method()) && - rr.path.equals(ad.path())) { - for(String param : ad.params()) { - ar.getParam().add(param); - } - for(String text : ad.text()) { - ar.getComments().add(text); - } - ar.setExpected(ad.expectedCode()); - for(int ec : ad.errorCodes()) { - ar.getExplicitErr().add(ec); - } - } - } - } - apiDF.newData(trans).load(api).to(resp.getOutputStream()); - setContentType(resp,apiDF.getOutType()); - return Result.ok(); + try { + StringBuilder holder = new StringBuilder(); + ERROR em = mapper().errorFromMessage(holder,msgId,msg,detail); + trans.checkpoint( + "ErrResp [" + + msgId + + "] " + + holder.toString(), + Env.ALWAYS); + if(hidemsg) { + holder.setLength(0); + em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); + } + errDF.newData(trans).load(em).to(response.getOutputStream()); + + } catch (Exception e) { + trans.error().log(e,"unable to send response for",msg); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getAPI(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse) + */ + public final static String API_REPORT = "apiReport"; + @Override + public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet) { + TimeTaken tt = trans.start(API_REPORT, Env.SUB); + try { + Api api = new Api(); + Api.Route ar; + Method[] meths = LocateServiceImpl.class.getDeclaredMethods(); + for(RouteReport rr : rservlet.routeReport()) { + api.getRoute().add(ar = new Api.Route()); + ar.setMeth(rr.meth.name()); + ar.setPath(rr.path); + ar.setDesc(rr.desc); + ar.getContentType().addAll(rr.contextTypes); + for(Method m : meths) { + ApiDoc ad; + if((ad = m.getAnnotation(ApiDoc.class))!=null && + rr.meth.equals(ad.method()) && + rr.path.equals(ad.path())) { + for(String param : ad.params()) { + ar.getParam().add(param); + } + for(String text : ad.text()) { + ar.getComments().add(text); + } + ar.setExpected(ad.expectedCode()); + for(int ec : ad.errorCodes()) { + ar.getExplicitErr().add(ec); + } + } + } + } + apiDF.newData(trans).load(api).to(resp.getOutputStream()); + setContentType(resp,apiDF.getOutType()); + return Result.ok(); - } catch (Exception e) { - trans.error().log(e,IN,API_REPORT); - return Result.err(e); - } finally { - tt.done(); - } - } - - public final static String API_EXAMPLE = "apiExample"; - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getAPIExample(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) { - TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB); - try { - String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); - resp.getOutputStream().print(content); - setContentType(resp,content.contains(" getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) { + TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB); + try { + String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); + resp.getOutputStream().print(content); + setContentType(resp,content.contains(" getEndpoints(AuthzTrans trans, HttpServletResponse resp, String key, String service, String version, String other) { - TimeTaken tt = trans.start(GET_ENDPOINTS, Env.SUB); - try { - String output=null; - long temp=System.currentTimeMillis(); - synchronized(LOCK) { - if(cacheClear reps = this.service.getEndPoints(trans,service,version,other); - if(reps.notOK()) { - return Result.err(reps); - } else { - output = epDF.newData(trans).load(reps.value).asString(); - synchronized(LOCK) { - epsCache.put(key, output); - } - } - } - resp.getOutputStream().println(output); - setContentType(resp,epDF.getOutType()); - return Result.ok(); - } catch (Exception e) { - trans.error().log(e,IN,API_EXAMPLE); - return Result.err(Result.ERR_NotImplemented,e.getMessage()); - } finally { - tt.done(); - } - } + public final static String GET_ENDPOINTS = "getEndpoints"; + private final static Object LOCK = new Object(); + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.facade.GwFacade#getEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result getEndpoints(AuthzTrans trans, HttpServletResponse resp, String key, String service, String version, String other) { + TimeTaken tt = trans.start(GET_ENDPOINTS, Env.SUB); + try { + String output=null; + long temp=System.currentTimeMillis(); + synchronized(LOCK) { + if(cacheClear reps = this.service.getEndPoints(trans,service,version,other); + if(reps.notOK()) { + return Result.err(reps); + } else { + output = epDF.newData(trans).load(reps.value).asString(); + synchronized(LOCK) { + epsCache.put(key, output); + } + } + } + resp.getOutputStream().println(output); + setContentType(resp,epDF.getOutType()); + return Result.ok(); + } catch (Exception e) { + trans.error().log(e,IN,API_EXAMPLE); + return Result.err(Result.ERR_NotImplemented,e.getMessage()); + } finally { + tt.done(); + } + } - private static final String PUT_MGMT_ENDPOINTS = "Put Mgmt Endpoints"; - /* (non-Javadoc) - * @see org.onap.aaf.auth.locate.facade.GwFacade#putMgmtEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result putMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(PUT_MGMT_ENDPOINTS, Env.SUB|Env.ALWAYS); - try { - MGMT_ENDPOINTS rreq; - try { - RosettaData data = mepDF.newData().load(req.getInputStream()); - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,PUT_MGMT_ENDPOINTS); - return Result.err(Status.ERR_BadData,"Invalid Input"); + private static final String PUT_MGMT_ENDPOINTS = "Put Mgmt Endpoints"; + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.facade.GwFacade#putMgmtEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result putMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(PUT_MGMT_ENDPOINTS, Env.SUB|Env.ALWAYS); + try { + MGMT_ENDPOINTS rreq; + try { + RosettaData data = mepDF.newData().load(req.getInputStream()); + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,PUT_MGMT_ENDPOINTS); + return Result.err(Status.ERR_BadData,"Invalid Input"); - } - Result rp = service.putMgmtEndPoints(trans, rreq); - switch(rp.status) { - case OK: - synchronized(LOCK) { - cacheClear = 0L; - } - setContentType(resp,mepDF.getOutType()); - return Result.ok(); - default: - return rp; - } - } catch (Exception e) { - trans.error().log(e,IN,PUT_MGMT_ENDPOINTS); - return Result.err(e); - } finally { - tt.done(); - } - } + } + Result rp = service.putMgmtEndPoints(trans, rreq); + switch(rp.status) { + case OK: + synchronized(LOCK) { + cacheClear = 0L; + } + setContentType(resp,mepDF.getOutType()); + return Result.ok(); + default: + return rp; + } + } catch (Exception e) { + trans.error().log(e,IN,PUT_MGMT_ENDPOINTS); + return Result.err(e); + } finally { + tt.done(); + } + } - private static final String DELETE_MGMT_ENDPOINTS = "Delete Mgmt Endpoints"; - /* (non-Javadoc) - * @see org.onap.aaf.auth.locate.facade.GwFacade#removeMgmtEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result removeMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_MGMT_ENDPOINTS, Env.SUB|Env.ALWAYS); - try { - MGMT_ENDPOINTS rreq; - try { - RosettaData data = mepDF.newData().load(req.getInputStream()); - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,DELETE_MGMT_ENDPOINTS); - return Result.err(Status.ERR_BadData,"Invalid Input"); + private static final String DELETE_MGMT_ENDPOINTS = "Delete Mgmt Endpoints"; + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.facade.GwFacade#removeMgmtEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result removeMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_MGMT_ENDPOINTS, Env.SUB|Env.ALWAYS); + try { + MGMT_ENDPOINTS rreq; + try { + RosettaData data = mepDF.newData().load(req.getInputStream()); + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_MGMT_ENDPOINTS); + return Result.err(Status.ERR_BadData,"Invalid Input"); - } - Result rp = service.removeMgmtEndPoints(trans, rreq); - switch(rp.status) { - case OK: - synchronized(LOCK) { - cacheClear = 0L; - } - setContentType(resp,mepDF.getOutType()); - return Result.ok(); - default: - return rp; - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_MGMT_ENDPOINTS); - return Result.err(e); - } finally { - tt.done(); - } - } + } + Result rp = service.removeMgmtEndPoints(trans, rreq); + switch(rp.status) { + case OK: + synchronized(LOCK) { + cacheClear = 0L; + } + setContentType(resp,mepDF.getOutType()); + return Result.ok(); + default: + return rp; + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_MGMT_ENDPOINTS); + return Result.err(e); + } finally { + tt.done(); + } + } - private static final String GET_CONFIG = "Get Configuration"; - @Override - public Result getConfig(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, final String id, final String type) { - TimeTaken tt = trans.start(GET_CONFIG, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getConfig(trans, id, type); - switch(rp.status) { - case OK: - setContentType(resp,mepDF.getOutType()); - confDF.newData(trans).load(rp.value).to(resp.getOutputStream()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_CONFIG); - return Result.err(e); - } finally { - tt.done(); - } - } - + private static final String GET_CONFIG = "Get Configuration"; + @Override + public Result getConfig(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, final String id, final String type) { + TimeTaken tt = trans.start(GET_CONFIG, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getConfig(trans, id, type); + switch(rp.status) { + case OK: + setContentType(resp,mepDF.getOutType()); + confDF.newData(trans).load(rp.value).to(resp.getOutputStream()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CONFIG); + return Result.err(e); + } finally { + tt.done(); + } + } + } \ No newline at end of file diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade_1_1.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade_1_1.java index 87d98361..8f45058f 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade_1_1.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacade_1_1.java @@ -36,7 +36,7 @@ import locate_local.v1_0.Error; public class LocateFacade_1_1 extends LocateFacadeImpl { - public LocateFacade_1_1(AuthzEnv env, LocateService service, Data.TYPE type) throws APIException { - super(env, service, type); - } + public LocateFacade_1_1(AuthzEnv env, LocateService service, Data.TYPE type) throws APIException { + super(env, service, type); + } } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper.java index 7e012f2d..e2cd4bce 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper.java @@ -30,12 +30,12 @@ import locate.v1_0.MgmtEndpoint; public interface Mapper { - public enum API{IN_REQ,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIG,ERROR,VOID}; - public Class getClass(API api); - public A newInstance(API api); + public enum API{IN_REQ,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIG,ERROR,VOID}; + public Class getClass(API api); + public A newInstance(API api); - public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); - public Result endpoints(Result> resultDB, String version, String other); - public Data locateData(MgmtEndpoint me); + public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); + public Result endpoints(Result> resultDB, String version, String other); + public Data locateData(MgmtEndpoint me); } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java index 2edb54f9..d2eeb632 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java @@ -38,116 +38,116 @@ import locate_local.v1_0.InRequest; import locate_local.v1_0.Out; public class Mapper_1_1 implements Mapper { - - @Override - public Class getClass(API api) { - switch(api) { - case IN_REQ: return InRequest.class; - case OUT: return Out.class; - case ERROR: return Error.class; - case VOID: return Void.class; - case ENDPOINTS: return Endpoints.class; - case MGMT_ENDPOINTS: return MgmtEndpoints.class; - case CONFIG: return Configuration.class; - } - return null; - } + + @Override + public Class getClass(API api) { + switch(api) { + case IN_REQ: return InRequest.class; + case OUT: return Out.class; + case ERROR: return Error.class; + case VOID: return Void.class; + case ENDPOINTS: return Endpoints.class; + case MGMT_ENDPOINTS: return MgmtEndpoints.class; + case CONFIG: return Configuration.class; + } + return null; + } - @SuppressWarnings("unchecked") - @Override - public A newInstance(API api) { - switch(api) { - case IN_REQ: return (A) new InRequest(); - case OUT: return (A) new Out(); - case ERROR: return (A)new Error(); - case ENDPOINTS: return (A) new Endpoints(); - case MGMT_ENDPOINTS: return (A) new MgmtEndpoints(); - case CONFIG: return (A) new Configuration(); - case VOID: return null; - } - return null; - } + @SuppressWarnings("unchecked") + @Override + public A newInstance(API api) { + switch(api) { + case IN_REQ: return (A) new InRequest(); + case OUT: return (A) new Out(); + case ERROR: return (A)new Error(); + case ENDPOINTS: return (A) new Endpoints(); + case MGMT_ENDPOINTS: return (A) new MgmtEndpoints(); + case CONFIG: return (A) new Configuration(); + case VOID: return null; + } + return null; + } - ////////////// Mapping Functions ///////////// - @Override - public locate_local.v1_0.Error errorFromMessage(StringBuilder holder, String msgID, String text,String... var) { - Error err = new Error(); - err.setMessageId(msgID); - // AT&T Restful Error Format requires numbers "%" placements - err.setText(Vars.convert(holder, text, var)); - for(String s : var) { - err.getVariables().add(s); - } - return err; - } + ////////////// Mapping Functions ///////////// + @Override + public locate_local.v1_0.Error errorFromMessage(StringBuilder holder, String msgID, String text,String... var) { + Error err = new Error(); + err.setMessageId(msgID); + // AT&T Restful Error Format requires numbers "%" placements + err.setText(Vars.convert(holder, text, var)); + for(String s : var) { + err.getVariables().add(s); + } + return err; + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.locate.mapper.Mapper#endpoints(org.onap.aaf.auth.layer.test.Result, java.lang.String, java.lang.String) - */ - @Override - public Result endpoints(Result> resultDB, String version, String other) { - if(resultDB.notOK()) { - return Result.err(resultDB); - } - int major=-1, minor=-1, patch=-1, pkg=-1; - if(version!=null) { - try { - String[] v = Split.split('.',version); - if(v.length>0) {major = Integer.parseInt(v[0]);} - if(v.length>1) {minor = Integer.parseInt(v[1]);} - if(v.length>2) {patch = Integer.parseInt(v[2]);} - if(v.length>3) {pkg = Integer.parseInt(v[3]);} - } catch (NumberFormatException e) { - return Result.err(Result.ERR_BadData,"Invalid Version String " + version); - } - } - Endpoints eps = new Endpoints(); - List leps = eps.getEndpoint(); - for(Data d : resultDB.value) { - if((major<0 || major==d.major) && - (minor<0 || minor<=d.minor) && - (patch<0 || patch==d.patch) && - (pkg<0 || pkg ==d.pkg)) { - Endpoint ep = new Endpoint(); - ep.setName(d.name); - ep.setHostname(d.hostname); - ep.setPort(d.port); - ep.setMajor(d.major); - ep.setMinor(d.minor); - ep.setPatch(d.patch); - ep.setPkg(d.pkg); - ep.setLatitude(d.latitude); - ep.setLongitude(d.longitude); - ep.setProtocol(d.protocol); - for(String s : d.subprotocol(false)) { - ep.getSubprotocol().add(s); - } - leps.add(ep); - } - } - return Result.ok(eps); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.mapper.Mapper#endpoints(org.onap.aaf.auth.layer.test.Result, java.lang.String, java.lang.String) + */ + @Override + public Result endpoints(Result> resultDB, String version, String other) { + if(resultDB.notOK()) { + return Result.err(resultDB); + } + int major=-1, minor=-1, patch=-1, pkg=-1; + if(version!=null) { + try { + String[] v = Split.split('.',version); + if(v.length>0) {major = Integer.parseInt(v[0]);} + if(v.length>1) {minor = Integer.parseInt(v[1]);} + if(v.length>2) {patch = Integer.parseInt(v[2]);} + if(v.length>3) {pkg = Integer.parseInt(v[3]);} + } catch (NumberFormatException e) { + return Result.err(Result.ERR_BadData,"Invalid Version String " + version); + } + } + Endpoints eps = new Endpoints(); + List leps = eps.getEndpoint(); + for(Data d : resultDB.value) { + if((major<0 || major==d.major) && + (minor<0 || minor<=d.minor) && + (patch<0 || patch==d.patch) && + (pkg<0 || pkg ==d.pkg)) { + Endpoint ep = new Endpoint(); + ep.setName(d.name); + ep.setHostname(d.hostname); + ep.setPort(d.port); + ep.setMajor(d.major); + ep.setMinor(d.minor); + ep.setPatch(d.patch); + ep.setPkg(d.pkg); + ep.setLatitude(d.latitude); + ep.setLongitude(d.longitude); + ep.setProtocol(d.protocol); + for(String s : d.subprotocol(false)) { + ep.getSubprotocol().add(s); + } + leps.add(ep); + } + } + return Result.ok(eps); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.locate.mapper.Mapper#locateData(locate.v1_0.MgmtEndpoint) - */ - @Override - public Data locateData(MgmtEndpoint me) { - Data data = new Data(); - data.name = me.getName(); - data.port = me.getPort(); - data.hostname = me.getHostname(); - data.major = me.getMajor(); - data.minor = me.getMinor(); - data.patch = me.getPatch(); - data.pkg = me.getPkg(); - data.latitude = me.getLatitude(); - data.longitude = me.getLongitude(); - data.protocol = me.getProtocol(); - for(String s : me.getSubprotocol()) { - data.subprotocol(true).add(s); - } - return data; - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.mapper.Mapper#locateData(locate.v1_0.MgmtEndpoint) + */ + @Override + public Data locateData(MgmtEndpoint me) { + Data data = new Data(); + data.name = me.getName(); + data.port = me.getPort(); + data.hostname = me.getHostname(); + data.major = me.getMajor(); + data.minor = me.getMinor(); + data.patch = me.getPatch(); + data.pkg = me.getPkg(); + data.latitude = me.getLatitude(); + data.longitude = me.getLongitude(); + data.protocol = me.getProtocol(); + for(String s : me.getSubprotocol()) { + data.subprotocol(true).add(s); + } + return data; + } } \ No newline at end of file diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateService.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateService.java index ac2e3c46..47f3b984 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateService.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateService.java @@ -26,9 +26,9 @@ import org.onap.aaf.auth.layer.Result; import org.onap.aaf.auth.locate.mapper.Mapper; public interface LocateService { - public Mapper mapper(); - public Result getEndPoints(AuthzTrans trans, String service, String version, String other); - public Result putMgmtEndPoints(AuthzTrans trans, MGMT_ENDPOINTS meps); - public Result removeMgmtEndPoints(AuthzTrans trans, MGMT_ENDPOINTS meps); - public Result getConfig(AuthzTrans trans, String id, String type); + public Mapper mapper(); + public Result getEndPoints(AuthzTrans trans, String service, String version, String other); + public Result putMgmtEndPoints(AuthzTrans trans, MGMT_ENDPOINTS meps); + public Result removeMgmtEndPoints(AuthzTrans trans, MGMT_ENDPOINTS meps); + public Result getConfig(AuthzTrans trans, String id, String type); } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java index b2cdfab6..d0aae466 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java @@ -42,111 +42,111 @@ import locate.v1_1.Configuration; import locate.v1_1.Configuration.Props; public class LocateServiceImpl - implements LocateService { - private Mapper mapper; - protected LocateDAO locateDAO; - private ConfigDAO configDAO; - private boolean permToRegister; - - public LocateServiceImpl(AuthzTrans trans, AAF_Locate locate, Mapper mapper) throws APIException { - this.mapper = mapper; - this.locateDAO = locate.locateDAO; - this.configDAO = locate.configDAO; - permToRegister = false; //TODO Setup a Configuration for this - } - - public Mapper mapper() {return mapper;} + implements LocateService { + private Mapper mapper; + protected LocateDAO locateDAO; + private ConfigDAO configDAO; + private boolean permToRegister; + + public LocateServiceImpl(AuthzTrans trans, AAF_Locate locate, Mapper mapper) throws APIException { + this.mapper = mapper; + this.locateDAO = locate.locateDAO; + this.configDAO = locate.configDAO; + permToRegister = false; //TODO Setup a Configuration for this + } + + public Mapper mapper() {return mapper;} - @Override - public Result getEndPoints(AuthzTrans trans, String service, String version, String other) { - return mapper.endpoints(locateDAO.readByName(trans, service), version, other); - } + @Override + public Result getEndPoints(AuthzTrans trans, String service, String version, String other) { + return mapper.endpoints(locateDAO.readByName(trans, service), version, other); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.locate.service.GwService#putMgmtEndPoints(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result putMgmtEndPoints(AuthzTrans trans, MgmtEndpoints meps) { - LocateValidator v = new LocateValidator().mgmt_endpoints(meps, false); - if(v.err()) { - return Result.err(Result.ERR_BadData,v.errs()); - } - int count = 0; - for(MgmtEndpoint me : meps.getMgmtEndpoint()) { - if(permToRegister) { - int dot = me.getName().lastIndexOf('.'); // Note: Validator checks for NS for getName() - AAFPermission p = new AAFPermission(me.getName().substring(0,dot),"locator",me.getName(),"write"); - if(trans.fish(p)) { - LocateDAO.Data data = mapper.locateData(me); - locateDAO.update(trans, data, true); - ++count; - } else { - return Result.err(Result.ERR_Denied,"May not register service (needs " + p.getKey() + ')'); - } - } else { //TODO if(MechID is part of Namespace) { - LocateDAO.Data data = mapper.locateData(me); - locateDAO.update(trans, data, true); - ++count; - } - } - if(count>0) { - return Result.ok(); - } else { - return Result.err(Result.ERR_NotFound, "No endpoints found"); - } - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.service.GwService#putMgmtEndPoints(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result putMgmtEndPoints(AuthzTrans trans, MgmtEndpoints meps) { + LocateValidator v = new LocateValidator().mgmt_endpoints(meps, false); + if(v.err()) { + return Result.err(Result.ERR_BadData,v.errs()); + } + int count = 0; + for(MgmtEndpoint me : meps.getMgmtEndpoint()) { + if(permToRegister) { + int dot = me.getName().lastIndexOf('.'); // Note: Validator checks for NS for getName() + AAFPermission p = new AAFPermission(me.getName().substring(0,dot),"locator",me.getName(),"write"); + if(trans.fish(p)) { + LocateDAO.Data data = mapper.locateData(me); + locateDAO.update(trans, data, true); + ++count; + } else { + return Result.err(Result.ERR_Denied,"May not register service (needs " + p.getKey() + ')'); + } + } else { //TODO if(MechID is part of Namespace) { + LocateDAO.Data data = mapper.locateData(me); + locateDAO.update(trans, data, true); + ++count; + } + } + if(count>0) { + return Result.ok(); + } else { + return Result.err(Result.ERR_NotFound, "No endpoints found"); + } + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.locate.service.GwService#removeMgmtEndPoints(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @Override - public Result removeMgmtEndPoints(AuthzTrans trans, MgmtEndpoints meps) { - LocateValidator v = new LocateValidator().mgmt_endpoint_key(meps); - if(v.err()) { - return Result.err(Result.ERR_BadData,v.errs()); - } - int count = 0; - for(MgmtEndpoint me : meps.getMgmtEndpoint()) { - int dot = me.getName().lastIndexOf('.'); // Note: Validator checks for NS for getName() - AAFPermission p = new AAFPermission(me.getName().substring(0,dot),"locator",me.getHostname(),"write"); - if(trans.fish(p)) { - LocateDAO.Data data = mapper.locateData(me); - data.port_key = UUID.randomUUID(); - locateDAO.delete(trans, data, false); - ++count; - } else { - return Result.err(Result.ERR_Denied,"May not register service (needs " + p.getKey() + ')'); - } - } - if(count>0) { - return Result.ok(); - } else { - return Result.err(Result.ERR_NotFound, "No endpoints found"); - } - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.service.GwService#removeMgmtEndPoints(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @Override + public Result removeMgmtEndPoints(AuthzTrans trans, MgmtEndpoints meps) { + LocateValidator v = new LocateValidator().mgmt_endpoint_key(meps); + if(v.err()) { + return Result.err(Result.ERR_BadData,v.errs()); + } + int count = 0; + for(MgmtEndpoint me : meps.getMgmtEndpoint()) { + int dot = me.getName().lastIndexOf('.'); // Note: Validator checks for NS for getName() + AAFPermission p = new AAFPermission(me.getName().substring(0,dot),"locator",me.getHostname(),"write"); + if(trans.fish(p)) { + LocateDAO.Data data = mapper.locateData(me); + data.port_key = UUID.randomUUID(); + locateDAO.delete(trans, data, false); + ++count; + } else { + return Result.err(Result.ERR_Denied,"May not register service (needs " + p.getKey() + ')'); + } + } + if(count>0) { + return Result.ok(); + } else { + return Result.err(Result.ERR_NotFound, "No endpoints found"); + } + } - ///// ADDED v1_1 - /* (non-Javadoc) - * @see org.onap.aaf.auth.locate.service.LocateService#getConfig(org.onap.aaf.auth.env.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result getConfig(AuthzTrans trans, String id, String type) { - Result> dr = configDAO.readName(trans, type); - Configuration c = new Configuration(); - c.setName(type); - Props p; - - if(dr.isOKhasData()) { - for(ConfigDAO.Data data : dr.value) { - p = new Props(); - p.setTag(data.tag); - p.setValue(data.value); - c.getProps().add(p); - } - } - return Result.ok(c); - //return Result.err(Result.ERR_NotImplemented,"not done yet"); - } + ///// ADDED v1_1 + /* (non-Javadoc) + * @see org.onap.aaf.auth.locate.service.LocateService#getConfig(org.onap.aaf.auth.env.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result getConfig(AuthzTrans trans, String id, String type) { + Result> dr = configDAO.readName(trans, type); + Configuration c = new Configuration(); + c.setName(type); + Props p; + + if(dr.isOKhasData()) { + for(ConfigDAO.Data data : dr.value) { + p = new Props(); + p.setTag(data.tag); + p.setValue(data.value); + c.getProps().add(p); + } + } + return Result.ok(c); + //return Result.err(Result.ERR_NotImplemented,"not done yet"); + } //////////////// APIs /////////////////// diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java index 89157826..6dd3d92a 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java @@ -39,103 +39,103 @@ import locate.v1_0.MgmtEndpoints; * */ public class LocateValidator extends Validator { - private LocateValidator endpoint_key(Endpoint e) { - if(e==null) { - msg("Endpoint Data is null."); - } else { - nullOrBlank("Endpoint Name", e.getName()); - if(e.getName()!=null) { - int idx = e.getName().indexOf('.'); - if(idx<=0) { - msg("Endpoint Name must prefixed by Namespace"); - } - } - nullOrBlank("Endpoint Hostname", e.getHostname()); - intRange("Endpoint Port",e.getPort(),0,1000000); - } - return this; - } + private LocateValidator endpoint_key(Endpoint e) { + if(e==null) { + msg("Endpoint Data is null."); + } else { + nullOrBlank("Endpoint Name", e.getName()); + if(e.getName()!=null) { + int idx = e.getName().indexOf('.'); + if(idx<=0) { + msg("Endpoint Name must prefixed by Namespace"); + } + } + nullOrBlank("Endpoint Hostname", e.getHostname()); + intRange("Endpoint Port",e.getPort(),0,1000000); + } + return this; + } - public LocateValidator endpoint(Endpoint e) { - endpoint_key(e); - if(e!=null) { - intRange("Endpoint Major Version",e.getMajor(),0,2000); - intRange("Endpoint Minor Version",e.getMinor(),0,2000); - intRange("Endpoint Patch Version",e.getPatch(),0,2000); - intRange("Endpoint Pkg Version",e.getPkg(),0,2000); - floatRange("Endpoint Latitude",e.getLatitude(),-90f,90f); - floatRange("Endpoint Longitude",e.getLongitude(),-180f,180f); - nullOrBlank("Endpoint Protocol", e.getProtocol()); - for(String s : e.getSubprotocol()) { - nullOrBlank("Endpoint Subprotocol", s); - } - } - return this; - } - - public LocateValidator endpoints(Endpoints e, boolean emptyNotOK) { - if(e==null) { - msg("Endpoints Data is null."); - } else { - if(emptyNotOK && e.getEndpoint().size()==0) { - msg("Endpoints contains no endpoints"); - } else { - for(Endpoint ep : e.getEndpoint()) { - endpoint(ep); - } - } - } - return this; - } + public LocateValidator endpoint(Endpoint e) { + endpoint_key(e); + if(e!=null) { + intRange("Endpoint Major Version",e.getMajor(),0,2000); + intRange("Endpoint Minor Version",e.getMinor(),0,2000); + intRange("Endpoint Patch Version",e.getPatch(),0,2000); + intRange("Endpoint Pkg Version",e.getPkg(),0,2000); + floatRange("Endpoint Latitude",e.getLatitude(),-90f,90f); + floatRange("Endpoint Longitude",e.getLongitude(),-180f,180f); + nullOrBlank("Endpoint Protocol", e.getProtocol()); + for(String s : e.getSubprotocol()) { + nullOrBlank("Endpoint Subprotocol", s); + } + } + return this; + } + + public LocateValidator endpoints(Endpoints e, boolean emptyNotOK) { + if(e==null) { + msg("Endpoints Data is null."); + } else { + if(emptyNotOK && e.getEndpoint().size()==0) { + msg("Endpoints contains no endpoints"); + } else { + for(Endpoint ep : e.getEndpoint()) { + endpoint(ep); + } + } + } + return this; + } - public LocateValidator mgmt_endpoint_key(MgmtEndpoints meps) { - if(meps==null) { - msg("MgmtEndpoints Data is null."); - } else { - for(MgmtEndpoint ep : meps.getMgmtEndpoint()) { - endpoint_key(ep); - } - } - return this; - } + public LocateValidator mgmt_endpoint_key(MgmtEndpoints meps) { + if(meps==null) { + msg("MgmtEndpoints Data is null."); + } else { + for(MgmtEndpoint ep : meps.getMgmtEndpoint()) { + endpoint_key(ep); + } + } + return this; + } - public LocateValidator mgmt_endpoints(MgmtEndpoints me, boolean emptyOK) { - if(me==null) { - msg("MgmtEndpoints Data is null."); - } else { - if(!emptyOK && me.getMgmtEndpoint().size()==0) { - msg("MgmtEndpoints contains no data"); - } else { - for(MgmtEndpoint ep : me.getMgmtEndpoint()) { - mgmt_endpoint(ep); - } - } - } - return this; - } + public LocateValidator mgmt_endpoints(MgmtEndpoints me, boolean emptyOK) { + if(me==null) { + msg("MgmtEndpoints Data is null."); + } else { + if(!emptyOK && me.getMgmtEndpoint().size()==0) { + msg("MgmtEndpoints contains no data"); + } else { + for(MgmtEndpoint ep : me.getMgmtEndpoint()) { + mgmt_endpoint(ep); + } + } + } + return this; + } - private LocateValidator mgmt_endpoint(MgmtEndpoint ep) { - endpoint(ep); - for(SpecialPorts sp : ep.getSpecialPorts()) { - specialPorts(sp); - } - return this; - } + private LocateValidator mgmt_endpoint(MgmtEndpoint ep) { + endpoint(ep); + for(SpecialPorts sp : ep.getSpecialPorts()) { + specialPorts(sp); + } + return this; + } - private LocateValidator specialPorts(SpecialPorts sp) { - if(sp==null) { - msg("Special Ports is null."); - } else { - nullOrBlank("Special Port Name",sp.getName()); - nullOrBlank("Special Port Protocol",sp.getProtocol()); - intRange("Special Port",sp.getPort(),0,1000000); - - for(String s : sp.getProtocolVersions()) { - nullOrBlank("Special Port Protocol Version", s); - } - } - return this; - } + private LocateValidator specialPorts(SpecialPorts sp) { + if(sp==null) { + msg("Special Ports is null."); + } else { + nullOrBlank("Special Port Name",sp.getName()); + nullOrBlank("Special Port Protocol",sp.getProtocol()); + intRange("Special Port",sp.getPort(),0,1000000); + + for(String s : sp.getProtocolVersions()) { + nullOrBlank("Special Port Protocol Version", s); + } + } + return this; + } } diff --git a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java index eea60eb0..cdae121a 100644 --- a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java +++ b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java @@ -42,74 +42,74 @@ import org.onap.aaf.misc.env.LogTarget; public class JU_BasicAuthCodeTest { - @Mock - AAFAuthn authn; + @Mock + AAFAuthn authn; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - AuthzTrans trans; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + AuthzTrans trans; - @Mock - HttpServletRequest req; + @Mock + HttpServletRequest req; - @Mock - HttpServletResponse resp; + @Mock + HttpServletResponse resp; - @Mock - LogTarget error; + @Mock + LogTarget error; - @Mock - LocateFacade facade; + @Mock + LocateFacade facade; - @Mock - BasicPrincipal basicPrincipal; - @Mock - X509Principal x509Principal; + @Mock + BasicPrincipal basicPrincipal; + @Mock + X509Principal x509Principal; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void testWithNullUserPrincipal() throws Exception { - BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade); - LocateCode locateCode = basicAuthCode.clone(facade, false); + @Test + public void testWithNullUserPrincipal() throws Exception { + BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade); + LocateCode locateCode = basicAuthCode.clone(facade, false); - assertEquals(locateCode.desc(), basicAuthCode.desc()); + assertEquals(locateCode.desc(), basicAuthCode.desc()); - when(trans.getUserPrincipal()).thenReturn(null); - when(trans.error()).thenReturn(error); + when(trans.getUserPrincipal()).thenReturn(null); + when(trans.error()).thenReturn(error); - basicAuthCode.handle(trans, req, resp); - } + basicAuthCode.handle(trans, req, resp); + } - @Test - public void testWithBasicUserPrincipal() throws Exception { - BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade); - LocateCode locateCode = basicAuthCode.clone(facade, false); + @Test + public void testWithBasicUserPrincipal() throws Exception { + BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade); + LocateCode locateCode = basicAuthCode.clone(facade, false); - assertEquals(locateCode.desc(), basicAuthCode.desc()); + assertEquals(locateCode.desc(), basicAuthCode.desc()); - when(trans.getUserPrincipal()).thenReturn(basicPrincipal); + when(trans.getUserPrincipal()).thenReturn(basicPrincipal); - basicAuthCode.handle(trans, req, resp); + basicAuthCode.handle(trans, req, resp); - verify(resp).setStatus(HttpStatus.OK_200); - } + verify(resp).setStatus(HttpStatus.OK_200); + } - @Test - public void testWithX509UserPrincipal() throws Exception { - BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade); - LocateCode locateCode = basicAuthCode.clone(facade, false); + @Test + public void testWithX509UserPrincipal() throws Exception { + BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade); + LocateCode locateCode = basicAuthCode.clone(facade, false); - assertEquals(locateCode.desc(), basicAuthCode.desc()); + assertEquals(locateCode.desc(), basicAuthCode.desc()); - when(trans.getUserPrincipal()).thenReturn(x509Principal); - when(req.getHeader("Authorization")).thenReturn("Basic 76//76"); + when(trans.getUserPrincipal()).thenReturn(x509Principal); + when(req.getHeader("Authorization")).thenReturn("Basic 76//76"); - basicAuthCode.handle(trans, req, resp); + basicAuthCode.handle(trans, req, resp); - verify(resp).setStatus(HttpStatus.FORBIDDEN_403); - } + verify(resp).setStatus(HttpStatus.FORBIDDEN_403); + } } diff --git a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java index 26bea940..5422117c 100644 --- a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java +++ b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java @@ -35,31 +35,31 @@ import locate_local.v1_0.Out; public class JU_Mapper_1_0Test { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @Test - public void testGetClasses() { - Mapper_1_1 mapper = new Mapper_1_1(); - assertEquals(InRequest.class, mapper.getClass(API.IN_REQ)); - assertEquals(Out.class, mapper.getClass(API.OUT)); - assertEquals(Error.class, mapper.getClass(API.ERROR)); - assertEquals(Void.class, mapper.getClass(API.VOID)); - assertEquals(Endpoints.class, mapper.getClass(API.ENDPOINTS)); - assertEquals(MgmtEndpoints.class, mapper.getClass(API.MGMT_ENDPOINTS)); - } + @Test + public void testGetClasses() { + Mapper_1_1 mapper = new Mapper_1_1(); + assertEquals(InRequest.class, mapper.getClass(API.IN_REQ)); + assertEquals(Out.class, mapper.getClass(API.OUT)); + assertEquals(Error.class, mapper.getClass(API.ERROR)); + assertEquals(Void.class, mapper.getClass(API.VOID)); + assertEquals(Endpoints.class, mapper.getClass(API.ENDPOINTS)); + assertEquals(MgmtEndpoints.class, mapper.getClass(API.MGMT_ENDPOINTS)); + } - @Test - public void testNewInstance() { - Mapper_1_1 mapper = new Mapper_1_1(); - assertTrue(mapper.newInstance(API.IN_REQ) instanceof InRequest); - assertTrue(mapper.newInstance(API.OUT) instanceof Out); - assertTrue(mapper.newInstance(API.ERROR) instanceof Error); - assertTrue(mapper.newInstance(API.ENDPOINTS) instanceof Endpoints); - assertTrue(mapper.newInstance(API.MGMT_ENDPOINTS) instanceof MgmtEndpoints); - assertEquals(null, mapper.newInstance(API.VOID)); - } + @Test + public void testNewInstance() { + Mapper_1_1 mapper = new Mapper_1_1(); + assertTrue(mapper.newInstance(API.IN_REQ) instanceof InRequest); + assertTrue(mapper.newInstance(API.OUT) instanceof Out); + assertTrue(mapper.newInstance(API.ERROR) instanceof Error); + assertTrue(mapper.newInstance(API.ENDPOINTS) instanceof Endpoints); + assertTrue(mapper.newInstance(API.MGMT_ENDPOINTS) instanceof MgmtEndpoints); + assertEquals(null, mapper.newInstance(API.VOID)); + } } diff --git a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java index c66de60b..e3a74720 100644 --- a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java +++ b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java @@ -44,71 +44,71 @@ import locate.v1_0.MgmtEndpoints; public class JU_LocateServiceImplTest { - // Extend, because I don't want a "setter" in the original. Compromised with a protected... - private final class LocateServiceImplExtension extends LocateServiceImpl { - private LocateServiceImplExtension(AuthzTrans trans, AAF_Locate locate, Mapper mapper) throws APIException { - super(trans, locate, mapper); - } - public void set(LocateDAO ld) { - locateDAO=ld; - } - } - - @Mock - private AuthzTrans trans; - @Mock - private AAF_Locate aaf_locate; - @Mock - private LocateDAO locateDAO; - @Mock - private Mapper mapper; - @Mock - private Result> result; - @Mock - private Result endPointResult; - @Mock - private MgmtEndpoints meps; - @Mock - private MgmtEndpoint mgmtEndPoint; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test() throws APIException { - LocateServiceImplExtension locateServiceImpl = new LocateServiceImplExtension(trans, aaf_locate, mapper); - locateServiceImpl.set(locateDAO); - - assertEquals(mapper, locateServiceImpl.mapper()); - - when(locateDAO.readByName(trans, "http")).thenReturn(result); - when(mapper.endpoints(result, "1.0", "other")).thenReturn(endPointResult); - - Result output = locateServiceImpl.getEndPoints(trans, "http", "1.0", "other"); - - assertEquals(endPointResult, output); - - List mgmtEndPoints = new ArrayList<>(); - mgmtEndPoints.add(mgmtEndPoint); - - when(mgmtEndPoint.getName()).thenReturn("http.Endpoint1"); - when(mgmtEndPoint.getHostname()).thenReturn("HOST1"); - when(mgmtEndPoint.getPort()).thenReturn(9090); - when(mgmtEndPoint.getProtocol()).thenReturn("HTTP"); - - when(meps.getMgmtEndpoint()).thenReturn(mgmtEndPoints); - output = locateServiceImpl.putMgmtEndPoints(trans, meps); - - assertEquals(output.toString(), Result.ok().toString()); - - when(trans.fish(any())).thenReturn(true); - Data data = new LocateDAO.Data(); - when(mapper.locateData(mgmtEndPoint)).thenReturn(data); - output = locateServiceImpl.removeMgmtEndPoints(trans, meps); - - assertEquals(output.toString(), Result.ok().toString()); - } + // Extend, because I don't want a "setter" in the original. Compromised with a protected... + private final class LocateServiceImplExtension extends LocateServiceImpl { + private LocateServiceImplExtension(AuthzTrans trans, AAF_Locate locate, Mapper mapper) throws APIException { + super(trans, locate, mapper); + } + public void set(LocateDAO ld) { + locateDAO=ld; + } + } + + @Mock + private AuthzTrans trans; + @Mock + private AAF_Locate aaf_locate; + @Mock + private LocateDAO locateDAO; + @Mock + private Mapper mapper; + @Mock + private Result> result; + @Mock + private Result endPointResult; + @Mock + private MgmtEndpoints meps; + @Mock + private MgmtEndpoint mgmtEndPoint; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws APIException { + LocateServiceImplExtension locateServiceImpl = new LocateServiceImplExtension(trans, aaf_locate, mapper); + locateServiceImpl.set(locateDAO); + + assertEquals(mapper, locateServiceImpl.mapper()); + + when(locateDAO.readByName(trans, "http")).thenReturn(result); + when(mapper.endpoints(result, "1.0", "other")).thenReturn(endPointResult); + + Result output = locateServiceImpl.getEndPoints(trans, "http", "1.0", "other"); + + assertEquals(endPointResult, output); + + List mgmtEndPoints = new ArrayList<>(); + mgmtEndPoints.add(mgmtEndPoint); + + when(mgmtEndPoint.getName()).thenReturn("http.Endpoint1"); + when(mgmtEndPoint.getHostname()).thenReturn("HOST1"); + when(mgmtEndPoint.getPort()).thenReturn(9090); + when(mgmtEndPoint.getProtocol()).thenReturn("HTTP"); + + when(meps.getMgmtEndpoint()).thenReturn(mgmtEndPoints); + output = locateServiceImpl.putMgmtEndPoints(trans, meps); + + assertEquals(output.toString(), Result.ok().toString()); + + when(trans.fish(any())).thenReturn(true); + Data data = new LocateDAO.Data(); + when(mapper.locateData(mgmtEndPoint)).thenReturn(data); + output = locateServiceImpl.removeMgmtEndPoints(trans, meps); + + assertEquals(output.toString(), Result.ok().toString()); + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java index d73c3be3..3ae80e3c 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java @@ -66,140 +66,140 @@ import com.datastax.driver.core.Cluster; import aafoauth.v2_0.Introspect; public class AAF_OAuth extends AbsService { - private static final String DOT_OAUTH = ".oauth"; - public Map cacheUser; - public AAFAuthn aafAuthn; - public AAFLurPerm aafLurPerm; - private final OAuthService service; - private OAFacade1_0 facade1_0; - private final Question question; - private TokenPermLoader tpLoader; - private final Cluster cluster; - - /** - * Construct AuthzAPI with all the Context Supporting Routes that Authz needs - * - * @param env - * @param si - * @param dm - * @param decryptor - * @throws APIException - */ - public AAF_OAuth(final AuthzEnv env) throws Exception { - super(env.access(),env); - - String aaf_env = env.getProperty(Config.AAF_ENV); - if(aaf_env==null) { - throw new APIException("aaf_env needs to be set"); - } - - // Initialize Facade for all uses - AuthzTrans trans = env.newTrans(); - cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); - - aafLurPerm = aafCon().newLur(); - // Note: If you need both Authn and Authz construct the following: - aafAuthn = aafCon().newAuthn(aafLurPerm); - - // Start Background Processing - // Question question = - question = new Question(trans, cluster, CassAccess.KEYSPACE, true); - - // Have AAFLocator object Create DirectLocators for Location needs - AbsAAFLocator.setCreator(new DirectLocatorCreator(env, question.locateDAO)); - - - service = new OAuthService(env.access(),trans,question); - facade1_0 = OAFacadeFactory.v1_0(this, trans, service, TYPE.JSON); - StringBuilder sb = new StringBuilder(); - trans.auditTrail(2, sb); - trans.init().log(sb); - - API_Token.init(this, facade1_0); - } - - /** - * Setup XML and JSON implementations for each supported Version type - * - * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties - * to do Versions and Content switches - * - */ - public void route(HttpMethods meth, String path, API api, HttpCode> code) throws Exception { - String version = "1.0"; - // Get Correct API Class from Mapper - Class respCls = facade1_0.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); - // setup Application API HTML ContentTypes for JSON and Route - String application = applicationJSON(respCls, version); - if(meth.equals(HttpMethods.POST)) { - route(env,meth,path,code,application,"application/json;version="+version,"application/x-www-form-urlencoded","*/*"); - } else { - route(env,meth,path,code,application,"application/json;version="+version,"*/*"); - } - } - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - try { - DirectOAuthTAF doat = new DirectOAuthTAF(env,question,facade1_0); - Object[] atl=new Object[additionalTafLurs.length+2]; - atl[0] = doat; - atl[1] = doat.directUserPass(); - - if(additionalTafLurs.length>0) { - System.arraycopy(additionalTafLurs, 0, atl, 2, additionalTafLurs.length); - } - - return new Filter[] { - new AuthzTransFilter(env,aafCon(), - new AAFTrustChecker((Env)env), - atl - )}; - } catch (NumberFormatException | APIException e) { - throw new CadiException("Invalid Property information", e); - } - } - - @SuppressWarnings("unchecked") - @Override - public Registrant[] registrants(final int port) throws CadiException { - return new Registrant[] { - new DirectRegistrar(access,question.locateDAO,app_name,app_version,port), - new DirectRegistrar(access,question.locateDAO,app_name.replace(DOT_OAUTH, ".token"),app_version,port), - new DirectRegistrar(access,question.locateDAO,app_name.replace(DOT_OAUTH, ".introspect"),app_version,port) - - }; - } - - - @Override - public void destroy() { - Cache.stopTimer(); - if(service!=null) { - service.close(); - } - if(cluster!=null) { - cluster.close(); - } - super.destroy(); - } - - // For use in CADI ONLY - public TokenMgr.TokenPermLoader tpLoader() { - return tpLoader; - } - - public static void main(final String[] args) { - try { - Log4JLogIt logIt = new Log4JLogIt(args, "oauth"); - PropAccess propAccess = new PropAccess(logIt,args); - - AAF_OAuth service = new AAF_OAuth(new AuthzEnv(propAccess)); - JettyServiceStarter jss = new JettyServiceStarter(service); - jss.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + private static final String DOT_OAUTH = ".oauth"; + public Map cacheUser; + public AAFAuthn aafAuthn; + public AAFLurPerm aafLurPerm; + private final OAuthService service; + private OAFacade1_0 facade1_0; + private final Question question; + private TokenPermLoader tpLoader; + private final Cluster cluster; + + /** + * Construct AuthzAPI with all the Context Supporting Routes that Authz needs + * + * @param env + * @param si + * @param dm + * @param decryptor + * @throws APIException + */ + public AAF_OAuth(final AuthzEnv env) throws Exception { + super(env.access(),env); + + String aaf_env = env.getProperty(Config.AAF_ENV); + if(aaf_env==null) { + throw new APIException("aaf_env needs to be set"); + } + + // Initialize Facade for all uses + AuthzTrans trans = env.newTrans(); + cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); + + aafLurPerm = aafCon().newLur(); + // Note: If you need both Authn and Authz construct the following: + aafAuthn = aafCon().newAuthn(aafLurPerm); + + // Start Background Processing + // Question question = + question = new Question(trans, cluster, CassAccess.KEYSPACE, true); + + // Have AAFLocator object Create DirectLocators for Location needs + AbsAAFLocator.setCreator(new DirectLocatorCreator(env, question.locateDAO)); + + + service = new OAuthService(env.access(),trans,question); + facade1_0 = OAFacadeFactory.v1_0(this, trans, service, TYPE.JSON); + StringBuilder sb = new StringBuilder(); + trans.auditTrail(2, sb); + trans.init().log(sb); + + API_Token.init(this, facade1_0); + } + + /** + * Setup XML and JSON implementations for each supported Version type + * + * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties + * to do Versions and Content switches + * + */ + public void route(HttpMethods meth, String path, API api, HttpCode> code) throws Exception { + String version = "1.0"; + // Get Correct API Class from Mapper + Class respCls = facade1_0.mapper().getClass(api); + if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + // setup Application API HTML ContentTypes for JSON and Route + String application = applicationJSON(respCls, version); + if(meth.equals(HttpMethods.POST)) { + route(env,meth,path,code,application,"application/json;version="+version,"application/x-www-form-urlencoded","*/*"); + } else { + route(env,meth,path,code,application,"application/json;version="+version,"*/*"); + } + } + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + try { + DirectOAuthTAF doat = new DirectOAuthTAF(env,question,facade1_0); + Object[] atl=new Object[additionalTafLurs.length+2]; + atl[0] = doat; + atl[1] = doat.directUserPass(); + + if(additionalTafLurs.length>0) { + System.arraycopy(additionalTafLurs, 0, atl, 2, additionalTafLurs.length); + } + + return new Filter[] { + new AuthzTransFilter(env,aafCon(), + new AAFTrustChecker((Env)env), + atl + )}; + } catch (NumberFormatException | APIException e) { + throw new CadiException("Invalid Property information", e); + } + } + + @SuppressWarnings("unchecked") + @Override + public Registrant[] registrants(final int port) throws CadiException { + return new Registrant[] { + new DirectRegistrar(access,question.locateDAO,app_name,app_version,port), + new DirectRegistrar(access,question.locateDAO,app_name.replace(DOT_OAUTH, ".token"),app_version,port), + new DirectRegistrar(access,question.locateDAO,app_name.replace(DOT_OAUTH, ".introspect"),app_version,port) + + }; + } + + + @Override + public void destroy() { + Cache.stopTimer(); + if(service!=null) { + service.close(); + } + if(cluster!=null) { + cluster.close(); + } + super.destroy(); + } + + // For use in CADI ONLY + public TokenMgr.TokenPermLoader tpLoader() { + return tpLoader; + } + + public static void main(final String[] args) { + try { + Log4JLogIt logIt = new Log4JLogIt(args, "oauth"); + PropAccess propAccess = new PropAccess(logIt,args); + + AAF_OAuth service = new AAF_OAuth(new AuthzEnv(propAccess)); + JettyServiceStarter jss = new JettyServiceStarter(service); + jss.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java index e602e863..bb882367 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java @@ -62,163 +62,163 @@ import org.onap.aaf.misc.env.APIException; import aafoauth.v2_0.Introspect; public class DirectOAuthTAF implements HttpTaf { - private PropAccess access; - private DirectIntrospect oaFacade; - private TokenMgr tkMgr; - private final DirectAAFUserPass directUserPass; - private TokenClient altIntrospectClient; - - public DirectOAuthTAF(AuthzEnv env, Question q, DirectIntrospect facade) throws APIException, CadiException { - access = env.access(); - oaFacade = facade; - tkMgr = TokenMgr.getInstance(access,"dbToken","dbIntrospect"); - String alt_url = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL,null); - TokenClientFactory tcf; - if(alt_url!=null) { - try { - tcf = TokenClientFactory.instance(access); - String[] split = Split.split(',', alt_url); - int timeout = split.length>1?Integer.parseInt(split[1]):3000; - altIntrospectClient = tcf.newClient(split[0], timeout); - altIntrospectClient.client_creds(access.getProperty(Config.AAF_ALT_CLIENT_ID,null), - access.getProperty(Config.AAF_ALT_CLIENT_SECRET,null)); - } catch (GeneralSecurityException | IOException | LocatorException e) { - throw new CadiException(e); - } - } - - directUserPass = new DirectAAFUserPass(env,q); - } - - @Override - public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { - String value; - String token; - if((value=req.getHeader("Authorization"))!=null && value.startsWith("Bearer ")) { - token = value.substring(7); - } else { - token = null; - } - - if("application/x-www-form-urlencoded".equals(req.getContentType())) { - Map map = req.getParameterMap(); - String client_id=null,client_secret=null,username=null,password=null; - for(Map.Entry es : map.entrySet()) { - switch(es.getKey()) { - case "client_id": - for(String s : es.getValue()) { - client_id=s; - } - break; - case "client_secret": - for(String s : es.getValue()) { - client_secret=s; - } - break; - case "username": - for(String s : es.getValue()) { - username=s; - } - break; - case "password": - for(String s : es.getValue()) { - password=s; - } - break; - case "token": - if(token!=null) { // Defined as both Bearer and Form Encoded - Error - return new OAuth2HttpTafResp(access, null, "Token Info found as both Bearer Token and Form Info", RESP.FAIL, resp, true); - } - for(String s : es.getValue()) { - token=s; - } - break; - // Ignore others - } - } - - if(client_id==null || client_secret==null) { - return new OAuth2HttpTafResp(access, null, "client_id and client_secret required", RESP.TRY_ANOTHER_TAF, resp, false); - } - - if(token==null) { // No Token to work with, use only Client_ID and Client_Secret - AuthzTrans trans = (AuthzTrans)req.getAttribute(TransFilter.TRANS_TAG); - - if(directUserPass.validate(client_id, Type.PASSWORD, client_secret.getBytes(), trans)) { - // Client_ID is valid - if(username==null) { // Validating just the Client_ID - return new OAuth2FormHttpTafResp(access,new OAuth2FormPrincipal(client_id,client_id),"OAuth client_id authenticated",RESP.IS_AUTHENTICATED,resp,false); - } else { - //TODO - Does a clientID need specific Authorization to pair authentication with user name? At the moment, no. - // username is ok. - if(password!=null) { - if(directUserPass.validate(username, Type.PASSWORD, password.getBytes(), trans)) { - return new OAuth2FormHttpTafResp(access,new OAuth2FormPrincipal(client_id, username),"OAuth username authenticated",RESP.IS_AUTHENTICATED,resp,false); - } else { - return new OAuth2HttpTafResp(access,null,"OAuth username " + username + " not authenticated ",RESP.FAIL,resp,true); - } - } else { // no Password - //TODO Check for Trust Permission, which requires looking up Perms? - return new OAuth2HttpTafResp(access,null,"OAuth username " + username + " not authenticated ",RESP.FAIL,resp,true); - } - } - } else { - return new OAuth2HttpTafResp(access,null,"OAuth client_id " + client_id + " not authenticated ",RESP.FAIL,resp,true); - } - } - } - - // OK, have only a Token to validate - if(token!=null) { - AuthzTrans trans = (AuthzTrans)req.getAttribute(TransFilter.TRANS_TAG); - - try { - Result ri = oaFacade.mappedIntrospect(trans, token); - if(ri.isOK()) { - TokenPerm tp = tkMgr.putIntrospect(ri.value, Hash.hashSHA256(token.getBytes())); - if(tp==null) { - return new OAuth2HttpTafResp(access, null, "TokenPerm persistence failure", RESP.FAIL, resp, false); - } else { - return new OAuth2HttpTafResp(access,new OAuth2Principal(tp,Hash.hashSHA256(token.getBytes())),"Token Authenticated",RESP.IS_AUTHENTICATED,resp,false); - } - } else { - return new OAuth2HttpTafResp(access, null, ri.errorString(), RESP.FAIL, resp, false); - } - } catch (APIException e) { - trans.error().log(e,"Error getting token"); - return new OAuth2HttpTafResp(access, null, "Error getting token: " + e.getMessage(), RESP.TRY_ANOTHER_TAF, resp, false); - } catch (NoSuchAlgorithmException e) { - return new OAuth2HttpTafResp(access, null, "Error in security algorithm: " + e.getMessage(), RESP.TRY_ANOTHER_TAF, resp, false); - } - } - return new OAuth2HttpTafResp(access, null, "No OAuth2 Credentials in OAuthForm", RESP.TRY_ANOTHER_TAF, resp, false); - } - - @Override - public Resp revalidate(CachedPrincipal prin, Object state) { - // TODO Auto-generated method stub - return null; - } - - class ServiceTPL implements TokenPermLoader { - private final AuthzTrans trans; - public ServiceTPL(AuthzTrans atrans) { - trans = atrans; - } - - @Override - public org.onap.aaf.cadi.client.Result load(String accessToken, byte[] cred) throws APIException, CadiException, LocatorException { - Result ri = oaFacade.mappedIntrospect(trans, accessToken); - if(ri.notOK()) { - //TODO what should the status mapping be? - return org.onap.aaf.cadi.client.Result.err(ri.status,ri.errorString()); - } - return org.onap.aaf.cadi.client.Result.ok(200,tkMgr.putIntrospect(ri.value, cred)); - } - } - - public DirectAAFUserPass directUserPass() { - return directUserPass; - } + private PropAccess access; + private DirectIntrospect oaFacade; + private TokenMgr tkMgr; + private final DirectAAFUserPass directUserPass; + private TokenClient altIntrospectClient; + + public DirectOAuthTAF(AuthzEnv env, Question q, DirectIntrospect facade) throws APIException, CadiException { + access = env.access(); + oaFacade = facade; + tkMgr = TokenMgr.getInstance(access,"dbToken","dbIntrospect"); + String alt_url = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL,null); + TokenClientFactory tcf; + if(alt_url!=null) { + try { + tcf = TokenClientFactory.instance(access); + String[] split = Split.split(',', alt_url); + int timeout = split.length>1?Integer.parseInt(split[1]):3000; + altIntrospectClient = tcf.newClient(split[0], timeout); + altIntrospectClient.client_creds(access.getProperty(Config.AAF_ALT_CLIENT_ID,null), + access.getProperty(Config.AAF_ALT_CLIENT_SECRET,null)); + } catch (GeneralSecurityException | IOException | LocatorException e) { + throw new CadiException(e); + } + } + + directUserPass = new DirectAAFUserPass(env,q); + } + + @Override + public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { + String value; + String token; + if((value=req.getHeader("Authorization"))!=null && value.startsWith("Bearer ")) { + token = value.substring(7); + } else { + token = null; + } + + if("application/x-www-form-urlencoded".equals(req.getContentType())) { + Map map = req.getParameterMap(); + String client_id=null,client_secret=null,username=null,password=null; + for(Map.Entry es : map.entrySet()) { + switch(es.getKey()) { + case "client_id": + for(String s : es.getValue()) { + client_id=s; + } + break; + case "client_secret": + for(String s : es.getValue()) { + client_secret=s; + } + break; + case "username": + for(String s : es.getValue()) { + username=s; + } + break; + case "password": + for(String s : es.getValue()) { + password=s; + } + break; + case "token": + if(token!=null) { // Defined as both Bearer and Form Encoded - Error + return new OAuth2HttpTafResp(access, null, "Token Info found as both Bearer Token and Form Info", RESP.FAIL, resp, true); + } + for(String s : es.getValue()) { + token=s; + } + break; + // Ignore others + } + } + + if(client_id==null || client_secret==null) { + return new OAuth2HttpTafResp(access, null, "client_id and client_secret required", RESP.TRY_ANOTHER_TAF, resp, false); + } + + if(token==null) { // No Token to work with, use only Client_ID and Client_Secret + AuthzTrans trans = (AuthzTrans)req.getAttribute(TransFilter.TRANS_TAG); + + if(directUserPass.validate(client_id, Type.PASSWORD, client_secret.getBytes(), trans)) { + // Client_ID is valid + if(username==null) { // Validating just the Client_ID + return new OAuth2FormHttpTafResp(access,new OAuth2FormPrincipal(client_id,client_id),"OAuth client_id authenticated",RESP.IS_AUTHENTICATED,resp,false); + } else { + //TODO - Does a clientID need specific Authorization to pair authentication with user name? At the moment, no. + // username is ok. + if(password!=null) { + if(directUserPass.validate(username, Type.PASSWORD, password.getBytes(), trans)) { + return new OAuth2FormHttpTafResp(access,new OAuth2FormPrincipal(client_id, username),"OAuth username authenticated",RESP.IS_AUTHENTICATED,resp,false); + } else { + return new OAuth2HttpTafResp(access,null,"OAuth username " + username + " not authenticated ",RESP.FAIL,resp,true); + } + } else { // no Password + //TODO Check for Trust Permission, which requires looking up Perms? + return new OAuth2HttpTafResp(access,null,"OAuth username " + username + " not authenticated ",RESP.FAIL,resp,true); + } + } + } else { + return new OAuth2HttpTafResp(access,null,"OAuth client_id " + client_id + " not authenticated ",RESP.FAIL,resp,true); + } + } + } + + // OK, have only a Token to validate + if(token!=null) { + AuthzTrans trans = (AuthzTrans)req.getAttribute(TransFilter.TRANS_TAG); + + try { + Result ri = oaFacade.mappedIntrospect(trans, token); + if(ri.isOK()) { + TokenPerm tp = tkMgr.putIntrospect(ri.value, Hash.hashSHA256(token.getBytes())); + if(tp==null) { + return new OAuth2HttpTafResp(access, null, "TokenPerm persistence failure", RESP.FAIL, resp, false); + } else { + return new OAuth2HttpTafResp(access,new OAuth2Principal(tp,Hash.hashSHA256(token.getBytes())),"Token Authenticated",RESP.IS_AUTHENTICATED,resp,false); + } + } else { + return new OAuth2HttpTafResp(access, null, ri.errorString(), RESP.FAIL, resp, false); + } + } catch (APIException e) { + trans.error().log(e,"Error getting token"); + return new OAuth2HttpTafResp(access, null, "Error getting token: " + e.getMessage(), RESP.TRY_ANOTHER_TAF, resp, false); + } catch (NoSuchAlgorithmException e) { + return new OAuth2HttpTafResp(access, null, "Error in security algorithm: " + e.getMessage(), RESP.TRY_ANOTHER_TAF, resp, false); + } + } + return new OAuth2HttpTafResp(access, null, "No OAuth2 Credentials in OAuthForm", RESP.TRY_ANOTHER_TAF, resp, false); + } + + @Override + public Resp revalidate(CachedPrincipal prin, Object state) { + // TODO Auto-generated method stub + return null; + } + + class ServiceTPL implements TokenPermLoader { + private final AuthzTrans trans; + public ServiceTPL(AuthzTrans atrans) { + trans = atrans; + } + + @Override + public org.onap.aaf.cadi.client.Result load(String accessToken, byte[] cred) throws APIException, CadiException, LocatorException { + Result ri = oaFacade.mappedIntrospect(trans, accessToken); + if(ri.notOK()) { + //TODO what should the status mapping be? + return org.onap.aaf.cadi.client.Result.err(ri.status,ri.errorString()); + } + return org.onap.aaf.cadi.client.Result.ok(200,tkMgr.putIntrospect(ri.value, cred)); + } + } + + public DirectAAFUserPass directUserPass() { + return directUserPass; + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OACode.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OACode.java index f60c689b..a0381c3e 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OACode.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OACode.java @@ -27,19 +27,19 @@ import org.onap.aaf.auth.rserv.HttpCode; import aafoauth.v2_0.Introspect; public abstract class OACode extends HttpCode> implements Cloneable { - public boolean useJSON; + public boolean useJSON; - public OACode(OAFacade facade, String description, boolean useJSON, String ... roles) { - super(facade, description, roles); - this.useJSON = useJSON; - } - - public D clone(OAFacade facade, boolean useJSON) throws Exception { - @SuppressWarnings("unchecked") - D d = (D)clone(); - d.useJSON = useJSON; - d.context = facade; - return d; - } - + public OACode(OAFacade facade, String description, boolean useJSON, String ... roles) { + super(facade, description, roles); + this.useJSON = useJSON; + } + + public D clone(OAFacade facade, boolean useJSON) throws Exception { + @SuppressWarnings("unchecked") + D d = (D)clone(); + d.useJSON = useJSON; + d.context = facade; + return d; + } + } \ No newline at end of file diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java index 4442e36f..161f6095 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java @@ -37,28 +37,28 @@ import org.onap.aaf.cadi.util.Split; public class OAuth2Filter implements Filter { - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - HttpServletRequest hreq = (HttpServletRequest)request; - Principal p = hreq.getUserPrincipal(); - if(request.getContentType().equals("application/x-www-form-urlencoded")) { - - } else if(p instanceof BearerPrincipal) { - for(String authz : Split.splitTrim(';', hreq.getHeader("Authorization"))) { - if(authz.startsWith("Bearer ")) { - ((BearerPrincipal)p).setBearer(authz.substring(7)); - } - } - } - chain.doFilter(request, response); - } + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest hreq = (HttpServletRequest)request; + Principal p = hreq.getUserPrincipal(); + if(request.getContentType().equals("application/x-www-form-urlencoded")) { + + } else if(p instanceof BearerPrincipal) { + for(String authz : Split.splitTrim(';', hreq.getHeader("Authorization"))) { + if(authz.startsWith("Bearer ")) { + ((BearerPrincipal)p).setBearer(authz.substring(7)); + } + } + } + chain.doFilter(request, response); + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2FormHttpTafResp.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2FormHttpTafResp.java index 6adb4641..f63daf89 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2FormHttpTafResp.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2FormHttpTafResp.java @@ -32,36 +32,36 @@ import org.onap.aaf.cadi.taf.AbsTafResp; import org.onap.aaf.cadi.taf.TafResp; public class OAuth2FormHttpTafResp extends AbsTafResp implements TafResp { - private static final String tafName = DirectOAuthTAF.class.getSimpleName(); - private HttpServletResponse httpResp; - private RESP status; - private final boolean wasFailed; - - public OAuth2FormHttpTafResp(Access access, OAuth2FormPrincipal principal, String desc, RESP status, HttpServletResponse resp, boolean wasFailed) { - super(access,tafName,principal, desc); - httpResp = resp; - this.status = status; - this.wasFailed = wasFailed; - } + private static final String tafName = DirectOAuthTAF.class.getSimpleName(); + private HttpServletResponse httpResp; + private RESP status; + private final boolean wasFailed; + + public OAuth2FormHttpTafResp(Access access, OAuth2FormPrincipal principal, String desc, RESP status, HttpServletResponse resp, boolean wasFailed) { + super(access,tafName,principal, desc); + httpResp = resp; + this.status = status; + this.wasFailed = wasFailed; + } - public OAuth2FormHttpTafResp(Access access, TrustPrincipal principal, String desc, RESP status,HttpServletResponse resp) { - super(access,tafName,principal, desc); - httpResp = resp; - this.status = status; - wasFailed = true; // if Trust Principal added, must be good - } + public OAuth2FormHttpTafResp(Access access, TrustPrincipal principal, String desc, RESP status,HttpServletResponse resp) { + super(access,tafName,principal, desc); + httpResp = resp; + this.status = status; + wasFailed = true; // if Trust Principal added, must be good + } - public RESP authenticate() throws IOException { - httpResp.setStatus(401); // Unauthorized - return RESP.HTTP_REDIRECT_INVOKED; - } + public RESP authenticate() throws IOException { + httpResp.setStatus(401); // Unauthorized + return RESP.HTTP_REDIRECT_INVOKED; + } - public RESP isAuthenticated() { - return status; - } + public RESP isAuthenticated() { + return status; + } - public boolean isFailedAttempt() { - return wasFailed; - } + public boolean isFailedAttempt() { + return wasFailed; + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java index f2836a7b..f795dfd3 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java @@ -40,43 +40,43 @@ import aafoauth.v2_0.Introspect; * */ public class API_Token { - // Hide Public Constructor - private API_Token() {} - - /** - * Normal Init level APIs - * - * @param authzAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_OAuth authzAPI, OAFacade facade) throws Exception { - //////// - // Overall APIs - /////// - authzAPI.route(HttpMethods.POST,"/token",API.TOKEN,new OACode(facade,"OAuth Token", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.createBearerToken(trans,req, resp); - if(r.isOK()) { - resp.setStatus(201/*HttpStatus.CREATED_201*/); - } else { - context.error(trans,resp,r); - } - } - }); - - authzAPI.route(HttpMethods.POST,"/introspect",API.INTROSPECT,new OACode(facade,"AAF Token Information", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.introspect(trans,req, resp); - if(r.isOK()) { - resp.setStatus(200 /*HttpStatus.OK_200*/); - } else { - context.error(trans,resp,r); - } - } - }); + // Hide Public Constructor + private API_Token() {} + + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_OAuth authzAPI, OAFacade facade) throws Exception { + //////// + // Overall APIs + /////// + authzAPI.route(HttpMethods.POST,"/token",API.TOKEN,new OACode(facade,"OAuth Token", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.createBearerToken(trans,req, resp); + if(r.isOK()) { + resp.setStatus(201/*HttpStatus.CREATED_201*/); + } else { + context.error(trans,resp,r); + } + } + }); + + authzAPI.route(HttpMethods.POST,"/introspect",API.INTROSPECT,new OACode(facade,"AAF Token Information", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.introspect(trans,req, resp); + if(r.isOK()) { + resp.setStatus(200 /*HttpStatus.OK_200*/); + } else { + context.error(trans,resp,r); + } + } + }); - } + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospect.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospect.java index 91423cef..6aec5feb 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospect.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospect.java @@ -25,5 +25,5 @@ import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.layer.Result; public interface DirectIntrospect { - Result mappedIntrospect(AuthzTrans trans, String token); + Result mappedIntrospect(AuthzTrans trans, String token); } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java index 91431c34..2935ea3d 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java @@ -29,29 +29,29 @@ import org.onap.aaf.auth.oauth.mapper.MapperIntrospect; import org.onap.aaf.auth.oauth.service.OAuthService; public class DirectIntrospectImpl extends FacadeImpl implements DirectIntrospect { - protected OAuthService service; - private MapperIntrospect mapper; + protected OAuthService service; + private MapperIntrospect mapper; - public DirectIntrospectImpl(OAuthService service, MapperIntrospect mapper) { - this.service = service; - this.mapper = mapper; - } + public DirectIntrospectImpl(OAuthService service, MapperIntrospect mapper) { + this.service = service; + this.mapper = mapper; + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.oauth.facade.OAFacade#mappedIntrospect(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) - */ - @Override - public Result mappedIntrospect(AuthzTrans trans, String token) { - Result rti; - Result rs = service.introspect(trans,token); - if(rs.notOK()) { - rti = Result.err(rs); - } else if(rs.isEmpty()) { - rti = Result.err(Result.ERR_NotFound,"No Token %s found",token); - } else { - rti = mapper.introspect(rs); - } - return rti; - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.oauth.facade.OAFacade#mappedIntrospect(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @Override + public Result mappedIntrospect(AuthzTrans trans, String token) { + Result rti; + Result rs = service.introspect(trans,token); + if(rs.notOK()) { + rti = Result.err(rs); + } else if(rs.isEmpty()) { + rti = Result.err(Result.ERR_NotFound,"No Token %s found",token); + } else { + rti = mapper.introspect(rs); + } + return rti; + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade.java index 52ff38b7..c0bb8e7e 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade.java @@ -37,27 +37,27 @@ import org.onap.aaf.auth.oauth.service.OAuthService; public interface OAFacade { ///////////////////// STANDARD ELEMENTS ////////////////// - /** - * @param trans - * @param response - * @param result - */ - public void error(AuthzTrans trans, HttpServletResponse response, Result result); + /** + * @param trans + * @param response + * @param result + */ + public void error(AuthzTrans trans, HttpServletResponse response, Result result); - /** - * - * @param trans - * @param response - * @param status - */ - public void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... detail); + /** + * + * @param trans + * @param response + * @param status + */ + public void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... detail); - public Result createBearerToken(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + public Result createBearerToken(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - public Result introspect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + public Result introspect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - public OAuthService service(); - + public OAuthService service(); + ///////////////////// STANDARD ELEMENTS ////////////////// diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade1_0.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade1_0.java index 204a104a..b0776d94 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade1_0.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacade1_0.java @@ -37,11 +37,11 @@ import aafoauth.v2_0.TokenRequest; * */ public class OAFacade1_0 extends OAFacadeImpl { - public OAFacade1_0(AAF_OAuth api, - OAuthService service, - Mapper mapper, - Data.TYPE type) throws APIException { - super(api, service, mapper, type); - } + public OAFacade1_0(AAF_OAuth api, + OAuthService service, + Mapper mapper, + Data.TYPE type) throws APIException { + super(api, service, mapper, type); + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeFactory.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeFactory.java index ff586007..11b7217e 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeFactory.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeFactory.java @@ -33,15 +33,15 @@ import aafoauth.v2_0.Introspect; public class OAFacadeFactory { - public static OAFacade1_0 v1_0(AAF_OAuth certman, AuthzTrans trans, OAuthService service, Data.TYPE type) throws APIException { - return new OAFacade1_0( - certman, - service, - new Mapper1_0(), - type); - } + public static OAFacade1_0 v1_0(AAF_OAuth certman, AuthzTrans trans, OAuthService service, Data.TYPE type) throws APIException { + return new OAFacade1_0( + certman, + service, + new Mapper1_0(), + type); + } - public static DirectIntrospect directV1_0(OAuthService service) { - return new DirectIntrospectImpl(service, new MapperIntrospect1_0()); - } + public static DirectIntrospect directV1_0(OAuthService service) { + return new DirectIntrospectImpl(service, new MapperIntrospect1_0()); + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java index ee35b8bf..cd1d7df1 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java @@ -69,7 +69,7 @@ import aaf.v2_0.Perms; * 1) Interact with the Service Implementation (which might be supported by various kinds of Backend Storage) * 2) Validate incoming data (if applicable) * 3) Convert the Service response into the right Format, and mark the Content Type - * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. + * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. * 4) Log Service info, warnings and exceptions as necessary * 5) When asked by the API layer, this will create and write Error content to the OutputStream * @@ -80,254 +80,254 @@ import aaf.v2_0.Perms; * */ public abstract class OAFacadeImpl - extends DirectIntrospectImpl implements OAFacade { - private static final String INVALID_INPUT = "Invalid Input"; - private final RosettaDF tokenDF; - private final RosettaDF tokenReqDF; - private final RosettaDF introspectDF; - private final RosettaDF errDF; - public final RosettaDF permsDF; - private final Mapper mapper; - - public OAFacadeImpl(AAF_OAuth api, - OAuthService service, - Mapper mapper, - Data.TYPE dataType) throws APIException { - super(service, mapper); - this.mapper = mapper; - AuthzEnv env = api.env; - (tokenReqDF = env.newDataFactory(mapper.getClass(API.TOKEN_REQ))).in(dataType).out(dataType); - (tokenDF = env.newDataFactory(mapper.getClass(API.TOKEN))).in(dataType).out(dataType); - (introspectDF = env.newDataFactory(mapper.getClass(API.INTROSPECT))).in(dataType).out(dataType); - (permsDF = env.newDataFactory(Perms.class)).in(dataType).out(dataType); - (errDF = env.newDataFactory(mapper.getClass(API.ERROR))).in(dataType).out(dataType); - } - - /////////////////////////// - // Tokens - /////////////////////////// - public static final String CREATE_TOKEN = "createToken"; - public static final String INTROSPECT = "introspect"; - - /* (non-Javadoc) - * @see org.onap.aaf.auth.oauth.facade.OAFacade#getToken(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, org.onap.aaf.auth.oauth.service.OAuthAPI) - */ - @Override - public Result createBearerToken(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(CREATE_TOKEN, Env.SUB|Env.ALWAYS); - try { - TOKEN_REQ request; - try { - request = mapper.tokenReqFromParams(req); - if(request==null) { - Data rd = tokenReqDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,rd.asString()); - } - request = rd.asObject(); - } - } catch(APIException e) { - trans.error().log(INVALID_INPUT,IN,CREATE_TOKEN); - return Result.err(Status.ERR_BadData,INVALID_INPUT); - } + extends DirectIntrospectImpl implements OAFacade { + private static final String INVALID_INPUT = "Invalid Input"; + private final RosettaDF tokenDF; + private final RosettaDF tokenReqDF; + private final RosettaDF introspectDF; + private final RosettaDF errDF; + public final RosettaDF permsDF; + private final Mapper mapper; + + public OAFacadeImpl(AAF_OAuth api, + OAuthService service, + Mapper mapper, + Data.TYPE dataType) throws APIException { + super(service, mapper); + this.mapper = mapper; + AuthzEnv env = api.env; + (tokenReqDF = env.newDataFactory(mapper.getClass(API.TOKEN_REQ))).in(dataType).out(dataType); + (tokenDF = env.newDataFactory(mapper.getClass(API.TOKEN))).in(dataType).out(dataType); + (introspectDF = env.newDataFactory(mapper.getClass(API.INTROSPECT))).in(dataType).out(dataType); + (permsDF = env.newDataFactory(Perms.class)).in(dataType).out(dataType); + (errDF = env.newDataFactory(mapper.getClass(API.ERROR))).in(dataType).out(dataType); + } + + /////////////////////////// + // Tokens + /////////////////////////// + public static final String CREATE_TOKEN = "createToken"; + public static final String INTROSPECT = "introspect"; + + /* (non-Javadoc) + * @see org.onap.aaf.auth.oauth.facade.OAFacade#getToken(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, org.onap.aaf.auth.oauth.service.OAuthAPI) + */ + @Override + public Result createBearerToken(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_TOKEN, Env.SUB|Env.ALWAYS); + try { + TOKEN_REQ request; + try { + request = mapper.tokenReqFromParams(req); + if(request==null) { + Data rd = tokenReqDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,rd.asString()); + } + request = rd.asObject(); + } + } catch(APIException e) { + trans.error().log(INVALID_INPUT,IN,CREATE_TOKEN); + return Result.err(Status.ERR_BadData,INVALID_INPUT); + } - // Already validated for Oauth2FormPrincipal -// Result rv = service.validate(trans,mapper.credsFromReq(request)); -// if(rv.notOK()) { -// return rv; -// } - Holder hgt = new Holder(GRANT_TYPE.unknown); - Result rs = service.createToken(trans,req,mapper.clientTokenReq(request,hgt),hgt); - Result rp; - if(rs.isOKhasData()) { - rp = mapper.tokenFromData(rs); - } else { - rp = Result.err(rs); - } - switch(rp.status) { - case OK: - RosettaData data = tokenDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - resp.getOutputStream().print('\n'); - setContentType(resp,tokenDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,CREATE_TOKEN); - return Result.err(e); - } finally { - tt.done(); - } + // Already validated for Oauth2FormPrincipal +// Result rv = service.validate(trans,mapper.credsFromReq(request)); +// if(rv.notOK()) { +// return rv; +// } + Holder hgt = new Holder(GRANT_TYPE.unknown); + Result rs = service.createToken(trans,req,mapper.clientTokenReq(request,hgt),hgt); + Result rp; + if(rs.isOKhasData()) { + rp = mapper.tokenFromData(rs); + } else { + rp = Result.err(rs); + } + switch(rp.status) { + case OK: + RosettaData data = tokenDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + resp.getOutputStream().print('\n'); + setContentType(resp,tokenDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_TOKEN); + return Result.err(e); + } finally { + tt.done(); + } - } + } /* (non-Javadoc) - * @see org.onap.aaf.auth.oauth.facade.OAFacade#Introspect(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result introspect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(INTROSPECT, Env.SUB|Env.ALWAYS); - try { - Principal p = req.getUserPrincipal(); - String token=null; - if(p != null) { - if(p instanceof OAuth2Principal) { - RosettaData data = introspectDF.newData(trans).load(mapper.fromPrincipal((OAuth2Principal)p)); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - resp.getOutputStream().print('\n'); - setContentType(resp,tokenDF.getOutType()); - return Result.ok(); - } else if(p instanceof OAuth2FormPrincipal) { - token = req.getParameter("token"); - } - } - - if(token==null) { - token = req.getParameter("access_token"); - if(token==null || token.isEmpty()) { - token = req.getHeader("Authorization"); - if(token != null && token.startsWith("Bearer ")) { - token = token.substring(7); - } else { - token = req.getParameter("token"); - if(token==null) { - return Result.err(Result.ERR_Security,"token is required"); - } - } - } - } + * @see org.onap.aaf.auth.oauth.facade.OAFacade#Introspect(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result introspect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(INTROSPECT, Env.SUB|Env.ALWAYS); + try { + Principal p = req.getUserPrincipal(); + String token=null; + if(p != null) { + if(p instanceof OAuth2Principal) { + RosettaData data = introspectDF.newData(trans).load(mapper.fromPrincipal((OAuth2Principal)p)); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + resp.getOutputStream().print('\n'); + setContentType(resp,tokenDF.getOutType()); + return Result.ok(); + } else if(p instanceof OAuth2FormPrincipal) { + token = req.getParameter("token"); + } + } + + if(token==null) { + token = req.getParameter("access_token"); + if(token==null || token.isEmpty()) { + token = req.getHeader("Authorization"); + if(token != null && token.startsWith("Bearer ")) { + token = token.substring(7); + } else { + token = req.getParameter("token"); + if(token==null) { + return Result.err(Result.ERR_Security,"token is required"); + } + } + } + } - Result rti = mappedIntrospect(trans,token); - switch(rti.status) { - case OK: - RosettaData data = introspectDF.newData(trans).load(rti.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - resp.getOutputStream().print('\n'); - setContentType(resp,tokenDF.getOutType()); - return Result.ok(); - default: - return Result.err(rti); - } - } catch (Exception e) { - trans.error().log(e,IN,INTROSPECT); - return Result.err(e); - } finally { - tt.done(); - } - } - + Result rti = mappedIntrospect(trans,token); + switch(rti.status) { + case OK: + RosettaData data = introspectDF.newData(trans).load(rti.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + resp.getOutputStream().print('\n'); + setContentType(resp,tokenDF.getOutType()); + return Result.ok(); + default: + return Result.err(rti); + } + } catch (Exception e) { + trans.error().log(e,IN,INTROSPECT); + return Result.err(e); + } finally { + tt.done(); + } + } + - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) - * - * Note: Conforms to AT&T TSS RESTful Error Structure - */ - @Override - public void error(AuthzTrans trans, HttpServletResponse response, Result result) { - error(trans, response, result.status, - result.details==null?"":result.details.trim(), - result.variables==null?new String[0]:result.variables); - } - - @Override - public void error(AuthzTrans trans, HttpServletResponse response, int status, final String _msg, final String ... _detail) { - String msgId; - String prefix; - boolean hidemsg=false; - switch(status) { - case 202: - case ERR_ActionNotCompleted: - msgId = "SVC1202"; - prefix = "Accepted, Action not complete"; - response.setStatus(/*httpstatus=*/202); - break; + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) + * + * Note: Conforms to AT&T TSS RESTful Error Structure + */ + @Override + public void error(AuthzTrans trans, HttpServletResponse response, Result result) { + error(trans, response, result.status, + result.details==null?"":result.details.trim(), + result.variables==null?new String[0]:result.variables); + } + + @Override + public void error(AuthzTrans trans, HttpServletResponse response, int status, final String _msg, final String ... _detail) { + String msgId; + String prefix; + boolean hidemsg=false; + switch(status) { + case 202: + case ERR_ActionNotCompleted: + msgId = "SVC1202"; + prefix = "Accepted, Action not complete"; + response.setStatus(/*httpstatus=*/202); + break; - case 403: - case ERR_Policy: - case ERR_Security: - case ERR_Denied: - msgId = "SVC1403"; - prefix = "Forbidden"; - response.setStatus(/*httpstatus=*/403); - break; - - case 404: - case ERR_NotFound: - msgId = "SVC1404"; - prefix = "Not Found"; - response.setStatus(/*httpstatus=*/404); - break; + case 403: + case ERR_Policy: + case ERR_Security: + case ERR_Denied: + msgId = "SVC1403"; + prefix = "Forbidden"; + response.setStatus(/*httpstatus=*/403); + break; + + case 404: + case ERR_NotFound: + msgId = "SVC1404"; + prefix = "Not Found"; + response.setStatus(/*httpstatus=*/404); + break; - case 406: - case ERR_BadData: - msgId="SVC1406"; - prefix = "Not Acceptable"; - response.setStatus(/*httpstatus=*/406); - break; - - case 409: - case ERR_ConflictAlreadyExists: - msgId = "SVC1409"; - prefix = "Conflict Already Exists"; - response.setStatus(/*httpstatus=*/409); - break; - - case 501: - case ERR_NotImplemented: - msgId = "SVC1501"; - prefix = "Not Implemented"; - response.setStatus(/*httpstatus=*/501); - break; - + case 406: + case ERR_BadData: + msgId="SVC1406"; + prefix = "Not Acceptable"; + response.setStatus(/*httpstatus=*/406); + break; + + case 409: + case ERR_ConflictAlreadyExists: + msgId = "SVC1409"; + prefix = "Conflict Already Exists"; + response.setStatus(/*httpstatus=*/409); + break; + + case 501: + case ERR_NotImplemented: + msgId = "SVC1501"; + prefix = "Not Implemented"; + response.setStatus(/*httpstatus=*/501); + break; + - default: - msgId = "SVC1500"; - prefix = "General Service Error"; - response.setStatus(/*httpstatus=*/500); - hidemsg=true; - break; - } + default: + msgId = "SVC1500"; + prefix = "General Service Error"; + response.setStatus(/*httpstatus=*/500); + hidemsg=true; + break; + } - try { - StringBuilder holder = new StringBuilder(); - ERROR em = mapper.errorFromMessage(holder, msgId,prefix + ": " + _msg,_detail); - trans.checkpoint( - "ErrResp [" + - msgId + - "] " + - holder.toString(), - Env.ALWAYS); - if(hidemsg) { - holder.setLength(0); - em = mapper.errorFromMessage(holder, msgId, "Server had an issue processing this request"); - } - errDF.newData(trans).load(em).to(response.getOutputStream()); - - } catch (Exception e) { - trans.error().log(e,"unable to send response for",_msg); - } - } - - public Mapper mapper() { - return mapper; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.oauth.facade.OAFacade#service() - */ - @Override - public OAuthService service() { - return service; - } + try { + StringBuilder holder = new StringBuilder(); + ERROR em = mapper.errorFromMessage(holder, msgId,prefix + ": " + _msg,_detail); + trans.checkpoint( + "ErrResp [" + + msgId + + "] " + + holder.toString(), + Env.ALWAYS); + if(hidemsg) { + holder.setLength(0); + em = mapper.errorFromMessage(holder, msgId, "Server had an issue processing this request"); + } + errDF.newData(trans).load(em).to(response.getOutputStream()); + + } catch (Exception e) { + trans.error().log(e,"unable to send response for",_msg); + } + } + + public Mapper mapper() { + return mapper; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.oauth.facade.OAFacade#service() + */ + @Override + public OAuthService service() { + return service; + } } \ No newline at end of file diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper.java index 55100e21..8e1c52e6 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper.java @@ -31,17 +31,17 @@ import org.onap.aaf.cadi.client.Holder; import org.onap.aaf.cadi.oauth.OAuth2Principal; public interface Mapper extends MapperIntrospect -{ - public enum API{TOKEN_REQ, TOKEN,INTROSPECT, ERROR,VOID}; - - public Class getClass(API api); - public A newInstance(API api); +{ + public enum API{TOKEN_REQ, TOKEN,INTROSPECT, ERROR,VOID}; + + public Class getClass(API api); + public A newInstance(API api); - public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); - public TOKEN_REQ tokenReqFromParams(HttpServletRequest req); - public OCreds credsFromReq(TOKEN_REQ tokReq); - - public OAuthTokenDAO.Data clientTokenReq(TOKEN_REQ tokReq, Holder hgt); - public Result tokenFromData(Result rs); - public INTROSPECT fromPrincipal(OAuth2Principal p); + public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); + public TOKEN_REQ tokenReqFromParams(HttpServletRequest req); + public OCreds credsFromReq(TOKEN_REQ tokReq); + + public OAuthTokenDAO.Data clientTokenReq(TOKEN_REQ tokReq, Holder hgt); + public Result tokenFromData(Result rs); + public INTROSPECT fromPrincipal(OAuth2Principal p); } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java index 688a03ce..4be079e4 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java @@ -46,179 +46,179 @@ import aafoauth.v2_0.TokenRequest; public class Mapper1_0 extends MapperIntrospect1_0 implements Mapper { - @Override - public Class getClass(API api) { - switch(api) { - case TOKEN_REQ: return TokenRequest.class; - case TOKEN: return Token.class; - case INTROSPECT: return Introspect.class; - case ERROR: return Error.class; - case VOID: return Void.class; - } - return null; - } - - @SuppressWarnings("unchecked") - @Override - public A newInstance(API api) { - switch(api) { - case TOKEN_REQ: return (A)new TokenRequest(); - case TOKEN: return (A)new Token(); - case INTROSPECT: return (A)new Introspect(); - case ERROR: return (A)new Error(); - case VOID: return null; - } - return null; - } - - ////////////// Mapping Functions ///////////// - @Override - public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { - Error err = new Error(); - err.setMessageId(msgID); - // AT&T Restful Error Format requires numbers "%" placements - err.setText(Vars.convert(holder, text, var)); - for(String s : var) { - err.getVariables().add(s); - } - return err; - } - - @Override - public TokenRequest tokenReqFromParams(HttpServletRequest req) { - TokenRequest tr = new TokenRequest(); - boolean data = false; - Map map = req.getParameterMap(); - for(Entry es : map.entrySet()) { - switch(es.getKey()) { - case "client_id": - if(es.getValue().length==1) { - tr.setClientId(es.getValue()[0]); - data = true; - } - break; - case "client_secret": - if(es.getValue().length==1) { - tr.setClientSecret(es.getValue()[0]); - data = true; - } - break; - case "username": - if(es.getValue().length==1) { - tr.setUsername(es.getValue()[0]); - data = true; - } - break; - case "password": - if(es.getValue().length==1) { - tr.setPassword(es.getValue()[0]); - data = true; - } - break; - case "scope": - if(es.getValue().length==1) { - tr.setScope(es.getValue()[0]); - data = true; - } - break; - case "grant_type": - if(es.getValue().length==1) { - tr.setGrantType(es.getValue()[0]); - data = true; - } - break; - case "refresh_token": - if(es.getValue().length==1) { - tr.setRefreshToken(es.getValue()[0]); - data = true; - } - break; - - } - } - return data?tr:null; - } - - - - /* (non-Javadoc) - * @see org.onap.aaf.auth.oauth.mapper.Mapper#credsFromReq(javax.servlet.http.HttpServletRequest) - */ - @Override - public OCreds credsFromReq(TokenRequest tokReq) { - return new OCreds(tokReq.getClientId(),tokReq.getClientSecret(), - tokReq.getUsername(),tokReq.getPassword()); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.oauth.mapper.Mapper#tokenReq(java.lang.Object) - */ - @Override - public Data clientTokenReq(TokenRequest tokReq, Holder hgt) { - OAuthTokenDAO.Data tdd = new OAuthTokenDAO.Data(); - tdd.client_id = tokReq.getClientId(); - tdd.user = tokReq.getUsername(); - if(tokReq.getRefreshToken()!=null) { - tdd.refresh=tokReq.getRefreshToken(); - } - - for(GRANT_TYPE ttt : GRANT_TYPE.values()) { - if(ttt.name().equals(tokReq.getGrantType())) { - hgt.set(ttt); - break; - } - } - - switch(hgt.get()) { - case client_credentials: - case password: - case refresh_token: - tdd.type = CLIENT_TYPE.confidential.ordinal(); - break; - default: - tdd.type = CLIENT_TYPE.unknown.ordinal(); - break; - } - String scopes=tokReq.getScope(); - if(scopes!=null) { - Set ss = tdd.scopes(true); - for(String s: Split.split(' ', tokReq.getScope())) { - ss.add(s); - } - } - - tdd.state = tokReq.getState(); - return tdd; - } - - @Override - public Result tokenFromData(Result rd) { - if(rd.notOK()) { - return Result.err(rd); - } - Data d = rd.value; - Token token = new Token(); - if(OAuthService.TOKEN_TYPE.values().length>d.type) { - token.setTokenType(OAuthService.TOKEN_TYPE.values()[d.type].name()); - } else { - token.setTokenType("Invalid"); - } - token.setAccessToken(d.id); - token.setRefreshToken(d.refresh); - token.setExpiresIn((int)(d.exp_sec-(System.currentTimeMillis())/1000)); - token.setScope(getScopes(d.scopes(false))); - token.setState(d.state); - return Result.ok(token); - } - - - - /* (non-Javadoc) - * @see org.onap.aaf.auth.oauth.mapper.Mapper#fromPrincipal(org.onap.aaf.cadi.oauth.OAuth2Principal) - */ - @Override - public Introspect fromPrincipal(OAuth2Principal p) { - return p.tokenPerm().getIntrospect(); - } + @Override + public Class getClass(API api) { + switch(api) { + case TOKEN_REQ: return TokenRequest.class; + case TOKEN: return Token.class; + case INTROSPECT: return Introspect.class; + case ERROR: return Error.class; + case VOID: return Void.class; + } + return null; + } + + @SuppressWarnings("unchecked") + @Override + public A newInstance(API api) { + switch(api) { + case TOKEN_REQ: return (A)new TokenRequest(); + case TOKEN: return (A)new Token(); + case INTROSPECT: return (A)new Introspect(); + case ERROR: return (A)new Error(); + case VOID: return null; + } + return null; + } + + ////////////// Mapping Functions ///////////// + @Override + public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { + Error err = new Error(); + err.setMessageId(msgID); + // AT&T Restful Error Format requires numbers "%" placements + err.setText(Vars.convert(holder, text, var)); + for(String s : var) { + err.getVariables().add(s); + } + return err; + } + + @Override + public TokenRequest tokenReqFromParams(HttpServletRequest req) { + TokenRequest tr = new TokenRequest(); + boolean data = false; + Map map = req.getParameterMap(); + for(Entry es : map.entrySet()) { + switch(es.getKey()) { + case "client_id": + if(es.getValue().length==1) { + tr.setClientId(es.getValue()[0]); + data = true; + } + break; + case "client_secret": + if(es.getValue().length==1) { + tr.setClientSecret(es.getValue()[0]); + data = true; + } + break; + case "username": + if(es.getValue().length==1) { + tr.setUsername(es.getValue()[0]); + data = true; + } + break; + case "password": + if(es.getValue().length==1) { + tr.setPassword(es.getValue()[0]); + data = true; + } + break; + case "scope": + if(es.getValue().length==1) { + tr.setScope(es.getValue()[0]); + data = true; + } + break; + case "grant_type": + if(es.getValue().length==1) { + tr.setGrantType(es.getValue()[0]); + data = true; + } + break; + case "refresh_token": + if(es.getValue().length==1) { + tr.setRefreshToken(es.getValue()[0]); + data = true; + } + break; + + } + } + return data?tr:null; + } + + + + /* (non-Javadoc) + * @see org.onap.aaf.auth.oauth.mapper.Mapper#credsFromReq(javax.servlet.http.HttpServletRequest) + */ + @Override + public OCreds credsFromReq(TokenRequest tokReq) { + return new OCreds(tokReq.getClientId(),tokReq.getClientSecret(), + tokReq.getUsername(),tokReq.getPassword()); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.oauth.mapper.Mapper#tokenReq(java.lang.Object) + */ + @Override + public Data clientTokenReq(TokenRequest tokReq, Holder hgt) { + OAuthTokenDAO.Data tdd = new OAuthTokenDAO.Data(); + tdd.client_id = tokReq.getClientId(); + tdd.user = tokReq.getUsername(); + if(tokReq.getRefreshToken()!=null) { + tdd.refresh=tokReq.getRefreshToken(); + } + + for(GRANT_TYPE ttt : GRANT_TYPE.values()) { + if(ttt.name().equals(tokReq.getGrantType())) { + hgt.set(ttt); + break; + } + } + + switch(hgt.get()) { + case client_credentials: + case password: + case refresh_token: + tdd.type = CLIENT_TYPE.confidential.ordinal(); + break; + default: + tdd.type = CLIENT_TYPE.unknown.ordinal(); + break; + } + String scopes=tokReq.getScope(); + if(scopes!=null) { + Set ss = tdd.scopes(true); + for(String s: Split.split(' ', tokReq.getScope())) { + ss.add(s); + } + } + + tdd.state = tokReq.getState(); + return tdd; + } + + @Override + public Result tokenFromData(Result rd) { + if(rd.notOK()) { + return Result.err(rd); + } + Data d = rd.value; + Token token = new Token(); + if(OAuthService.TOKEN_TYPE.values().length>d.type) { + token.setTokenType(OAuthService.TOKEN_TYPE.values()[d.type].name()); + } else { + token.setTokenType("Invalid"); + } + token.setAccessToken(d.id); + token.setRefreshToken(d.refresh); + token.setExpiresIn((int)(d.exp_sec-(System.currentTimeMillis())/1000)); + token.setScope(getScopes(d.scopes(false))); + token.setState(d.state); + return Result.ok(token); + } + + + + /* (non-Javadoc) + * @see org.onap.aaf.auth.oauth.mapper.Mapper#fromPrincipal(org.onap.aaf.cadi.oauth.OAuth2Principal) + */ + @Override + public Introspect fromPrincipal(OAuth2Principal p) { + return p.tokenPerm().getIntrospect(); + } } \ No newline at end of file diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect.java index bf558799..27f40ecf 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect.java @@ -25,5 +25,5 @@ import org.onap.aaf.auth.dao.cass.OAuthTokenDAO; import org.onap.aaf.auth.layer.Result; public interface MapperIntrospect { - public Result introspect(Result rs); + public Result introspect(Result rs); } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java index 00a94fdf..ac015c81 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java @@ -31,44 +31,44 @@ import aafoauth.v2_0.Introspect; public class MapperIntrospect1_0 implements MapperIntrospect { - public Result introspect(Result rs) { - if(rs.isOKhasData()) { - Data data = rs.value; - Introspect ti = new Introspect(); - ti.setAccessToken(data.id); - ti.setActive(data.active); - ti.setClientId(data.client_id); - for(CLIENT_TYPE ct : CLIENT_TYPE.values()) { - if(data.type==ct.ordinal()) { - ti.setClientType(ct.name()); - break; - } - } - if(ti.getClientType()==null) { - ti.setClientType(CLIENT_TYPE.unknown.name()); - } - ti.setActive(data.active); - ti.setScope(getScopes(data.scopes(false))); - ti.setContent(data.content); - ti.setUsername(data.user); - ti.setExp(data.exp_sec); // want seconds from Jan 1, 1970 - return Result.ok(ti); - } - return Result.err(rs); - } - - protected static String getScopes(Set scopes) { - StringBuilder sb = new StringBuilder(); - boolean start = true; - for(String s : scopes) { - if(start) { - start = false; - } else { - sb.append(' '); - } - sb.append(s); - } - return sb.toString(); - } + public Result introspect(Result rs) { + if(rs.isOKhasData()) { + Data data = rs.value; + Introspect ti = new Introspect(); + ti.setAccessToken(data.id); + ti.setActive(data.active); + ti.setClientId(data.client_id); + for(CLIENT_TYPE ct : CLIENT_TYPE.values()) { + if(data.type==ct.ordinal()) { + ti.setClientType(ct.name()); + break; + } + } + if(ti.getClientType()==null) { + ti.setClientType(CLIENT_TYPE.unknown.name()); + } + ti.setActive(data.active); + ti.setScope(getScopes(data.scopes(false))); + ti.setContent(data.content); + ti.setUsername(data.user); + ti.setExp(data.exp_sec); // want seconds from Jan 1, 1970 + return Result.ok(ti); + } + return Result.err(rs); + } + + protected static String getScopes(Set scopes) { + StringBuilder sb = new StringBuilder(); + boolean start = true; + for(String s : scopes) { + if(start) { + start = false; + } else { + sb.append(' '); + } + sb.append(s); + } + return sb.toString(); + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoader.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoader.java index bf04472b..51120870 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoader.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoader.java @@ -29,6 +29,6 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.misc.env.APIException; public interface JSONPermLoader { - public Result loadJSONPerms(AuthzTrans trans, String user, Set scopes) throws APIException, CadiException; + public Result loadJSONPerms(AuthzTrans trans, String user, Set scopes) throws APIException, CadiException; } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java index f4400869..886b06c5 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java @@ -38,82 +38,82 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.TimeTaken; public class JSONPermLoaderFactory { - /** - * Load JSON Perms from AAF Service (Remotely) - * @param aafcon - * @param timeout - * @return - */ - public static JSONPermLoader remote(final AAFCon aafcon, final int timeout) { - return new JSONPermLoader() { - public Result loadJSONPerms(AuthzTrans trans, String user, Set scopes) throws APIException, CadiException { - Rcli c = aafcon.clientAs(Config.AAF_DEFAULT_VERSION,trans.getUserPrincipal()); - StringBuilder pathinfo = new StringBuilder("/authz/perms/user/"); - pathinfo.append(user); - pathinfo.append("?scopes="); - boolean first = true; - for(String s : scopes) { - if(first) { - first = false; - } else { - pathinfo.append(':'); - } - pathinfo.append(s); - } - TimeTaken tt = trans.start("Call AAF Service", Env.REMOTE); - try { - Future fs = c.read(pathinfo.toString(), "application/Perms+json;charset=utf-8;version=2.0"); - if(fs.get(timeout)) { - return Result.ok(fs.body()); - } else if(fs.code()==404) { - return Result.err(Result.ERR_NotFound,fs.body()); - } else { - return Result.err(Result.ERR_Backend,"Error accessing AAF %s: %s",Integer.toString(fs.code()),fs.body()); - } - } finally { - tt.done(); - } - } - }; - } - public static JSONPermLoader direct(final Question question) { - return new JSONPermLoader() { - public Result loadJSONPerms(AuthzTrans trans, String user, Set scopes) throws APIException, CadiException { - TimeTaken tt = trans.start("Cached DB Perm lookup", Env.SUB); - Result> pd; - try { - pd = question.getPermsByUser(trans, user, false); - } finally { - tt.done(); - } - if(pd.notOK()) { - return Result.err(pd); - } - // Since we know it is - StringBuilder sb = new StringBuilder("{\"perm\":["); - boolean first = true; - for(PermDAO.Data d : pd.value) { - if(scopes.contains(d.ns)) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append("{\"ns\":\""); - sb.append(d.ns); - sb.append("\",\"type\":\""); - sb.append(d.type); - sb.append("\",\"instance\":\""); - sb.append(d.instance); - sb.append("\",\"action\":\""); - sb.append(d.action); - sb.append("\"}"); - } - } - sb.append("]}"); - return Result.ok(sb.toString()); - } - }; - } + /** + * Load JSON Perms from AAF Service (Remotely) + * @param aafcon + * @param timeout + * @return + */ + public static JSONPermLoader remote(final AAFCon aafcon, final int timeout) { + return new JSONPermLoader() { + public Result loadJSONPerms(AuthzTrans trans, String user, Set scopes) throws APIException, CadiException { + Rcli c = aafcon.clientAs(Config.AAF_DEFAULT_VERSION,trans.getUserPrincipal()); + StringBuilder pathinfo = new StringBuilder("/authz/perms/user/"); + pathinfo.append(user); + pathinfo.append("?scopes="); + boolean first = true; + for(String s : scopes) { + if(first) { + first = false; + } else { + pathinfo.append(':'); + } + pathinfo.append(s); + } + TimeTaken tt = trans.start("Call AAF Service", Env.REMOTE); + try { + Future fs = c.read(pathinfo.toString(), "application/Perms+json;charset=utf-8;version=2.0"); + if(fs.get(timeout)) { + return Result.ok(fs.body()); + } else if(fs.code()==404) { + return Result.err(Result.ERR_NotFound,fs.body()); + } else { + return Result.err(Result.ERR_Backend,"Error accessing AAF %s: %s",Integer.toString(fs.code()),fs.body()); + } + } finally { + tt.done(); + } + } + }; + } + public static JSONPermLoader direct(final Question question) { + return new JSONPermLoader() { + public Result loadJSONPerms(AuthzTrans trans, String user, Set scopes) throws APIException, CadiException { + TimeTaken tt = trans.start("Cached DB Perm lookup", Env.SUB); + Result> pd; + try { + pd = question.getPermsByUser(trans, user, false); + } finally { + tt.done(); + } + if(pd.notOK()) { + return Result.err(pd); + } + // Since we know it is + StringBuilder sb = new StringBuilder("{\"perm\":["); + boolean first = true; + for(PermDAO.Data d : pd.value) { + if(scopes.contains(d.ns)) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append("{\"ns\":\""); + sb.append(d.ns); + sb.append("\",\"type\":\""); + sb.append(d.type); + sb.append("\",\"instance\":\""); + sb.append(d.instance); + sb.append("\",\"action\":\""); + sb.append(d.action); + sb.append("\"}"); + } + } + sb.append("]}"); + return Result.ok(sb.toString()); + } + }; + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java index 0064e224..1d926a74 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java @@ -54,248 +54,248 @@ import org.onap.aaf.misc.env.APIException; import aafoauth.v2_0.Introspect; public class OAuthService { - - private static final int TOK_EXP = 60*60*1000; // 1 hour, millis. + + private static final int TOK_EXP = 60*60*1000; // 1 hour, millis. - public enum TOKEN_TYPE {unknown,bearer,refresh} - public enum GRANT_TYPE {unknown,password,client_credentials,refresh_token}; - public enum CLIENT_TYPE {unknown,confidential}; - - // Additional Expires - private final DAO[] daos; - public final OAuthTokenDAO tokenDAO; - private final DirectAAFUserPass directUserPass; - private final TokenClientFactory tcf; - private TokenClient altIntrospectClient; - private String altDomain; - private final JSONPermLoader permLoader; + public enum TOKEN_TYPE {unknown,bearer,refresh} + public enum GRANT_TYPE {unknown,password,client_credentials,refresh_token}; + public enum CLIENT_TYPE {unknown,confidential}; + + // Additional Expires + private final DAO[] daos; + public final OAuthTokenDAO tokenDAO; + private final DirectAAFUserPass directUserPass; + private final TokenClientFactory tcf; + private TokenClient altIntrospectClient; + private String altDomain; + private final JSONPermLoader permLoader; - // If we add more CAs, may want to parameterize + // If we add more CAs, may want to parameterize - @SuppressWarnings("unchecked") - public OAuthService(final Access access, final AuthzTrans trans, final Question q) throws APIException, IOException { - permLoader = JSONPermLoaderFactory.direct(q); - tokenDAO = new OAuthTokenDAO(trans, q.historyDAO); - daos =(DAO[]) new DAO[] { - tokenDAO - }; - try { - String alt_url = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL,null); - if(alt_url!=null) { - tcf = TokenClientFactory.instance(access); - String[] split = Split.split(',', alt_url); - int timeout = split.length>1?Integer.parseInt(split[1]):3000; - altIntrospectClient = tcf.newClient(split[0], timeout); - altIntrospectClient.client_creds(access.getProperty(Config.AAF_ALT_CLIENT_ID,null), - access.getProperty(Config.AAF_ALT_CLIENT_SECRET,null)); - altDomain = '@'+access.getProperty(Config.AAF_ALT_OAUTH2_DOMAIN,null); - } else { - tcf = null; - } - directUserPass = new DirectAAFUserPass(trans.env(), q); - } catch (GeneralSecurityException | CadiException | LocatorException e) { - throw new APIException("Could not construct TokenClientFactory",e); - } - - } + @SuppressWarnings("unchecked") + public OAuthService(final Access access, final AuthzTrans trans, final Question q) throws APIException, IOException { + permLoader = JSONPermLoaderFactory.direct(q); + tokenDAO = new OAuthTokenDAO(trans, q.historyDAO); + daos =(DAO[]) new DAO[] { + tokenDAO + }; + try { + String alt_url = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL,null); + if(alt_url!=null) { + tcf = TokenClientFactory.instance(access); + String[] split = Split.split(',', alt_url); + int timeout = split.length>1?Integer.parseInt(split[1]):3000; + altIntrospectClient = tcf.newClient(split[0], timeout); + altIntrospectClient.client_creds(access.getProperty(Config.AAF_ALT_CLIENT_ID,null), + access.getProperty(Config.AAF_ALT_CLIENT_SECRET,null)); + altDomain = '@'+access.getProperty(Config.AAF_ALT_OAUTH2_DOMAIN,null); + } else { + tcf = null; + } + directUserPass = new DirectAAFUserPass(trans.env(), q); + } catch (GeneralSecurityException | CadiException | LocatorException e) { + throw new APIException("Could not construct TokenClientFactory",e); + } + + } - public Result validate(AuthzTrans trans, OCreds creds) { - if(directUserPass.validate(creds.username, Type.PASSWORD, creds.password, trans)) { - return Result.ok(); - } else { - return Result.err(Result.ERR_Security, "Invalid Credential for ",creds.username); - } - } + public Result validate(AuthzTrans trans, OCreds creds) { + if(directUserPass.validate(creds.username, Type.PASSWORD, creds.password, trans)) { + return Result.ok(); + } else { + return Result.err(Result.ERR_Security, "Invalid Credential for ",creds.username); + } + } - public Result createToken(AuthzTrans trans, HttpServletRequest req, OAuthTokenDAO.Data odd, Holder hgt) { - switch(hgt.get()) { - case client_credentials: - case password: - return createBearerToken(trans, odd); - case refresh_token: - return refreshBearerToken(trans, odd); - default: - return Result.err(Result.ERR_BadData, "Unknown Grant Type"); - } - } - - private Result createBearerToken(AuthzTrans trans, OAuthTokenDAO.Data odd) { - if(odd.user==null) { - odd.user = trans.user(); - } - odd.id = AAFToken.toToken(UUID.randomUUID()); - odd.refresh = AAFToken.toToken(UUID.randomUUID()); - odd.active = true; - long exp; - odd.expires = new Date(exp=(System.currentTimeMillis()+TOK_EXP)); - odd.exp_sec = exp/1000; - odd.req_ip = trans.ip(); - - try { - Result rd = loadToken(trans, odd); - if(rd.notOK()) { - return rd; - } - } catch (APIException | CadiException e) { - return Result.err(e); - } - return tokenDAO.create(trans, odd); - } - - private Result loadToken(AuthzTrans trans, Data odd) throws APIException, CadiException { - Result rs = permLoader.loadJSONPerms(trans,odd.user,odd.scopes(false)); - if(rs.isOK()) { - odd.content = rs.value; - odd.type = TOKEN_TYPE.bearer.ordinal(); - return Result.ok(odd); - } else if(rs.status == Result.ERR_NotFound || rs.status==Status.ERR_UserRoleNotFound) { - odd.type = TOKEN_TYPE.bearer.ordinal(); - return Result.ok(odd); - } else { - return Result.err(Result.ERR_Backend,"Error accessing AAF Info: %s",rs.errorString()); - } - } - - + public Result createToken(AuthzTrans trans, HttpServletRequest req, OAuthTokenDAO.Data odd, Holder hgt) { + switch(hgt.get()) { + case client_credentials: + case password: + return createBearerToken(trans, odd); + case refresh_token: + return refreshBearerToken(trans, odd); + default: + return Result.err(Result.ERR_BadData, "Unknown Grant Type"); + } + } + + private Result createBearerToken(AuthzTrans trans, OAuthTokenDAO.Data odd) { + if(odd.user==null) { + odd.user = trans.user(); + } + odd.id = AAFToken.toToken(UUID.randomUUID()); + odd.refresh = AAFToken.toToken(UUID.randomUUID()); + odd.active = true; + long exp; + odd.expires = new Date(exp=(System.currentTimeMillis()+TOK_EXP)); + odd.exp_sec = exp/1000; + odd.req_ip = trans.ip(); + + try { + Result rd = loadToken(trans, odd); + if(rd.notOK()) { + return rd; + } + } catch (APIException | CadiException e) { + return Result.err(e); + } + return tokenDAO.create(trans, odd); + } + + private Result loadToken(AuthzTrans trans, Data odd) throws APIException, CadiException { + Result rs = permLoader.loadJSONPerms(trans,odd.user,odd.scopes(false)); + if(rs.isOK()) { + odd.content = rs.value; + odd.type = TOKEN_TYPE.bearer.ordinal(); + return Result.ok(odd); + } else if(rs.status == Result.ERR_NotFound || rs.status==Status.ERR_UserRoleNotFound) { + odd.type = TOKEN_TYPE.bearer.ordinal(); + return Result.ok(odd); + } else { + return Result.err(Result.ERR_Backend,"Error accessing AAF Info: %s",rs.errorString()); + } + } + + - private Result refreshBearerToken(AuthzTrans trans, Data odd) { - Result> rld = tokenDAO.readByUser(trans, trans.user()); - if(rld.notOK()) { - return Result.err(rld); - } - if(rld.isEmpty()) { - return Result.err(Result.ERR_NotFound,"Data not Found for %1 %2",trans.user(),odd.refresh==null?"":odd.refresh.toString()); - } - Data token = null; - for(Data d : rld.value) { - if(d.refresh.equals(odd.refresh)) { - token = d; - boolean scopesNE = false; - Set scopes = odd.scopes(false); - if(scopes.size()>0) { // only check if Scopes listed, RFC 6749, Section 6 - if(scopesNE=!(scopes.size() == d.scopes(false).size())) { - for(String s : odd.scopes(false)) { - if(!d.scopes(false).contains(s)) { - scopesNE=true; - break; - } - } - } - if(scopesNE) { - return Result.err(Result.ERR_BadData,"Requested Scopes do not match existing Token"); - } - } - break; - } - } - - if(token==null) { - trans.audit().printf("Duplicate Refresh Token (%s) attempted for %s. Possible Replay Attack",odd.refresh.toString(),trans.user()); - return Result.err(Result.ERR_Security,"Invalid Refresh Token"); - } else { - // Got the Result - Data deleteMe = new Data(); - deleteMe.id = token.id; - token.id = AAFToken.toToken(UUID.randomUUID()); - token.client_id = trans.user(); - token.refresh = AAFToken.toToken(UUID.randomUUID()); - long exp; - token.expires = new Date(exp=(System.currentTimeMillis()+TOK_EXP)); - token.exp_sec = exp/1000; - token.req_ip = trans.ip(); - Result rd = tokenDAO.create(trans, token); - if(rd.notOK()) { - return Result.err(rd); - } - Result rv = tokenDAO.delete(trans, deleteMe,false); - if(rv.notOK()) { - trans.error().log("Unable to delete token", token); - } - } - return Result.ok(token); - } + private Result refreshBearerToken(AuthzTrans trans, Data odd) { + Result> rld = tokenDAO.readByUser(trans, trans.user()); + if(rld.notOK()) { + return Result.err(rld); + } + if(rld.isEmpty()) { + return Result.err(Result.ERR_NotFound,"Data not Found for %1 %2",trans.user(),odd.refresh==null?"":odd.refresh.toString()); + } + Data token = null; + for(Data d : rld.value) { + if(d.refresh.equals(odd.refresh)) { + token = d; + boolean scopesNE = false; + Set scopes = odd.scopes(false); + if(scopes.size()>0) { // only check if Scopes listed, RFC 6749, Section 6 + if(scopesNE=!(scopes.size() == d.scopes(false).size())) { + for(String s : odd.scopes(false)) { + if(!d.scopes(false).contains(s)) { + scopesNE=true; + break; + } + } + } + if(scopesNE) { + return Result.err(Result.ERR_BadData,"Requested Scopes do not match existing Token"); + } + } + break; + } + } + + if(token==null) { + trans.audit().printf("Duplicate Refresh Token (%s) attempted for %s. Possible Replay Attack",odd.refresh.toString(),trans.user()); + return Result.err(Result.ERR_Security,"Invalid Refresh Token"); + } else { + // Got the Result + Data deleteMe = new Data(); + deleteMe.id = token.id; + token.id = AAFToken.toToken(UUID.randomUUID()); + token.client_id = trans.user(); + token.refresh = AAFToken.toToken(UUID.randomUUID()); + long exp; + token.expires = new Date(exp=(System.currentTimeMillis()+TOK_EXP)); + token.exp_sec = exp/1000; + token.req_ip = trans.ip(); + Result rd = tokenDAO.create(trans, token); + if(rd.notOK()) { + return Result.err(rd); + } + Result rv = tokenDAO.delete(trans, deleteMe,false); + if(rv.notOK()) { + trans.error().log("Unable to delete token", token); + } + } + return Result.ok(token); + } - public Result introspect(AuthzTrans trans, String token) { - Result> rld; - try { - UUID uuid = AAFToken.fromToken(token); - if(uuid==null) { // not an AAF Token - // Attempt to get Alternative Token - if(altIntrospectClient!=null) { - org.onap.aaf.cadi.client.Result rai = altIntrospectClient.introspect(token); - if(rai.isOK()) { - Introspect in = rai.value; - if(in.getExp()==null) { - trans.audit().printf("Alt OAuth sent back inactive, empty token: requesting_id,%s,access_token=%s,ip=%s\n",trans.user(),token,trans.ip()); - } - long expires = in.getExp()*1000; - if(in.isActive() && expires>System.currentTimeMillis()) { - // We have a good Token, modify to be Fully Qualified - String fqid = in.getUsername()+altDomain; - // read contents - rld = tokenDAO.read(trans, token); - if(rld.isOKhasData()) { - Data td = rld.value.get(0); - in.setContent(td.content); - } else { - Data td = new Data(); - td.id = token; - td.client_id = in.getClientId(); - td.user = fqid; - td.active=true; - td.type = TOKEN_TYPE.bearer.ordinal(); - td.expires = new Date(expires); - td.exp_sec = in.getExp(); - Set scopes = td.scopes(true); - if(in.getScope()!=null) { - for(String s : Split.split(' ', in.getScope())) { - scopes.add(s); - } - } - // td.state = nothing to add at this point - td.req_ip = trans.ip(); - trans.checkpoint(td.user + ':' + td.client_id + ", " + td.id); - return loadToken(trans, td); - } - } -// System.out.println(rai.value.getClientId()); - } else { - trans.audit().printf("Alt OAuth rejects: requesting_id,%s,access_token=%s,ip=%s,code=%d,error=%s\n",trans.user(),token,trans.ip(),rai.code,rai.error); - } - } else { - trans.audit().printf("Bad Token: requesting_id,%s,access_token=%s,ip=%s\n",trans.user(),token,trans.ip()); - } - return Result.err(Result.ERR_Denied,"Bad Token"); - } else { - return dbIntrospect(trans,token); - } - } catch (CadiException | APIException | LocatorException e) { - return Result.err(e); - } - } + public Result introspect(AuthzTrans trans, String token) { + Result> rld; + try { + UUID uuid = AAFToken.fromToken(token); + if(uuid==null) { // not an AAF Token + // Attempt to get Alternative Token + if(altIntrospectClient!=null) { + org.onap.aaf.cadi.client.Result rai = altIntrospectClient.introspect(token); + if(rai.isOK()) { + Introspect in = rai.value; + if(in.getExp()==null) { + trans.audit().printf("Alt OAuth sent back inactive, empty token: requesting_id,%s,access_token=%s,ip=%s\n",trans.user(),token,trans.ip()); + } + long expires = in.getExp()*1000; + if(in.isActive() && expires>System.currentTimeMillis()) { + // We have a good Token, modify to be Fully Qualified + String fqid = in.getUsername()+altDomain; + // read contents + rld = tokenDAO.read(trans, token); + if(rld.isOKhasData()) { + Data td = rld.value.get(0); + in.setContent(td.content); + } else { + Data td = new Data(); + td.id = token; + td.client_id = in.getClientId(); + td.user = fqid; + td.active=true; + td.type = TOKEN_TYPE.bearer.ordinal(); + td.expires = new Date(expires); + td.exp_sec = in.getExp(); + Set scopes = td.scopes(true); + if(in.getScope()!=null) { + for(String s : Split.split(' ', in.getScope())) { + scopes.add(s); + } + } + // td.state = nothing to add at this point + td.req_ip = trans.ip(); + trans.checkpoint(td.user + ':' + td.client_id + ", " + td.id); + return loadToken(trans, td); + } + } +// System.out.println(rai.value.getClientId()); + } else { + trans.audit().printf("Alt OAuth rejects: requesting_id,%s,access_token=%s,ip=%s,code=%d,error=%s\n",trans.user(),token,trans.ip(),rai.code,rai.error); + } + } else { + trans.audit().printf("Bad Token: requesting_id,%s,access_token=%s,ip=%s\n",trans.user(),token,trans.ip()); + } + return Result.err(Result.ERR_Denied,"Bad Token"); + } else { + return dbIntrospect(trans,token); + } + } catch (CadiException | APIException | LocatorException e) { + return Result.err(e); + } + } - public Result dbIntrospect(final AuthzTrans trans, final String token) { - Result> rld = tokenDAO.read(trans, token); - if(rld.notOKorIsEmpty()) { - return Result.err(rld); - } - OAuthTokenDAO.Data odd = rld.value.get(0); - trans.checkpoint(odd.user + ':' + odd.client_id + ", " + odd.id); - if(odd.active) { - if(odd.expires.before(trans.now())) { - return Result.err(Result.ERR_Policy,"Token %1 has expired",token); - } - return Result.ok(rld.value.get(0)); // ok keyed on id/token. - } else { - return Result.err(Result.ERR_Denied,"Token %1 is inactive",token); - } - } + public Result dbIntrospect(final AuthzTrans trans, final String token) { + Result> rld = tokenDAO.read(trans, token); + if(rld.notOKorIsEmpty()) { + return Result.err(rld); + } + OAuthTokenDAO.Data odd = rld.value.get(0); + trans.checkpoint(odd.user + ':' + odd.client_id + ", " + odd.id); + if(odd.active) { + if(odd.expires.before(trans.now())) { + return Result.err(Result.ERR_Policy,"Token %1 has expired",token); + } + return Result.ok(rld.value.get(0)); // ok keyed on id/token. + } else { + return Result.err(Result.ERR_Denied,"Token %1 is inactive",token); + } + } - public void close() { - for(DAO dao : daos) { - dao.close(NullTrans.singleton()); - } - } + public void close() { + for(DAO dao : daos) { + dao.close(NullTrans.singleton()); + } + } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OCreds.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OCreds.java index becb746a..af15d4c2 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OCreds.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OCreds.java @@ -22,12 +22,12 @@ package org.onap.aaf.auth.oauth.service; public class OCreds { - public final String client_id, username; - public final byte[] client_secret, password; - public OCreds(String client_id, String client_secret, String username, String password) { - this.client_id = client_id; - this.client_secret = client_secret==null?null:client_secret.getBytes(); - this.username = username; - this.password = password==null?null:password.getBytes(); - } + public final String client_id, username; + public final byte[] client_secret, password; + public OCreds(String client_id, String client_secret, String username, String password) { + this.client_id = client_id; + this.client_secret = client_secret==null?null:client_secret.getBytes(); + this.username = username; + this.password = password==null?null:password.getBytes(); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_DirectOAuthTAF.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_DirectOAuthTAF.java index ed80b10c..61608a17 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_DirectOAuthTAF.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_DirectOAuthTAF.java @@ -50,78 +50,78 @@ import aafoauth.v2_0.Introspect; public class JU_DirectOAuthTAF { - @Mock - private AuthzEnv env; - - @Mock - private PropAccess access; - - private Properties props = new Properties(); - - @Mock - private HttpServletRequest req; - - private Map parameterMap; - @Mock - private DirectIntrospect facade; - @Mock - private AuthzTrans trans; - @Mock - private Result ri; - - @Before - public void setup() { - initMocks(this); - parameterMap = new TreeMap(); - - } - - @Test - public void testValidateWithoutSecret() throws APIException, CadiException { - parameterMap.put("client_id", new String[] { "Client1" }); - // parameterMap.put("client_secret", new String[] { "Secret1" }); - parameterMap.put("username", new String[] { "User1" }); - parameterMap.put("password", new String[] { "Pass1" }); - parameterMap.put("token", new String[] { "token1" }); - when(env.access()).thenReturn(access); - when(access.getProperties()).thenReturn(props); - when(req.getContentType()).thenReturn("application/x-www-form-urlencoded"); - when(req.getParameterMap()).thenReturn(parameterMap); - - DirectOAuthTAF oAuthTaf = new DirectOAuthTAF(env, null, null); - - TafResp validate = oAuthTaf.validate(null, req, null); - - assertNotNull(validate); - assertEquals(validate.getAccess(), access); - assertEquals(validate.desc(), "client_id and client_secret required"); - } - - @Test - public void testValidateWithSecret() throws APIException, CadiException { - parameterMap.put("client_id", new String[] { "Client1" }); - parameterMap.put("client_secret", new String[] { "Secret1" }); - parameterMap.put("username", new String[] { "User1" }); - parameterMap.put("password", new String[] { "Pass1" }); - parameterMap.put("token", new String[] { "token1" }); - - when(env.access()).thenReturn(access); - when(access.getProperties()).thenReturn(props); - when(req.getContentType()).thenReturn("application/x-www-form-urlencoded"); - when(req.getParameterMap()).thenReturn(parameterMap); - when(req.getAttribute(TransFilter.TRANS_TAG)).thenReturn(trans); - when(facade.mappedIntrospect(trans, "token1")).thenReturn(ri); - - DirectOAuthTAF oAuthTaf = new DirectOAuthTAF(env, null, facade); - - TafResp validate = oAuthTaf.validate(null, req, null); - - assertNotNull(validate); - assertEquals(validate.getAccess(), access); - assertEquals(validate.desc(), ri.errorString()); - - assertNull(oAuthTaf.revalidate(null, null)); - assertNotNull(oAuthTaf.directUserPass()); - } + @Mock + private AuthzEnv env; + + @Mock + private PropAccess access; + + private Properties props = new Properties(); + + @Mock + private HttpServletRequest req; + + private Map parameterMap; + @Mock + private DirectIntrospect facade; + @Mock + private AuthzTrans trans; + @Mock + private Result ri; + + @Before + public void setup() { + initMocks(this); + parameterMap = new TreeMap(); + + } + + @Test + public void testValidateWithoutSecret() throws APIException, CadiException { + parameterMap.put("client_id", new String[] { "Client1" }); + // parameterMap.put("client_secret", new String[] { "Secret1" }); + parameterMap.put("username", new String[] { "User1" }); + parameterMap.put("password", new String[] { "Pass1" }); + parameterMap.put("token", new String[] { "token1" }); + when(env.access()).thenReturn(access); + when(access.getProperties()).thenReturn(props); + when(req.getContentType()).thenReturn("application/x-www-form-urlencoded"); + when(req.getParameterMap()).thenReturn(parameterMap); + + DirectOAuthTAF oAuthTaf = new DirectOAuthTAF(env, null, null); + + TafResp validate = oAuthTaf.validate(null, req, null); + + assertNotNull(validate); + assertEquals(validate.getAccess(), access); + assertEquals(validate.desc(), "client_id and client_secret required"); + } + + @Test + public void testValidateWithSecret() throws APIException, CadiException { + parameterMap.put("client_id", new String[] { "Client1" }); + parameterMap.put("client_secret", new String[] { "Secret1" }); + parameterMap.put("username", new String[] { "User1" }); + parameterMap.put("password", new String[] { "Pass1" }); + parameterMap.put("token", new String[] { "token1" }); + + when(env.access()).thenReturn(access); + when(access.getProperties()).thenReturn(props); + when(req.getContentType()).thenReturn("application/x-www-form-urlencoded"); + when(req.getParameterMap()).thenReturn(parameterMap); + when(req.getAttribute(TransFilter.TRANS_TAG)).thenReturn(trans); + when(facade.mappedIntrospect(trans, "token1")).thenReturn(ri); + + DirectOAuthTAF oAuthTaf = new DirectOAuthTAF(env, null, facade); + + TafResp validate = oAuthTaf.validate(null, req, null); + + assertNotNull(validate); + assertEquals(validate.getAccess(), access); + assertEquals(validate.desc(), ri.errorString()); + + assertNull(oAuthTaf.revalidate(null, null)); + assertNotNull(oAuthTaf.directUserPass()); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OACodeTest.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OACodeTest.java index 9ae7a012..22958736 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OACodeTest.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OACodeTest.java @@ -39,33 +39,33 @@ import aafoauth.v2_0.Introspect; public class JU_OACodeTest { - @Mock - private OAFacade facade; + @Mock + private OAFacade facade; - @Mock - private OAFacade facade1; + @Mock + private OAFacade facade1; - @Before - public void setup() { - initMocks(this); - } + @Before + public void setup() { + initMocks(this); + } - @Test - public void testOACodeDefaultMethod() throws Exception { - OACode code = new OACode(facade, "Original Description", true, "role1") { + @Test + public void testOACodeDefaultMethod() throws Exception { + OACode code = new OACode(facade, "Original Description", true, "role1") { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - // Blank implementation to test abstract OACode class. - } - }; + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + // Blank implementation to test abstract OACode class. + } + }; - OACode clone = code.clone(facade1, false); + OACode clone = code.clone(facade1, false); - assertNotSame(code, clone); + assertNotSame(code, clone); - assertTrue(code.useJSON); - assertFalse(clone.useJSON); + assertTrue(code.useJSON); + assertFalse(clone.useJSON); - } + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FilterTest.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FilterTest.java index 56dc669d..56eba95b 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FilterTest.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FilterTest.java @@ -38,51 +38,51 @@ import org.onap.aaf.cadi.principal.BearerPrincipal; public class JU_OAuth2FilterTest { - @Mock - private HttpServletRequest request; - @Mock - private FilterChain chain; - @Mock - private BearerPrincipal principal; - - @Before - public void setup() { - initMocks(this); - } - - @Test - public void testDoFilterWithContentType() throws IOException, ServletException { - when(request.getContentType()).thenReturn("application/x-www-form-urlencoded"); - - OAuth2Filter filter = new OAuth2Filter(); - filter.doFilter(request, null, chain); - - verify(chain, only()).doFilter(request, null); - } - - @Test - public void testDoFilter() throws IOException, ServletException { - when(request.getContentType()).thenReturn("somethingElse"); - when(request.getUserPrincipal()).thenReturn(principal); - when(request.getHeader("Authorization")).thenReturn("Bearer 1;Bearer2"); - - OAuth2Filter filter = new OAuth2Filter(); - filter.init(null); - filter.destroy(); - filter.doFilter(request, null, chain); - - verify(chain, only()).doFilter(request, null); - verify(principal, only()).setBearer("1"); - } - - @Test - public void testDoFilterWithoutBearerPrincipal() throws IOException, ServletException { - when(request.getContentType()).thenReturn("somethingElse"); - when(request.getHeader("Authorization")).thenReturn("Bearer 1;Bearer2"); - - OAuth2Filter filter = new OAuth2Filter(); - filter.doFilter(request, null, chain); - - verify(chain, only()).doFilter(request, null); - } + @Mock + private HttpServletRequest request; + @Mock + private FilterChain chain; + @Mock + private BearerPrincipal principal; + + @Before + public void setup() { + initMocks(this); + } + + @Test + public void testDoFilterWithContentType() throws IOException, ServletException { + when(request.getContentType()).thenReturn("application/x-www-form-urlencoded"); + + OAuth2Filter filter = new OAuth2Filter(); + filter.doFilter(request, null, chain); + + verify(chain, only()).doFilter(request, null); + } + + @Test + public void testDoFilter() throws IOException, ServletException { + when(request.getContentType()).thenReturn("somethingElse"); + when(request.getUserPrincipal()).thenReturn(principal); + when(request.getHeader("Authorization")).thenReturn("Bearer 1;Bearer2"); + + OAuth2Filter filter = new OAuth2Filter(); + filter.init(null); + filter.destroy(); + filter.doFilter(request, null, chain); + + verify(chain, only()).doFilter(request, null); + verify(principal, only()).setBearer("1"); + } + + @Test + public void testDoFilterWithoutBearerPrincipal() throws IOException, ServletException { + when(request.getContentType()).thenReturn("somethingElse"); + when(request.getHeader("Authorization")).thenReturn("Bearer 1;Bearer2"); + + OAuth2Filter filter = new OAuth2Filter(); + filter.doFilter(request, null, chain); + + verify(chain, only()).doFilter(request, null); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FormHttpTafRespTest.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FormHttpTafRespTest.java index 7a332fa3..8913cceb 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FormHttpTafRespTest.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/JU_OAuth2FormHttpTafRespTest.java @@ -37,28 +37,28 @@ import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_OAuth2FormHttpTafRespTest { - @Mock - private HttpServletResponse resp; + @Mock + private HttpServletResponse resp; - @Before - public void setup() { - initMocks(this); - } + @Before + public void setup() { + initMocks(this); + } - @Test - public void testAuthenticated() throws IOException { - OAuth2FormHttpTafResp oAuth2 = new OAuth2FormHttpTafResp(null, null, null, null, resp); + @Test + public void testAuthenticated() throws IOException { + OAuth2FormHttpTafResp oAuth2 = new OAuth2FormHttpTafResp(null, null, null, null, resp); - assertEquals(oAuth2.authenticate(), RESP.HTTP_REDIRECT_INVOKED); + assertEquals(oAuth2.authenticate(), RESP.HTTP_REDIRECT_INVOKED); - verify(resp, only()).setStatus(401); - } + verify(resp, only()).setStatus(401); + } - @Test - public void testIsAuthenticated() throws IOException { - OAuth2FormHttpTafResp oAuth2 = new OAuth2FormHttpTafResp(null, null, null, RESP.HAS_PROCESSED, null, false); + @Test + public void testIsAuthenticated() throws IOException { + OAuth2FormHttpTafResp oAuth2 = new OAuth2FormHttpTafResp(null, null, null, RESP.HAS_PROCESSED, null, false); - assertEquals(oAuth2.isAuthenticated(), RESP.HAS_PROCESSED); - assertFalse(oAuth2.isFailedAttempt()); - } + assertEquals(oAuth2.isAuthenticated(), RESP.HAS_PROCESSED); + assertFalse(oAuth2.isFailedAttempt()); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_DirectOAFacadeImplTest.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_DirectOAFacadeImplTest.java index 1393f291..6e6722f9 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_DirectOAFacadeImplTest.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_DirectOAFacadeImplTest.java @@ -27,10 +27,10 @@ import org.junit.Test; public class JU_DirectOAFacadeImplTest { - @Test - public void test() { - DirectOAFacadeImpl oAFacade = new DirectOAFacadeImpl(); - assertNotNull(oAFacade); - } + @Test + public void test() { + DirectOAFacadeImpl oAFacade = new DirectOAFacadeImpl(); + assertNotNull(oAFacade); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_OAFacadeFactory.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_OAFacadeFactory.java index bf9cbdd6..3c7b2970 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_OAFacadeFactory.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/facade/JU_OAFacadeFactory.java @@ -37,51 +37,51 @@ import aafoauth.v2_0.Introspect; public class JU_OAFacadeFactory { - @Mock - private OAuthService service; + @Mock + private OAuthService service; - private String token; + private String token; - private AuthzTrans trans; - @Mock - private Result rs; + private AuthzTrans trans; + @Mock + private Result rs; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void testStatusNotOk() throws APIException { - when(service.introspect(trans, token)).thenReturn(rs); - when(rs.notOK()).thenReturn(true); + @Test + public void testStatusNotOk() throws APIException { + when(service.introspect(trans, token)).thenReturn(rs); + when(rs.notOK()).thenReturn(true); - DirectIntrospect direct = OAFacadeFactory.directV1_0(service); - Result rti = direct.mappedIntrospect(trans, token); + DirectIntrospect direct = OAFacadeFactory.directV1_0(service); + Result rti = direct.mappedIntrospect(trans, token); - assertEquals(rti.status, 0); - } + assertEquals(rti.status, 0); + } - @Test - public void testStatusOk() throws APIException { - when(service.introspect(trans, token)).thenReturn(rs); - when(rs.notOK()).thenReturn(false); + @Test + public void testStatusOk() throws APIException { + when(service.introspect(trans, token)).thenReturn(rs); + when(rs.notOK()).thenReturn(false); - DirectIntrospect directV1_0 = OAFacadeFactory.directV1_0(service); - Result rti = directV1_0.mappedIntrospect(trans, token); + DirectIntrospect directV1_0 = OAFacadeFactory.directV1_0(service); + Result rti = directV1_0.mappedIntrospect(trans, token); - assertEquals(rti.status, 0); - } + assertEquals(rti.status, 0); + } - @Test - public void testStatusOkWithResultSetEmpty() throws APIException { - when(service.introspect(trans, token)).thenReturn(rs); - when(rs.isEmpty()).thenReturn(true); - when(rs.notOK()).thenReturn(false); + @Test + public void testStatusOkWithResultSetEmpty() throws APIException { + when(service.introspect(trans, token)).thenReturn(rs); + when(rs.isEmpty()).thenReturn(true); + when(rs.notOK()).thenReturn(false); - DirectIntrospect directV1_0 = OAFacadeFactory.directV1_0(service); - Result rti = directV1_0.mappedIntrospect(trans, token); + DirectIntrospect directV1_0 = OAFacadeFactory.directV1_0(service); + Result rti = directV1_0.mappedIntrospect(trans, token); - assertEquals(rti.status, Result.ERR_NotFound); - } + assertEquals(rti.status, Result.ERR_NotFound); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_Mapper1_0Test.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_Mapper1_0Test.java index c872cb8e..3a0a40d9 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_Mapper1_0Test.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_Mapper1_0Test.java @@ -49,178 +49,178 @@ import aafoauth.v2_0.Token; import aafoauth.v2_0.TokenRequest; public class JU_Mapper1_0Test { - @Mock - private HttpServletRequest req; - - @Mock - private TokenRequest tokenRequest; - - @Mock - private Holder hgt; - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - private OAuth2Principal p; - - private Data data; - - @Before - public void setup() { - initMocks(this); - data = new Data(); - data.id = "id"; - } - - @Test - public void testMapper() { - Mapper mapper = new Mapper1_0(); - assertEquals(TokenRequest.class, mapper.getClass(API.TOKEN_REQ)); - assertEquals(Token.class, mapper.getClass(API.TOKEN)); - assertEquals(Introspect.class, mapper.getClass(API.INTROSPECT)); - assertEquals(Error.class, mapper.getClass(API.ERROR)); - assertEquals(Void.class, mapper.getClass(API.VOID)); - - assertTrue(mapper.newInstance(API.TOKEN_REQ) instanceof TokenRequest); - assertTrue(mapper.newInstance(API.TOKEN) instanceof Token); - assertTrue(mapper.newInstance(API.INTROSPECT) instanceof Introspect); - assertTrue(mapper.newInstance(API.ERROR) instanceof Error); - assertEquals(null, mapper.newInstance(API.VOID)); + @Mock + private HttpServletRequest req; + + @Mock + private TokenRequest tokenRequest; + + @Mock + private Holder hgt; + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private OAuth2Principal p; + + private Data data; + + @Before + public void setup() { + initMocks(this); + data = new Data(); + data.id = "id"; + } + + @Test + public void testMapper() { + Mapper mapper = new Mapper1_0(); + assertEquals(TokenRequest.class, mapper.getClass(API.TOKEN_REQ)); + assertEquals(Token.class, mapper.getClass(API.TOKEN)); + assertEquals(Introspect.class, mapper.getClass(API.INTROSPECT)); + assertEquals(Error.class, mapper.getClass(API.ERROR)); + assertEquals(Void.class, mapper.getClass(API.VOID)); + + assertTrue(mapper.newInstance(API.TOKEN_REQ) instanceof TokenRequest); + assertTrue(mapper.newInstance(API.TOKEN) instanceof Token); + assertTrue(mapper.newInstance(API.INTROSPECT) instanceof Introspect); + assertTrue(mapper.newInstance(API.ERROR) instanceof Error); + assertEquals(null, mapper.newInstance(API.VOID)); - Error error = mapper.errorFromMessage(null, null, "text", "var1", "var2"); - assertEquals("text", error.getText()); + Error error = mapper.errorFromMessage(null, null, "text", "var1", "var2"); + assertEquals("text", error.getText()); - Object tokenReqFromParams = mapper.tokenReqFromParams(req); - assertNull(tokenReqFromParams); - } + Object tokenReqFromParams = mapper.tokenReqFromParams(req); + assertNull(tokenReqFromParams); + } - @Test - public void testTokeReqFromParams() { - Map parameterMap = new TreeMap(); - parameterMap.put("client_id", new String[] { "ClientId1" }); - parameterMap.put("client_secret", new String[] { "client_secret" }); - parameterMap.put("username", new String[] { "username" }); - parameterMap.put("password", new String[] { "password" }); - parameterMap.put("scope", new String[] { "scope" }); - parameterMap.put("grant_type", new String[] { "grant_type" }); - parameterMap.put("refresh_token", new String[] { "refresh_token" }); - parameterMap.put("etc", new String[] { "etc" }); - when(req.getParameterMap()).thenReturn(parameterMap); + @Test + public void testTokeReqFromParams() { + Map parameterMap = new TreeMap(); + parameterMap.put("client_id", new String[] { "ClientId1" }); + parameterMap.put("client_secret", new String[] { "client_secret" }); + parameterMap.put("username", new String[] { "username" }); + parameterMap.put("password", new String[] { "password" }); + parameterMap.put("scope", new String[] { "scope" }); + parameterMap.put("grant_type", new String[] { "grant_type" }); + parameterMap.put("refresh_token", new String[] { "refresh_token" }); + parameterMap.put("etc", new String[] { "etc" }); + when(req.getParameterMap()).thenReturn(parameterMap); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - TokenRequest param = mapper.tokenReqFromParams(req); + TokenRequest param = mapper.tokenReqFromParams(req); - assertEquals("ClientId1", param.getClientId()); - assertEquals("client_secret", param.getClientSecret()); - assertEquals("username", param.getUsername()); - assertEquals("password", param.getPassword()); - assertEquals("scope", param.getScope()); - assertEquals("grant_type", param.getGrantType()); - assertEquals("refresh_token", param.getRefreshToken()); + assertEquals("ClientId1", param.getClientId()); + assertEquals("client_secret", param.getClientSecret()); + assertEquals("username", param.getUsername()); + assertEquals("password", param.getPassword()); + assertEquals("scope", param.getScope()); + assertEquals("grant_type", param.getGrantType()); + assertEquals("refresh_token", param.getRefreshToken()); - OCreds credsFromReq = mapper.credsFromReq(param); - assertEquals("ClientId1", credsFromReq.client_id); - assertEquals("username", credsFromReq.username); + OCreds credsFromReq = mapper.credsFromReq(param); + assertEquals("ClientId1", credsFromReq.client_id); + assertEquals("username", credsFromReq.username); - } + } - @Test - public void testTokeReqFromParamsWithNoValues() { - Map parameterMap = new TreeMap(); - parameterMap.put("client_id", new String[] {}); - parameterMap.put("client_secret", new String[] {}); - parameterMap.put("username", new String[] {}); - parameterMap.put("password", new String[] {}); - parameterMap.put("scope", new String[] {}); - parameterMap.put("grant_type", new String[] {}); - parameterMap.put("refresh_token", new String[] {}); - parameterMap.put("etc", new String[] {}); - when(req.getParameterMap()).thenReturn(parameterMap); + @Test + public void testTokeReqFromParamsWithNoValues() { + Map parameterMap = new TreeMap(); + parameterMap.put("client_id", new String[] {}); + parameterMap.put("client_secret", new String[] {}); + parameterMap.put("username", new String[] {}); + parameterMap.put("password", new String[] {}); + parameterMap.put("scope", new String[] {}); + parameterMap.put("grant_type", new String[] {}); + parameterMap.put("refresh_token", new String[] {}); + parameterMap.put("etc", new String[] {}); + when(req.getParameterMap()).thenReturn(parameterMap); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - Object param = mapper.tokenReqFromParams(req); + Object param = mapper.tokenReqFromParams(req); - assertNull(param); + assertNull(param); - } + } - @Test - public void testClientTokenReqWithClientCred() { - when(hgt.get()).thenReturn(GRANT_TYPE.client_credentials); - when(tokenRequest.getState()).thenReturn("State"); - when(tokenRequest.getGrantType()).thenReturn("client_credentials"); - when(tokenRequest.getScope()).thenReturn("Scope"); + @Test + public void testClientTokenReqWithClientCred() { + when(hgt.get()).thenReturn(GRANT_TYPE.client_credentials); + when(tokenRequest.getState()).thenReturn("State"); + when(tokenRequest.getGrantType()).thenReturn("client_credentials"); + when(tokenRequest.getScope()).thenReturn("Scope"); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - Data clientTokenReq = mapper.clientTokenReq(tokenRequest, hgt); + Data clientTokenReq = mapper.clientTokenReq(tokenRequest, hgt); - assertEquals("State", clientTokenReq.state); - assertTrue(clientTokenReq.scopes.contains("Scope")); + assertEquals("State", clientTokenReq.state); + assertTrue(clientTokenReq.scopes.contains("Scope")); - } + } - @Test - public void testClientTokenReqWithPassword() { - when(hgt.get()).thenReturn(GRANT_TYPE.unknown); - when(tokenRequest.getState()).thenReturn("State"); - when(tokenRequest.getRefreshToken()).thenReturn("UnKnown"); + @Test + public void testClientTokenReqWithPassword() { + when(hgt.get()).thenReturn(GRANT_TYPE.unknown); + when(tokenRequest.getState()).thenReturn("State"); + when(tokenRequest.getRefreshToken()).thenReturn("UnKnown"); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - Data clientTokenReq = mapper.clientTokenReq(tokenRequest, hgt); + Data clientTokenReq = mapper.clientTokenReq(tokenRequest, hgt); - assertEquals("State", clientTokenReq.state); - assertEquals(clientTokenReq.type, 0); - } + assertEquals("State", clientTokenReq.state); + assertEquals(clientTokenReq.type, 0); + } - @Test - public void testTokenFromDataWithNotOk() { - Result dataResult = Result.create(null, 1, "detail", "var"); + @Test + public void testTokenFromDataWithNotOk() { + Result dataResult = Result.create(null, 1, "detail", "var"); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - Result clientTokenReq = mapper.tokenFromData(dataResult); + Result clientTokenReq = mapper.tokenFromData(dataResult); - assertEquals(null, clientTokenReq.value); - } + assertEquals(null, clientTokenReq.value); + } - @Test - public void testTokenFromData() { + @Test + public void testTokenFromData() { - Result dataResult = Result.create(data, 0, "detail", "var"); + Result dataResult = Result.create(data, 0, "detail", "var"); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - Result clientTokenReq = mapper.tokenFromData(dataResult); + Result clientTokenReq = mapper.tokenFromData(dataResult); - assertEquals(clientTokenReq.value.getAccessToken(), data.id); - } + assertEquals(clientTokenReq.value.getAccessToken(), data.id); + } - @Test - public void testTokenFromDataWithNoTokenType() { - data.type = 20; + @Test + public void testTokenFromDataWithNoTokenType() { + data.type = 20; - Result dataResult = Result.create(data, 0, "detail", "var"); + Result dataResult = Result.create(data, 0, "detail", "var"); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - Result clientTokenReq = mapper.tokenFromData(dataResult); + Result clientTokenReq = mapper.tokenFromData(dataResult); - assertEquals(clientTokenReq.value.getAccessToken(), data.id); - assertEquals(clientTokenReq.value.getTokenType(), "Invalid"); - } + assertEquals(clientTokenReq.value.getAccessToken(), data.id); + assertEquals(clientTokenReq.value.getTokenType(), "Invalid"); + } - @Test - public void testFromPrincipal() { + @Test + public void testFromPrincipal() { - Introspect introspect = new Introspect(); - when(p.tokenPerm().getIntrospect()).thenReturn(introspect); + Introspect introspect = new Introspect(); + when(p.tokenPerm().getIntrospect()).thenReturn(introspect); - Mapper mapper = new Mapper1_0(); + Mapper mapper = new Mapper1_0(); - Introspect intro = mapper.fromPrincipal(p); + Introspect intro = mapper.fromPrincipal(p); - assertEquals(introspect, intro); - } + assertEquals(introspect, intro); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_MapperIntrospect1_0Test.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_MapperIntrospect1_0Test.java index d303755f..f5e50d5e 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_MapperIntrospect1_0Test.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/mapper/JU_MapperIntrospect1_0Test.java @@ -37,58 +37,58 @@ import org.onap.aaf.auth.layer.Result; import aafoauth.v2_0.Introspect; public class JU_MapperIntrospect1_0Test { - @Mock - private HttpServletRequest req; + @Mock + private HttpServletRequest req; - Data data; + Data data; - @Before - public void setup() { - initMocks(this); - data = new Data(); - } + @Before + public void setup() { + initMocks(this); + data = new Data(); + } - @Test - public void testIntrospect() { - data.type = 1; + @Test + public void testIntrospect() { + data.type = 1; - Result dataResult = Result.create(data, 0, "detail", "var"); + Result dataResult = Result.create(data, 0, "detail", "var"); - MapperIntrospect mapper = new MapperIntrospect1_0(); + MapperIntrospect mapper = new MapperIntrospect1_0(); - Result intro = mapper.introspect(dataResult); + Result intro = mapper.introspect(dataResult); - assertEquals(intro.value.getClientType(), "confidential"); - } + assertEquals(intro.value.getClientType(), "confidential"); + } - @Test - public void testIntrospectWithUnknowType() { - data.type = 5; - data.scopes = new HashSet(); + @Test + public void testIntrospectWithUnknowType() { + data.type = 5; + data.scopes = new HashSet(); - data.scopes.add(Scope.APPLICATION.toString()); - data.scopes.add(Scope.HANDLER.toString()); + data.scopes.add(Scope.APPLICATION.toString()); + data.scopes.add(Scope.HANDLER.toString()); - Result dataResult = Result.create(data, 0, "detail", "var"); + Result dataResult = Result.create(data, 0, "detail", "var"); - MapperIntrospect mapper = new MapperIntrospect1_0(); + MapperIntrospect mapper = new MapperIntrospect1_0(); - Result intro = mapper.introspect(dataResult); + Result intro = mapper.introspect(dataResult); - assertEquals(intro.value.getClientType(), "unknown"); - } + assertEquals(intro.value.getClientType(), "unknown"); + } - @Test - public void testIntrospectWithNotOk() { - data.type = 5; + @Test + public void testIntrospectWithNotOk() { + data.type = 5; - Result dataResult = Result.create(data, 1, "detail", "var"); + Result dataResult = Result.create(data, 1, "detail", "var"); - MapperIntrospect mapper = new MapperIntrospect1_0(); + MapperIntrospect mapper = new MapperIntrospect1_0(); - Result intro = mapper.introspect(dataResult); + Result intro = mapper.introspect(dataResult); - assertEquals(intro.value, null); - } + assertEquals(intro.value, null); + } } \ No newline at end of file diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_JSONPermLoaderFactoryTest.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_JSONPermLoaderFactoryTest.java index 1a13580f..4a26da7d 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_JSONPermLoaderFactoryTest.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_JSONPermLoaderFactoryTest.java @@ -54,147 +54,147 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.TimeTaken; public class JU_JSONPermLoaderFactoryTest { - @Mock - private AAFCon aafcon; - @Mock - private AuthzTrans trans; - @Mock - private TimeTaken tt; - @Mock - Rcli c; - @Mock - private Future fs; - @Mock - private Question question; - @Mock - private Result rdns; - private NsSplit nss; + @Mock + private AAFCon aafcon; + @Mock + private AuthzTrans trans; + @Mock + private TimeTaken tt; + @Mock + Rcli c; + @Mock + private Future fs; + @Mock + private Question question; + @Mock + private Result rdns; + private NsSplit nss; - private Access access; + private Access access; - @Before - public void setup() throws CadiException { - access = new AuthzEnv(); - Define.set(access); - initMocks(this); - nss = new NsSplit("APPLICATION", "APPLICATION"); - } + @Before + public void setup() throws CadiException { + access = new AuthzEnv(); + Define.set(access); + initMocks(this); + nss = new NsSplit("APPLICATION", "APPLICATION"); + } - @Test - public void testRemoteWithTimeOut() throws APIException, CadiException { - when(trans.start("Call AAF Service", Env.REMOTE)).thenReturn(tt); - when(aafcon.clientAs(Config.AAF_DEFAULT_VERSION, trans.getUserPrincipal())).thenReturn(c); - when(c.read("/authz/perms/user/null?scopes=APPLICATION:HANDLER", - "application/Perms+json;charset=utf-8;version=2.0")).thenReturn(fs); - when(fs.get(0)).thenReturn(true); + @Test + public void testRemoteWithTimeOut() throws APIException, CadiException { + when(trans.start("Call AAF Service", Env.REMOTE)).thenReturn(tt); + when(aafcon.clientAs(Config.AAF_DEFAULT_VERSION, trans.getUserPrincipal())).thenReturn(c); + when(c.read("/authz/perms/user/null?scopes=APPLICATION:HANDLER", + "application/Perms+json;charset=utf-8;version=2.0")).thenReturn(fs); + when(fs.get(0)).thenReturn(true); - Set scopes = new HashSet(); - scopes.add(Scope.APPLICATION.toString()); - scopes.add(Scope.HANDLER.toString()); + Set scopes = new HashSet(); + scopes.add(Scope.APPLICATION.toString()); + scopes.add(Scope.HANDLER.toString()); - JSONPermLoader factory = JSONPermLoaderFactory.remote(aafcon, 0); + JSONPermLoader factory = JSONPermLoaderFactory.remote(aafcon, 0); - Result loadJSONPerms = factory.loadJSONPerms(trans, null, scopes); + Result loadJSONPerms = factory.loadJSONPerms(trans, null, scopes); - assertEquals(0, loadJSONPerms.status); + assertEquals(0, loadJSONPerms.status); - verify(tt, only()).done(); - } + verify(tt, only()).done(); + } - @Test - public void testRemoteWith404() throws APIException, CadiException { - when(trans.start("Call AAF Service", Env.REMOTE)).thenReturn(tt); - when(aafcon.clientAs(Config.AAF_DEFAULT_VERSION, trans.getUserPrincipal())).thenReturn(c); - when(c.read("/authz/perms/user/null?scopes=APPLICATION:HANDLER", - "application/Perms+json;charset=utf-8;version=2.0")).thenReturn(fs); - when(fs.get(0)).thenReturn(false); - when(fs.code()).thenReturn(404); + @Test + public void testRemoteWith404() throws APIException, CadiException { + when(trans.start("Call AAF Service", Env.REMOTE)).thenReturn(tt); + when(aafcon.clientAs(Config.AAF_DEFAULT_VERSION, trans.getUserPrincipal())).thenReturn(c); + when(c.read("/authz/perms/user/null?scopes=APPLICATION:HANDLER", + "application/Perms+json;charset=utf-8;version=2.0")).thenReturn(fs); + when(fs.get(0)).thenReturn(false); + when(fs.code()).thenReturn(404); - Set scopes = new HashSet(); - scopes.add(Scope.APPLICATION.toString()); - scopes.add(Scope.HANDLER.toString()); + Set scopes = new HashSet(); + scopes.add(Scope.APPLICATION.toString()); + scopes.add(Scope.HANDLER.toString()); - JSONPermLoader factory = JSONPermLoaderFactory.remote(aafcon, 0); + JSONPermLoader factory = JSONPermLoaderFactory.remote(aafcon, 0); - Result loadJSONPerms = factory.loadJSONPerms(trans, null, scopes); + Result loadJSONPerms = factory.loadJSONPerms(trans, null, scopes); - assertEquals(Result.ERR_NotFound, loadJSONPerms.status); + assertEquals(Result.ERR_NotFound, loadJSONPerms.status); - verify(tt, only()).done(); - } + verify(tt, only()).done(); + } - @Test - public void testRemote() throws APIException, CadiException { - when(trans.start("Call AAF Service", Env.REMOTE)).thenReturn(tt); - when(aafcon.clientAs(Config.AAF_DEFAULT_VERSION, trans.getUserPrincipal())).thenReturn(c); - when(c.read("/authz/perms/user/null?scopes=APPLICATION:HANDLER", - "application/Perms+json;charset=utf-8;version=2.0")).thenReturn(fs); - when(fs.get(0)).thenReturn(false); + @Test + public void testRemote() throws APIException, CadiException { + when(trans.start("Call AAF Service", Env.REMOTE)).thenReturn(tt); + when(aafcon.clientAs(Config.AAF_DEFAULT_VERSION, trans.getUserPrincipal())).thenReturn(c); + when(c.read("/authz/perms/user/null?scopes=APPLICATION:HANDLER", + "application/Perms+json;charset=utf-8;version=2.0")).thenReturn(fs); + when(fs.get(0)).thenReturn(false); - Set scopes = new HashSet(); - scopes.add(Scope.APPLICATION.toString()); - scopes.add(Scope.HANDLER.toString()); + Set scopes = new HashSet(); + scopes.add(Scope.APPLICATION.toString()); + scopes.add(Scope.HANDLER.toString()); - JSONPermLoader factory = JSONPermLoaderFactory.remote(aafcon, 0); + JSONPermLoader factory = JSONPermLoaderFactory.remote(aafcon, 0); - Result loadJSONPerms = factory.loadJSONPerms(trans, null, scopes); + Result loadJSONPerms = factory.loadJSONPerms(trans, null, scopes); - assertEquals(Result.ERR_Backend, loadJSONPerms.status); + assertEquals(Result.ERR_Backend, loadJSONPerms.status); - verify(tt, only()).done(); - } + verify(tt, only()).done(); + } - @Test - public void testDirectWhenPdNotOk() throws APIException, CadiException { + @Test + public void testDirectWhenPdNotOk() throws APIException, CadiException { - Result> pd = Result.create(null, Result.ERR_Backend, "details", "vars"); + Result> pd = Result.create(null, Result.ERR_Backend, "details", "vars"); - when(question.getPermsByUser(trans, "user", false)).thenReturn(pd); - when(trans.start("Cached DB Perm lookup", Env.SUB)).thenReturn(tt); + when(question.getPermsByUser(trans, "user", false)).thenReturn(pd); + when(trans.start("Cached DB Perm lookup", Env.SUB)).thenReturn(tt); - Set scopes = new HashSet(); - scopes.add(Scope.APPLICATION.toString()); - scopes.add(Scope.HANDLER.toString()); + Set scopes = new HashSet(); + scopes.add(Scope.APPLICATION.toString()); + scopes.add(Scope.HANDLER.toString()); - JSONPermLoader factory = JSONPermLoaderFactory.direct(question); + JSONPermLoader factory = JSONPermLoaderFactory.direct(question); - Result loadJSONPerms = factory.loadJSONPerms(trans, "user", scopes); + Result loadJSONPerms = factory.loadJSONPerms(trans, "user", scopes); - assertEquals(Result.ERR_Backend, loadJSONPerms.status); + assertEquals(Result.ERR_Backend, loadJSONPerms.status); - verify(tt, only()).done(); - } + verify(tt, only()).done(); + } - @Test - public void testDirectWhenPdOk() throws APIException, CadiException { + @Test + public void testDirectWhenPdOk() throws APIException, CadiException { - when(trans.start("Cached DB Perm lookup", Env.SUB)).thenReturn(tt); - when(question.deriveNsSplit(trans, "name")).thenReturn(rdns); - when(rdns.isOKhasData()).thenReturn(false); + when(trans.start("Cached DB Perm lookup", Env.SUB)).thenReturn(tt); + when(question.deriveNsSplit(trans, "name")).thenReturn(rdns); + when(rdns.isOKhasData()).thenReturn(false); - List list = new ArrayList(); - list.add(new PermDAO.Data(nss, "instance", "action")); - list.add(new PermDAO.Data(nss, "instance", "action")); + List list = new ArrayList(); + list.add(new PermDAO.Data(nss, "instance", "action")); + list.add(new PermDAO.Data(nss, "instance", "action")); - Result> pd = Result.create(list, Result.OK, "details", "vars"); + Result> pd = Result.create(list, Result.OK, "details", "vars"); - when(question.getPermsByUser(trans, "user", false)).thenReturn(pd); + when(question.getPermsByUser(trans, "user", false)).thenReturn(pd); - Set scopes = new HashSet(); - scopes.add(Scope.APPLICATION.toString()); - scopes.add(Scope.HANDLER.toString()); + Set scopes = new HashSet(); + scopes.add(Scope.APPLICATION.toString()); + scopes.add(Scope.HANDLER.toString()); - JSONPermLoader factory = JSONPermLoaderFactory.direct(question); + JSONPermLoader factory = JSONPermLoaderFactory.direct(question); - Result loadJSONPerms = factory.loadJSONPerms(trans, "user", scopes); + Result loadJSONPerms = factory.loadJSONPerms(trans, "user", scopes); - assertEquals(Result.OK, loadJSONPerms.status); - assertEquals("Success", loadJSONPerms.details); - assertEquals( - "{\"perm\":[{\"ns\":\"APPLICATION\",\"type\":\"APPLICATION\",\"instance\":\"instance\",\"action\":\"action\"},{\"ns\":\"APPLICATION\",\"type\":\"APPLICATION\",\"instance\":\"instance\",\"action\":\"action\"}]}", - loadJSONPerms.value); + assertEquals(Result.OK, loadJSONPerms.status); + assertEquals("Success", loadJSONPerms.details); + assertEquals( + "{\"perm\":[{\"ns\":\"APPLICATION\",\"type\":\"APPLICATION\",\"instance\":\"instance\",\"action\":\"action\"},{\"ns\":\"APPLICATION\",\"type\":\"APPLICATION\",\"instance\":\"instance\",\"action\":\"action\"}]}", + loadJSONPerms.value); - verify(tt, only()).done(); - } + verify(tt, only()).done(); + } } diff --git a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_OCredsTest.java b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_OCredsTest.java index 1c16772b..51ea07a3 100644 --- a/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_OCredsTest.java +++ b/auth/auth-oauth/src/test/java/org/onap/aaf/auth/oauth/service/JU_OCredsTest.java @@ -26,24 +26,24 @@ import org.junit.Test; public class JU_OCredsTest { - @Test - public void test() { - OCreds cred = new OCreds("client_id", "client_secret", "username", "password"); - - assertEquals(cred.client_id, "client_id"); - assertEquals(cred.username, "username"); - assertEquals(new String(cred.client_secret), "client_secret"); - assertEquals(new String(cred.password), "password"); - } - - @Test - public void testWithNullValues() { - OCreds cred = new OCreds("client_id", null, "username", null); - - assertEquals(cred.client_id, "client_id"); - assertEquals(cred.username, "username"); - assertEquals(cred.client_secret, null); - assertEquals(cred.password, null); - } + @Test + public void test() { + OCreds cred = new OCreds("client_id", "client_secret", "username", "password"); + + assertEquals(cred.client_id, "client_id"); + assertEquals(cred.username, "username"); + assertEquals(new String(cred.client_secret), "client_secret"); + assertEquals(new String(cred.password), "password"); + } + + @Test + public void testWithNullValues() { + OCreds cred = new OCreds("client_id", null, "username", null); + + assertEquals(cred.client_id, "client_id"); + assertEquals(cred.username, "username"); + assertEquals(cred.client_secret, null); + assertEquals(cred.password, null); + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java index 40640007..69cde411 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java @@ -70,168 +70,168 @@ import com.datastax.driver.core.Cluster; public class AAF_Service extends AbsService { - private static final String ORGANIZATION = "Organization."; - - public final Question question; - private AuthzFacade_2_0 facade; - private AuthzFacade_2_0 facade_XML; - private DirectAAFUserPass directAAFUserPass; - private final Cluster cluster; - //private final OAuthService oauthService; - - /** - * Construct AuthzAPI with all the Context Supporting Routes that Authz needs - * - * @param env - * @param decryptor - * @throws APIException - */ - public AAF_Service( final AuthzEnv env) throws Exception { - super(env.access(), env); - - // Initialize Facade for all uses - AuthzTrans trans = env.newTrans(); - - cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); - - // Need Question for Security purposes (direct User/Authz Query in Filter) - // Start Background Processing - question = new Question(trans, cluster, CassAccess.KEYSPACE, true); - DirectCertIdentity.set(question.certDAO); - - // Have AAFLocator object Create DirectLocators for Location needs - AbsAAFLocator.setCreator(new DirectLocatorCreator(env, question.locateDAO)); - - // Initialize Organizations... otherwise, first pass may miss - int org_size = ORGANIZATION.length(); - for(String n : env.existingStaticSlotNames()) { - if(n.startsWith(ORGANIZATION)) { - OrganizationFactory.obtain(env, n.substring(org_size)); - } - } - - - // For direct Introspection needs. - //oauthService = new OAuthService(trans, question); - - facade = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.JSON,question); - facade_XML = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.XML,question); - - directAAFUserPass = new DirectAAFUserPass(trans.env(),question); - - // Print results and cleanup - StringBuilder sb = new StringBuilder(); - trans.auditTrail(0, sb); - if(sb.length()>0)env.init().log(sb); - trans = null; - sb = null; - - //////////////////////////////////////////////////////////////////////////// - // Time Critical - // These will always be evaluated first - //////////////////////////////////////////////////////////////////////// - API_Creds.timeSensitiveInit(env, this, facade,directAAFUserPass); - API_Perms.timeSensitiveInit(this, facade); - //////////////////////////////////////////////////////////////////////// - // Service APIs - //////////////////////////////////////////////////////////////////////// - API_Creds.init(this, facade); - API_UserRole.init(this, facade); - API_Roles.init(this, facade); - API_Perms.init(this, facade); - API_NS.init(this, facade); - API_User.init(this, facade); - API_Delegate.init(this,facade); - API_Approval.init(this, facade); - API_History.init(this, facade); - - //////////////////////////////////////////////////////////////////////// - // Management APIs - //////////////////////////////////////////////////////////////////////// - // There are several APIs around each concept, and it gets a bit too - // long in this class to create. The initialization of these Management - // APIs have therefore been pushed to StandAlone Classes with static - // init functions - API_Mgmt.init(this, facade); - API_Api.init(this, facade); - - } - - @Override - public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { - final String domain = FQI.reverseDomain(access.getProperty(Config.AAF_ROOT_NS,Config.AAF_ROOT_NS_DEF)); - try { - Object[] atl=new Object[additionalTafLurs.length+2]; - atl[0]=new DirectAAFLur(env,question); // Note, this will be assigned by AuthzTransFilter to TrustChecker - atl[1]= new BasicHttpTaf(env, directAAFUserPass, - domain,Long.parseLong(env.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)), - false); - - if(additionalTafLurs.length>0) { - System.arraycopy(additionalTafLurs, 0, atl, 2, additionalTafLurs.length); - } - - return new Filter[] { - new AuthzTransFilter(env,aafCon(), - new AAFTrustChecker((Env)env), - atl - )}; - } catch (NumberFormatException e) { - throw new CadiException("Invalid Property information", e); - } - } - - - - @SuppressWarnings("unchecked") - @Override - public Registrant[] registrants(final int port) throws CadiException { - return new Registrant[] { - new DirectRegistrar(access,question.locateDAO,app_name,app_interface_version,port) - }; - } - - @Override - public void destroy() { - Cache.stopTimer(); - if(cluster!=null) { - cluster.close(); - } - super.destroy(); - } - - - /** - * Setup XML and JSON implementations for each supported Version type - * - * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties - * to do Versions and Content switches - * - */ - public void route(HttpMethods meth, String path, API api, Code code) throws Exception { - String version = "2.0"; - Class respCls = facade.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); - String application = applicationJSON(respCls, version); - - route(env,meth,path,code,application,"application/json;version=2.0","*/*"); - application = applicationXML(respCls, version); - route(env,meth,path,code.clone(facade_XML,false),application,"text/xml;version=2.0"); - } - - /** - * Start up AAF_Service as Jetty Service - */ - public static void main(final String[] args) { - try { - Log4JLogIt logIt = new Log4JLogIt(args, "authz"); - PropAccess propAccess = new PropAccess(logIt,args); - - AbsService service = new AAF_Service(new AuthzEnv(propAccess)); - JettyServiceStarter jss = new JettyServiceStarter(service); - jss.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + private static final String ORGANIZATION = "Organization."; + + public final Question question; + private AuthzFacade_2_0 facade; + private AuthzFacade_2_0 facade_XML; + private DirectAAFUserPass directAAFUserPass; + private final Cluster cluster; + //private final OAuthService oauthService; + + /** + * Construct AuthzAPI with all the Context Supporting Routes that Authz needs + * + * @param env + * @param decryptor + * @throws APIException + */ + public AAF_Service( final AuthzEnv env) throws Exception { + super(env.access(), env); + + // Initialize Facade for all uses + AuthzTrans trans = env.newTrans(); + + cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); + + // Need Question for Security purposes (direct User/Authz Query in Filter) + // Start Background Processing + question = new Question(trans, cluster, CassAccess.KEYSPACE, true); + DirectCertIdentity.set(question.certDAO); + + // Have AAFLocator object Create DirectLocators for Location needs + AbsAAFLocator.setCreator(new DirectLocatorCreator(env, question.locateDAO)); + + // Initialize Organizations... otherwise, first pass may miss + int org_size = ORGANIZATION.length(); + for(String n : env.existingStaticSlotNames()) { + if(n.startsWith(ORGANIZATION)) { + OrganizationFactory.obtain(env, n.substring(org_size)); + } + } + + + // For direct Introspection needs. + //oauthService = new OAuthService(trans, question); + + facade = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.JSON,question); + facade_XML = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.XML,question); + + directAAFUserPass = new DirectAAFUserPass(trans.env(),question); + + // Print results and cleanup + StringBuilder sb = new StringBuilder(); + trans.auditTrail(0, sb); + if(sb.length()>0)env.init().log(sb); + trans = null; + sb = null; + + //////////////////////////////////////////////////////////////////////////// + // Time Critical + // These will always be evaluated first + //////////////////////////////////////////////////////////////////////// + API_Creds.timeSensitiveInit(env, this, facade,directAAFUserPass); + API_Perms.timeSensitiveInit(this, facade); + //////////////////////////////////////////////////////////////////////// + // Service APIs + //////////////////////////////////////////////////////////////////////// + API_Creds.init(this, facade); + API_UserRole.init(this, facade); + API_Roles.init(this, facade); + API_Perms.init(this, facade); + API_NS.init(this, facade); + API_User.init(this, facade); + API_Delegate.init(this,facade); + API_Approval.init(this, facade); + API_History.init(this, facade); + + //////////////////////////////////////////////////////////////////////// + // Management APIs + //////////////////////////////////////////////////////////////////////// + // There are several APIs around each concept, and it gets a bit too + // long in this class to create. The initialization of these Management + // APIs have therefore been pushed to StandAlone Classes with static + // init functions + API_Mgmt.init(this, facade); + API_Api.init(this, facade); + + } + + @Override + public Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException { + final String domain = FQI.reverseDomain(access.getProperty(Config.AAF_ROOT_NS,Config.AAF_ROOT_NS_DEF)); + try { + Object[] atl=new Object[additionalTafLurs.length+2]; + atl[0]=new DirectAAFLur(env,question); // Note, this will be assigned by AuthzTransFilter to TrustChecker + atl[1]= new BasicHttpTaf(env, directAAFUserPass, + domain,Long.parseLong(env.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)), + false); + + if(additionalTafLurs.length>0) { + System.arraycopy(additionalTafLurs, 0, atl, 2, additionalTafLurs.length); + } + + return new Filter[] { + new AuthzTransFilter(env,aafCon(), + new AAFTrustChecker((Env)env), + atl + )}; + } catch (NumberFormatException e) { + throw new CadiException("Invalid Property information", e); + } + } + + + + @SuppressWarnings("unchecked") + @Override + public Registrant[] registrants(final int port) throws CadiException { + return new Registrant[] { + new DirectRegistrar(access,question.locateDAO,app_name,app_interface_version,port) + }; + } + + @Override + public void destroy() { + Cache.stopTimer(); + if(cluster!=null) { + cluster.close(); + } + super.destroy(); + } + + + /** + * Setup XML and JSON implementations for each supported Version type + * + * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties + * to do Versions and Content switches + * + */ + public void route(HttpMethods meth, String path, API api, Code code) throws Exception { + String version = "2.0"; + Class respCls = facade.mapper().getClass(api); + if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + String application = applicationJSON(respCls, version); + + route(env,meth,path,code,application,"application/json;version=2.0","*/*"); + application = applicationXML(respCls, version); + route(env,meth,path,code.clone(facade_XML,false),application,"text/xml;version=2.0"); + } + + /** + * Start up AAF_Service as Jetty Service + */ + public static void main(final String[] args) { + try { + Log4JLogIt logIt = new Log4JLogIt(args, "authz"); + PropAccess propAccess = new PropAccess(logIt,args); + + AbsService service = new AAF_Service(new AuthzEnv(propAccess)); + JettyServiceStarter jss = new JettyServiceStarter(service); + jss.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java index 668d482c..c3e92df4 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java @@ -107,1160 +107,1160 @@ import aaf.v2_0.CredRequest; * @param * @param */ -public class AuthzCassServiceImpl - implements AuthzService { - - private Mapper mapper; - @Override - public Mapper mapper() {return mapper;} - - private static final String ASTERIX = "*"; - private static final String CACHE = "cache"; - private static final String ROOT_NS = Define.ROOT_NS(); - private static final String ROOT_COMPANY = Define.ROOT_COMPANY(); - - private final Question ques; - private final Function func; - - public AuthzCassServiceImpl(AuthzTrans trans, Mapper mapper,Question question) { - this.ques = question; - func = new Function(trans, question); - this.mapper = mapper; - - } +public class AuthzCassServiceImpl + implements AuthzService { + + private Mapper mapper; + @Override + public Mapper mapper() {return mapper;} + + private static final String ASTERIX = "*"; + private static final String CACHE = "cache"; + private static final String ROOT_NS = Define.ROOT_NS(); + private static final String ROOT_COMPANY = Define.ROOT_COMPANY(); + + private final Question ques; + private final Function func; + + public AuthzCassServiceImpl(AuthzTrans trans, Mapper mapper,Question question) { + this.ques = question; + func = new Function(trans, question); + this.mapper = mapper; + + } /*********************************** * NAMESPACE ***********************************/ - /** - * createNS - * @throws DAOException - * @see org.onap.aaf.auth.service.AuthzService#createNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) - */ - @ApiDoc( - method = POST, - path = "/authz/ns", - params = {}, - expectedCode = 201, - errorCodes = { 403,404,406,409 }, - text = { "Namespace consists of: ", - "

    ", - "Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ", - "created with parent credentials (i.e. To create com.myCompany.myApp, you must ", - "be an admin of com.myCompany or com" - } - ) - @Override - public Result createNS(final AuthzTrans trans, REQUEST from, NsType type) { - final Result rnamespace = mapper.ns(trans, from); - final ServiceValidator v = new ServiceValidator(); - if(v.ns(rnamespace).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - final Namespace namespace = rnamespace.value; - final Result parentNs = ques.deriveNs(trans,namespace.name); - if(parentNs.notOK()) { - return Result.err(parentNs); - } - - if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed - return func.createNS(trans, namespace, false); - } - - Result fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true, - new Mapper.Memo() { - @Override - public String get() { - return "Create Namespace [" + namespace.name + ']'; - } - }, - new MayChange() { - private Result rnd; - @Override - public Result mayChange() { - if(rnd==null) { - rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write); - } - return rnd; - } - }); - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, FUTURE_OP.C); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - return func.createNS(trans, namespace, false); - default: - return Result.err(fd); - } - } - - @ApiDoc( - method = POST, - path = "/authz/ns/:ns/admin/:id", - params = { "ns|string|true", - "id|string|true" - }, - expectedCode = 201, - errorCodes = { 403,404,406,409 }, - text = { "Add an Identity :id to the list of Admins for the Namespace :ns", - "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" } - ) - @Override - public Result addAdminNS(AuthzTrans trans, String ns, String id) { - return func.addUserRole(trans, id, ns,Question.ADMIN); - } - - @ApiDoc( - method = DELETE, - path = "/authz/ns/:ns/admin/:id", - params = { "ns|string|true", - "id|string|true" - }, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { "Remove an Identity :id from the list of Admins for the Namespace :ns", - "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" } - ) - @Override - public Result delAdminNS(AuthzTrans trans, String ns, String id) { - return func.delAdmin(trans,ns,id); - } - - @ApiDoc( - method = POST, - path = "/authz/ns/:ns/responsible/:id", - params = { "ns|string|true", - "id|string|true" - }, - expectedCode = 201, - errorCodes = { 403,404,406,409 }, - text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns", - "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" } - ) - @Override - public Result addResponsibleNS(AuthzTrans trans, String ns, String id) { - return func.addUserRole(trans,id,ns,Question.OWNER); - } - - @ApiDoc( - method = DELETE, - path = "/authz/ns/:ns/responsible/:id", - params = { "ns|string|true", - "id|string|true" - }, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns", - "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)", - "Note: A namespace must have at least 1 responsible party" - } - ) - @Override - public Result delResponsibleNS(AuthzTrans trans, String ns, String id) { - return func.delOwner(trans,ns,id); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#applyModel(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) - */ - @ApiDoc( - method = POST, - path = "/authz/ns/:ns/attrib/:key/:value", - params = { "ns|string|true", - "key|string|true", - "value|string|true"}, - expectedCode = 201, - errorCodes = { 403,404,406,409 }, - text = { - "Create an attribute in the Namespace", - "You must be given direct permission for key by AAF" - } - ) - @Override - public Result createNsAttrib(AuthzTrans trans, String ns, String key, String value) { - TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); - try { - // Check inputs - final Validator v = new ServiceValidator(); - if(v.ns(ns).err() || - v.key(key).err() || - v.value(value).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // Check if exists already - Result> rlnsd = ques.nsDAO.read(trans, ns); - if(rlnsd.notOKorIsEmpty()) { - return Result.err(rlnsd); - } - NsDAO.Data nsd = rlnsd.value.get(0); - - // Check for Existence - if(nsd.attrib.get(key)!=null) { - return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key); - } - - // Check if User may put - if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, - ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { - return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); - } - - // Add Attrib - nsd.attrib.put(key, value); - ques.nsDAO.dao().attribAdd(trans,ns,key,value); - return Result.ok(); - } finally { - tt.done(); - } - } - - @ApiDoc( - method = GET, - path = "/authz/ns/attrib/:key", - params = { "key|string|true" }, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { - "Read Attributes for Namespace" - } - ) - @Override - public Result readNsByAttrib(AuthzTrans trans, String key) { - // Check inputs - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Key",key).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // May Read - if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, - ":"+trans.org().getDomain()+".*:"+key, Question.READ)) { - return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key); - } - - Result> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key); - if(rsd.notOK()) { - return Result.err(rsd); - } - return mapper().keys(rsd.value); - } - - - @ApiDoc( - method = PUT, - path = "/authz/ns/:ns/attrib/:key/:value", - params = { "ns|string|true", - "key|string|true"}, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { - "Update Value on an existing attribute in the Namespace", - "You must be given direct permission for key by AAF" - } - ) - @Override - public Result updateNsAttrib(AuthzTrans trans, String ns, String key, String value) { - TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); - try { - // Check inputs - final Validator v = new ServiceValidator(); - if(v.ns(ns).err() || - v.key(key).err() || - v.value(value).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // Check if exists already (NS must exist) - Result> rlnsd = ques.nsDAO.read(trans, ns); - if(rlnsd.notOKorIsEmpty()) { - return Result.err(rlnsd); - } - NsDAO.Data nsd = rlnsd.value.get(0); - - // Check for Existence - if(nsd.attrib.get(key)==null) { - return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key); - } - - // Check if User may put - if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, - ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { - return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); - } - - // Add Attrib - nsd.attrib.put(key, value); - - return ques.nsDAO.update(trans,nsd); + /** + * createNS + * @throws DAOException + * @see org.onap.aaf.auth.service.AuthzService#createNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @ApiDoc( + method = POST, + path = "/authz/ns", + params = {}, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Namespace consists of: ", + "
    • name - What you want to call this Namespace
    • ", + "
    • responsible(s) - Person(s) who receive Notifications and approves Requests ", + "regarding this Namespace. Companies have Policies as to who may take on ", + "this Responsibility. Separate multiple identities with commas
    • ", + "
    • admin(s) - Person(s) who are allowed to make changes on the namespace, ", + "including creating Roles, Permissions and Credentials. Separate multiple ", + "identities with commas
    ", + "Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ", + "created with parent credentials (i.e. To create com.myCompany.myApp, you must ", + "be an admin of com.myCompany or com" + } + ) + @Override + public Result createNS(final AuthzTrans trans, REQUEST from, NsType type) { + final Result rnamespace = mapper.ns(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.ns(rnamespace).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final Namespace namespace = rnamespace.value; + final Result parentNs = ques.deriveNs(trans,namespace.name); + if(parentNs.notOK()) { + return Result.err(parentNs); + } + + if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed + return func.createNS(trans, namespace, false); + } + + Result fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true, + new Mapper.Memo() { + @Override + public String get() { + return "Create Namespace [" + namespace.name + ']'; + } + }, + new MayChange() { + private Result rnd; + @Override + public Result mayChange() { + if(rnd==null) { + rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write); + } + return rnd; + } + }); + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.createNS(trans, namespace, false); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/admin/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Add an Identity :id to the list of Admins for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" } + ) + @Override + public Result addAdminNS(AuthzTrans trans, String ns, String id) { + return func.addUserRole(trans, id, ns,Question.ADMIN); + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/admin/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Remove an Identity :id from the list of Admins for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" } + ) + @Override + public Result delAdminNS(AuthzTrans trans, String ns, String id) { + return func.delAdmin(trans,ns,id); + } + + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/responsible/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" } + ) + @Override + public Result addResponsibleNS(AuthzTrans trans, String ns, String id) { + return func.addUserRole(trans,id,ns,Question.OWNER); + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/responsible/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)", + "Note: A namespace must have at least 1 responsible party" + } + ) + @Override + public Result delResponsibleNS(AuthzTrans trans, String ns, String id) { + return func.delOwner(trans,ns,id); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#applyModel(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/attrib/:key/:value", + params = { "ns|string|true", + "key|string|true", + "value|string|true"}, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { + "Create an attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result createNsAttrib(AuthzTrans trans, String ns, String key, String value) { + TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); + try { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.ns(ns).err() || + v.key(key).err() || + v.value(value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already + Result> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)!=null) { + return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key); + } + + // Check if User may put + if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.put(key, value); + ques.nsDAO.dao().attribAdd(trans,ns,key,value); + return Result.ok(); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authz/ns/attrib/:key", + params = { "key|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Read Attributes for Namespace" + } + ) + @Override + public Result readNsByAttrib(AuthzTrans trans, String key) { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Key",key).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // May Read + if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Question.READ)) { + return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key); + } + + Result> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key); + if(rsd.notOK()) { + return Result.err(rsd); + } + return mapper().keys(rsd.value); + } + + + @ApiDoc( + method = PUT, + path = "/authz/ns/:ns/attrib/:key/:value", + params = { "ns|string|true", + "key|string|true"}, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Update Value on an existing attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result updateNsAttrib(AuthzTrans trans, String ns, String key, String value) { + TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); + try { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.ns(ns).err() || + v.key(key).err() || + v.value(value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already (NS must exist) + Result> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)==null) { + return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key); + } + + // Check if User may put + if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.put(key, value); + + return ques.nsDAO.update(trans,nsd); - } finally { - tt.done(); - } - } - - @ApiDoc( - method = DELETE, - path = "/authz/ns/:ns/attrib/:key", - params = { "ns|string|true", - "key|string|true"}, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { - "Delete an attribute in the Namespace", - "You must be given direct permission for key by AAF" - } - ) - @Override - public Result deleteNsAttrib(AuthzTrans trans, String ns, String key) { - TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB); - try { - // Check inputs - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS",ns).err() || - v.nullOrBlank("Key",key).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // Check if exists already - Result> rlnsd = ques.nsDAO.read(trans, ns); - if(rlnsd.notOKorIsEmpty()) { - return Result.err(rlnsd); - } - NsDAO.Data nsd = rlnsd.value.get(0); - - // Check for Existence - if(nsd.attrib.get(key)==null) { - return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key); - } - - // Check if User may del - if(!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) { - return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key); - } - - // Add Attrib - nsd.attrib.remove(key); - ques.nsDAO.dao().attribRemove(trans,ns,key); - return Result.ok(); - } finally { - tt.done(); - } - } - - @ApiDoc( - method = GET, - path = "/authz/nss/:id", - params = { "id|string|true" }, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { - "Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)", - "Credential(s) and Expiration of Credential(s) in Namespace :id", - } - ) - @Override - public Result getNSbyName(AuthzTrans trans, String ns) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", ns).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rlnd = ques.nsDAO.read(trans, ns); - if(rlnd.isOK()) { - if(rlnd.isEmpty()) { - return Result.err(Status.ERR_NotFound, "No data found for %s",ns); - } - Result rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - - Namespace namespace = new Namespace(rnd.value); - Result> rd = func.getOwners(trans, namespace.name, false); - if(rd.isOK()) { - namespace.owner = rd.value; - } - rd = func.getAdmins(trans, namespace.name, false); - if(rd.isOK()) { - namespace.admin = rd.value; - } - - NSS nss = mapper.newInstance(API.NSS); - return mapper.nss(trans, namespace, nss); - } else { - return Result.err(rlnd); - } - } - - @ApiDoc( - method = GET, - path = "/authz/nss/admin/:id", - params = { "id|string|true" }, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { "Lists all Namespaces where Identity :id is an Admin", - "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" - } - ) - @Override - public Result getNSbyAdmin(AuthzTrans trans, String user, boolean full) { - final Validator v = new ServiceValidator(); - if (v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData, v.errs()); - } - - Result> rn = loadNamepace(trans, user, ".admin", full); - if(rn.notOK()) { - return Result.err(rn); - } - if (rn.isEmpty()) { - return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user); - } - NSS nss = mapper.newInstance(API.NSS); - // Note: "loadNamespace" already validates view of Namespace - return mapper.nss(trans, rn.value, nss); - } - - @ApiDoc( - method = GET, - path = "/authz/nss/either/:id", - params = { "id|string|true" }, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner", - "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" - } - ) - @Override - public Result getNSbyEither(AuthzTrans trans, String user, boolean full) { - final Validator v = new ServiceValidator(); - if (v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData, v.errs()); - } - - Result> rn = loadNamepace(trans, user, null, full); - if(rn.notOK()) { - return Result.err(rn); - } - if (rn.isEmpty()) { - return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user); - } - NSS nss = mapper.newInstance(API.NSS); - // Note: "loadNamespace" already validates view of Namespace - return mapper.nss(trans, rn.value, nss); - } - - private Result> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) { - Result> urd = ques.userRoleDAO.readByUser(trans, user); - if(urd.notOKorIsEmpty()) { - return Result.err(urd); - } - Map lm = new HashMap<>(); - Map other = full || endsWith==null?null:new TreeMap<>(); - for(UserRoleDAO.Data urdd : urd.value) { - if(full) { - if(endsWith==null || urdd.role.endsWith(endsWith)) { - RoleDAO.Data rd = RoleDAO.Data.decode(urdd); - Result nsd = ques.mayUser(trans, user, rd, Access.read); - if(nsd.isOK()) { - Namespace namespace = lm.get(nsd.value.name); - if(namespace==null) { - namespace = new Namespace(nsd.value); - lm.put(namespace.name,namespace); - } - Result> rls = func.getAdmins(trans, namespace.name, false); - if(rls.isOK()) { - namespace.admin=rls.value; - } - - rls = func.getOwners(trans, namespace.name, false); - if(rls.isOK()) { - namespace.owner=rls.value; - } - } - } - } else { // Shortened version. Only Namespace Info available from Role. - if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) { - RoleDAO.Data rd = RoleDAO.Data.decode(urdd); - Result nsd = ques.mayUser(trans, user, rd, Access.read); - if(nsd.isOK()) { - Namespace namespace = lm.get(nsd.value.name); - if(namespace==null) { - if(other!=null) { - namespace = other.remove(nsd.value.name); - } - if(namespace==null) { - namespace = new Namespace(nsd.value); - namespace.admin=new ArrayList<>(); - namespace.owner=new ArrayList<>(); - } - if(endsWith==null || urdd.role.endsWith(endsWith)) { - lm.put(namespace.name,namespace); - } else { - other.put(namespace.name,namespace); - } - } - if(Question.OWNER.equals(urdd.rname)) { - namespace.owner.add(urdd.user); - } else { - namespace.admin.add(urdd.user); - } - } - } - } - } - return Result.ok(lm.values()); - } - - @ApiDoc( - method = GET, - path = "/authz/nss/responsible/:id", - params = { "id|string|true" }, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { "Lists all Namespaces where Identity :id is a Responsible Party", - "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" - } - ) - @Override - public Result getNSbyResponsible(AuthzTrans trans, String user, boolean full) { - final Validator v = new ServiceValidator(); - if (v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData, v.errs()); - } - Result> rn = loadNamepace(trans, user, ".owner",full); - if(rn.notOK()) { - return Result.err(rn); - } - if (rn.isEmpty()) { - return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user); - } - NSS nss = mapper.newInstance(API.NSS); - // Note: "loadNamespace" prevalidates - return mapper.nss(trans, rn.value, nss); - } - - @ApiDoc( - method = GET, - path = "/authz/nss/children/:id", - params = { "id|string|true" }, - expectedCode = 200, - errorCodes = { 403,404 }, - text = { "Lists all Child Namespaces of Namespace :id", - "Note: This is not a cached read" - } - ) - @Override - public Result getNSsChildren(AuthzTrans trans, String parent) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", parent).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rnd = ques.deriveNs(trans, parent); - if(rnd.notOK()) { - return Result.err(rnd); - } - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - Set lm = new HashSet<>(); - Result> rlnd = ques.nsDAO.dao().getChildren(trans, parent); - if(rlnd.isOK()) { - if(rlnd.isEmpty()) { - return Result.err(Status.ERR_NotFound, "No data found for %s",parent); - } - for(NsDAO.Data ndd : rlnd.value) { - Namespace namespace = new Namespace(ndd); - Result> rls = func.getAdmins(trans, namespace.name, false); - if(rls.isOK()) { - namespace.admin=rls.value; - } - - rls = func.getOwners(trans, namespace.name, false); - if(rls.isOK()) { - namespace.owner=rls.value; - } - - lm.add(namespace); - } - NSS nss = mapper.newInstance(API.NSS); - return mapper.nss(trans,lm, nss); - } else { - return Result.err(rlnd); - } - } - - - @ApiDoc( - method = PUT, - path = "/authz/ns", - params = {}, - expectedCode = 200, - errorCodes = { 403,404,406 }, - text = { "Replace the Current Description of a Namespace with a new one" - } - ) - @Override - public Result updateNsDescription(AuthzTrans trans, REQUEST from) { - final Result nsd = mapper.ns(trans, from); - final ServiceValidator v = new ServiceValidator(); - if(v.ns(nsd).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - if(v.nullOrBlank("description", nsd.value.description).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Namespace namespace = nsd.value; - Result> rlnd = ques.nsDAO.read(trans, namespace.name); - - if(rlnd.notOKorIsEmpty()) { - return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name); - } - - if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) { - return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name); - } - - Result rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description); - if(rdr.isOK()) { - return Result.ok(); - } else { - return Result.err(rdr); - } - } - - /** - * deleteNS - * @throws DAOException - * @see org.onap.aaf.auth.service.AuthzService#deleteNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) - */ - @ApiDoc( - method = DELETE, - path = "/authz/ns/:ns", - params = { "ns|string|true" }, - expectedCode = 200, - errorCodes = { 403,404,424 }, - text = { "Delete the Namespace :ns. Namespaces cannot normally be deleted when there ", - "are still credentials associated with them, but they can be deleted by setting ", - "the \"force\" property. To do this: Add 'force=true' as a query parameter", - "

    WARNING: Using force will delete all credentials attached to this namespace. Use with care.

    " - + "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted," - + "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted " - + "at or below Application Scope" - } - ) - @Override - public Result deleteNS(AuthzTrans trans, String ns) { - return func.deleteNS(trans, ns); - } + } finally { + tt.done(); + } + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/attrib/:key", + params = { "ns|string|true", + "key|string|true"}, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Delete an attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result deleteNsAttrib(AuthzTrans trans, String ns, String key) { + TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB); + try { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS",ns).err() || + v.nullOrBlank("Key",key).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already + Result> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)==null) { + return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key); + } + + // Check if User may del + if(!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.remove(key); + ques.nsDAO.dao().attribRemove(trans,ns,key); + return Result.ok(); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authz/nss/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { + "Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)", + "Credential(s) and Expiration of Credential(s) in Namespace :id", + } + ) + @Override + public Result getNSbyName(AuthzTrans trans, String ns) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlnd = ques.nsDAO.read(trans, ns); + if(rlnd.isOK()) { + if(rlnd.isEmpty()) { + return Result.err(Status.ERR_NotFound, "No data found for %s",ns); + } + Result rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + + Namespace namespace = new Namespace(rnd.value); + Result> rd = func.getOwners(trans, namespace.name, false); + if(rd.isOK()) { + namespace.owner = rd.value; + } + rd = func.getAdmins(trans, namespace.name, false); + if(rd.isOK()) { + namespace.admin = rd.value; + } + + NSS nss = mapper.newInstance(API.NSS); + return mapper.nss(trans, namespace, nss); + } else { + return Result.err(rlnd); + } + } + + @ApiDoc( + method = GET, + path = "/authz/nss/admin/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is an Admin", + "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" + } + ) + @Override + public Result getNSbyAdmin(AuthzTrans trans, String user, boolean full) { + final Validator v = new ServiceValidator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + + Result> rn = loadNamepace(trans, user, ".admin", full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" already validates view of Namespace + return mapper.nss(trans, rn.value, nss); + } + + @ApiDoc( + method = GET, + path = "/authz/nss/either/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner", + "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" + } + ) + @Override + public Result getNSbyEither(AuthzTrans trans, String user, boolean full) { + final Validator v = new ServiceValidator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + + Result> rn = loadNamepace(trans, user, null, full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" already validates view of Namespace + return mapper.nss(trans, rn.value, nss); + } + + private Result> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) { + Result> urd = ques.userRoleDAO.readByUser(trans, user); + if(urd.notOKorIsEmpty()) { + return Result.err(urd); + } + Map lm = new HashMap<>(); + Map other = full || endsWith==null?null:new TreeMap<>(); + for(UserRoleDAO.Data urdd : urd.value) { + if(full) { + if(endsWith==null || urdd.role.endsWith(endsWith)) { + RoleDAO.Data rd = RoleDAO.Data.decode(urdd); + Result nsd = ques.mayUser(trans, user, rd, Access.read); + if(nsd.isOK()) { + Namespace namespace = lm.get(nsd.value.name); + if(namespace==null) { + namespace = new Namespace(nsd.value); + lm.put(namespace.name,namespace); + } + Result> rls = func.getAdmins(trans, namespace.name, false); + if(rls.isOK()) { + namespace.admin=rls.value; + } + + rls = func.getOwners(trans, namespace.name, false); + if(rls.isOK()) { + namespace.owner=rls.value; + } + } + } + } else { // Shortened version. Only Namespace Info available from Role. + if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) { + RoleDAO.Data rd = RoleDAO.Data.decode(urdd); + Result nsd = ques.mayUser(trans, user, rd, Access.read); + if(nsd.isOK()) { + Namespace namespace = lm.get(nsd.value.name); + if(namespace==null) { + if(other!=null) { + namespace = other.remove(nsd.value.name); + } + if(namespace==null) { + namespace = new Namespace(nsd.value); + namespace.admin=new ArrayList<>(); + namespace.owner=new ArrayList<>(); + } + if(endsWith==null || urdd.role.endsWith(endsWith)) { + lm.put(namespace.name,namespace); + } else { + other.put(namespace.name,namespace); + } + } + if(Question.OWNER.equals(urdd.rname)) { + namespace.owner.add(urdd.user); + } else { + namespace.admin.add(urdd.user); + } + } + } + } + } + return Result.ok(lm.values()); + } + + @ApiDoc( + method = GET, + path = "/authz/nss/responsible/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is a Responsible Party", + "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" + } + ) + @Override + public Result getNSbyResponsible(AuthzTrans trans, String user, boolean full) { + final Validator v = new ServiceValidator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + Result> rn = loadNamepace(trans, user, ".owner",full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" prevalidates + return mapper.nss(trans, rn.value, nss); + } + + @ApiDoc( + method = GET, + path = "/authz/nss/children/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Child Namespaces of Namespace :id", + "Note: This is not a cached read" + } + ) + @Override + public Result getNSsChildren(AuthzTrans trans, String parent) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", parent).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rnd = ques.deriveNs(trans, parent); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Set lm = new HashSet<>(); + Result> rlnd = ques.nsDAO.dao().getChildren(trans, parent); + if(rlnd.isOK()) { + if(rlnd.isEmpty()) { + return Result.err(Status.ERR_NotFound, "No data found for %s",parent); + } + for(NsDAO.Data ndd : rlnd.value) { + Namespace namespace = new Namespace(ndd); + Result> rls = func.getAdmins(trans, namespace.name, false); + if(rls.isOK()) { + namespace.admin=rls.value; + } + + rls = func.getOwners(trans, namespace.name, false); + if(rls.isOK()) { + namespace.owner=rls.value; + } + + lm.add(namespace); + } + NSS nss = mapper.newInstance(API.NSS); + return mapper.nss(trans,lm, nss); + } else { + return Result.err(rlnd); + } + } + + + @ApiDoc( + method = PUT, + path = "/authz/ns", + params = {}, + expectedCode = 200, + errorCodes = { 403,404,406 }, + text = { "Replace the Current Description of a Namespace with a new one" + } + ) + @Override + public Result updateNsDescription(AuthzTrans trans, REQUEST from) { + final Result nsd = mapper.ns(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.ns(nsd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + if(v.nullOrBlank("description", nsd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Namespace namespace = nsd.value; + Result> rlnd = ques.nsDAO.read(trans, namespace.name); + + if(rlnd.notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name); + } + + if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name); + } + + Result rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + } + + /** + * deleteNS + * @throws DAOException + * @see org.onap.aaf.auth.service.AuthzService#deleteNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns", + params = { "ns|string|true" }, + expectedCode = 200, + errorCodes = { 403,404,424 }, + text = { "Delete the Namespace :ns. Namespaces cannot normally be deleted when there ", + "are still credentials associated with them, but they can be deleted by setting ", + "the \"force\" property. To do this: Add 'force=true' as a query parameter", + "

    WARNING: Using force will delete all credentials attached to this namespace. Use with care.

    " + + "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted," + + "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted " + + "at or below Application Scope" + } + ) + @Override + public Result deleteNS(AuthzTrans trans, String ns) { + return func.deleteNS(trans, ns); + } /*********************************** * PERM ***********************************/ - /* - * (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object, boolean, java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List) - */ - @ApiDoc( - method = POST, - path = "/authz/perm", - params = {}, - expectedCode = 201, - errorCodes = {403,404,406,409}, - text = { "Permission consists of:", - "
    • type - a Namespace qualified identifier specifying what kind of resource " - + "is being protected
    • ", - "
    • instance - a key, possibly multi-dimensional, that identifies a specific " - + " instance of the type
    • ", - "
    • action - what kind of action is allowed
    ", - "Note: instance and action can be an *" - } - ) - @Override - public Result createPerm(final AuthzTrans trans,REQUEST rreq) { - final Result newPd = mapper.perm(trans, rreq); - final ServiceValidator v = new ServiceValidator(); - if(v.perm(newPd).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false, - new Mapper.Memo() { - @Override - public String get() { - return "Create Permission [" + - newPd.value.fullType() + '|' + - newPd.value.instance + '|' + - newPd.value.action + ']'; - } - }, - new MayChange() { - private Result nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write); - } - return nsd; - } - }); - Result> nsr = ques.nsDAO.read(trans, newPd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans,fd.value, - newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action, - trans.user(), - nsr.value.get(0), - FUTURE_OP.C); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", - newPd.value.ns, - newPd.value.type, - newPd.value.instance, - newPd.value.action); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - return func.createPerm(trans, newPd.value, true); - default: - return Result.err(fd); - } - } - - @ApiDoc( - method = GET, - path = "/authz/perms/:type", - params = {"type|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "List All Permissions that match the :type element of the key" } - ) - @Override - public Result getPermsByType(AuthzTrans trans, final String permType) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("PermType", permType).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rlpd = ques.getPermsByType(trans, permType); - if(rlpd.notOK()) { - return Result.err(rlpd); - } - -// We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper? -// Result r; -// if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r); - - PERMS perms = mapper.newInstance(API.PERMS); - if(!rlpd.isEmpty()) { - // Note: Mapper will restrict what can be viewed - return mapper.perms(trans, rlpd.value, perms, true); - } - return Result.ok(perms); - } - - @ApiDoc( - method = GET, - path = "/authz/perms/:type/:instance/:action", - params = {"type|string|true", - "instance|string|true", - "action|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "List Permissions that match key; :type, :instance and :action" } - ) - @Override - public Result getPermsByName(AuthzTrans trans, String type, String instance, String action) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("PermType", type).err() - || v.nullOrBlank("PermInstance", instance).err() - || v.nullOrBlank("PermAction", action).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rlpd = ques.getPermsByName(trans, type, instance, action); - if(rlpd.notOK()) { - return Result.err(rlpd); - } - - PERMS perms = mapper.newInstance(API.PERMS); - if(!rlpd.isEmpty()) { - // Note: Mapper will restrict what can be viewed - return mapper.perms(trans, rlpd.value, perms, true); - } - return Result.ok(perms); - } - - @ApiDoc( - method = GET, - path = "/authz/perms/user/:user", - params = {"user|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "List All Permissions that match user :user", - "

    'user' must be expressed as full identity (ex: id@full.domain.com)

    "} - ) - @Override - public Result getPermsByUser(AuthzTrans trans, String user) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rlpd = ques.getPermsByUser(trans, user, - trans.requested(force)); - if(rlpd.notOK()) { - return Result.err(rlpd); - } - - PERMS perms = mapper.newInstance(API.PERMS); - - if(rlpd.isEmpty()) { - return Result.ok(perms); - } - // Note: Mapper will restrict what can be viewed - // if user is the same as that which is looked up, no filtering is required - return mapper.perms(trans, rlpd.value, - perms, - !user.equals(trans.user())); - } - - @ApiDoc( - method = GET, - path = "/authz/perms/user/:user/scope/:scope", - params = {"user|string|true","scope|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "List All Permissions that match user :user, filtered by NS (Scope)", - "

    'user' must be expressed as full identity (ex: id@full.domain.com)

    ", - "

    'scope' must be expressed as NSs separated by ':'

    " - } - ) - @Override - public Result getPermsByUserScope(AuthzTrans trans, String user, String[] scopes) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rlpd = ques.getPermsByUser(trans, user, trans.requested(force)); - if(rlpd.notOK()) { - return Result.err(rlpd); - } - - PERMS perms = mapper.newInstance(API.PERMS); - - if(rlpd.isEmpty()) { - return Result.ok(perms); - } - // Note: Mapper will restrict what can be viewed - // if user is the same as that which is looked up, no filtering is required - return mapper.perms(trans, rlpd.value, - perms, - scopes, - !user.equals(trans.user())); - } - - @ApiDoc( - method = POST, - path = "/authz/perms/user/:user", - params = {"user|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "List All Permissions that match user :user", - "

    'user' must be expressed as full identity (ex: id@full.domain.com)

    ", - "", - "Present Queries as one or more Permissions (see ContentType Links below for format).", - "", - "If the Caller is Granted this specific Permission, and the Permission is valid", - " for the User, it will be included in response Permissions, along with", - " all the normal permissions on the 'GET' version of this call. If it is not", - " valid, or Caller does not have permission to see, it will be removed from the list", - "", - " *Note: This design allows you to make one call for all expected permissions", - " The permission to be included MUST be:", - " .access|:[:key]|", - " examples:", - " com.att.myns.access|:ns|write", - " com.att.myns.access|:role:myrole|create", - " com.att.myns.access|:perm:mytype:myinstance:myaction|read", - "" - } - ) - @Override - public Result getPermsByUser(AuthzTrans trans, PERMS _perms, String user) { - PERMS perms = _perms; - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - ////////////// - Result> rlpd = ques.getPermsByUser(trans, user,trans.requested(force)); - if(rlpd.notOK()) { - return Result.err(rlpd); - } - - /*//TODO - 1) See if allowed to query - 2) See if User is allowed - */ - Result> in = mapper.perms(trans, perms); - if(in.isOKhasData()) { - List out = rlpd.value; - boolean ok; - for(PermDAO.Data pdd : in.value) { - ok = false; - if("access".equals(pdd.type)) { - Access access = Access.valueOf(pdd.action); - String[] mdkey = Split.splitTrim(':',pdd.instance); - if(mdkey.length>1) { - String type = mdkey[1]; - if("role".equals(type)) { - if(mdkey.length>2) { - RoleDAO.Data rdd = new RoleDAO.Data(); - rdd.ns=pdd.ns; - rdd.name=mdkey[2]; - ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK(); - } - } else if("perm".equals(type)) { - if(mdkey.length>4) { // also need instance/action - PermDAO.Data p = new PermDAO.Data(); - p.ns=pdd.ns; - p.type=mdkey[2]; - p.instance=mdkey[3]; - p.action=mdkey[4]; - ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK(); - } - } else if("ns".equals(type)) { - NsDAO.Data ndd = new NsDAO.Data(); - ndd.name=pdd.ns; - ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK(); - } - } - } - if(ok) { - out.add(pdd); - } - } - } - - perms = mapper.newInstance(API.PERMS); - if(rlpd.isEmpty()) { - return Result.ok(perms); - } - // Note: Mapper will restrict what can be viewed - // if user is the same as that which is looked up, no filtering is required - return mapper.perms(trans, rlpd.value, - perms, - !user.equals(trans.user())); - } - - @ApiDoc( - method = GET, - path = "/authz/perms/role/:role", - params = {"role|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "List All Permissions that are granted to :role" } - ) - @Override - public Result getPermsByRole(AuthzTrans trans,String role) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role", role).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rrdd = RoleDAO.Data.decode(trans, ques,role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - Result r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); - if(r.notOK()) { - return Result.err(r); - } - - PERMS perms = mapper.newInstance(API.PERMS); - - Result> rlpd = ques.getPermsByRole(trans, role, trans.requested(force)); - if(rlpd.isOKhasData()) { - // Note: Mapper will restrict what can be viewed - return mapper.perms(trans, rlpd.value, perms, true); - } - return Result.ok(perms); - } - - @ApiDoc( - method = GET, - path = "/authz/perms/ns/:ns", - params = {"ns|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "List All Permissions that are in Namespace :ns" } - ) - @Override - public Result getPermsByNS(AuthzTrans trans,String ns) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", ns).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rnd = ques.deriveNs(trans, ns); - if(rnd.notOK()) { - return Result.err(rnd); - } - - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - Result> rlpd = ques.permDAO.readNS(trans, ns); - if(rlpd.notOK()) { - return Result.err(rlpd); - } - - PERMS perms = mapper.newInstance(API.PERMS); - if(!rlpd.isEmpty()) { - // Note: Mapper will restrict what can be viewed - return mapper.perms(trans, rlpd.value,perms, true); - } - return Result.ok(perms); - } - - @ApiDoc( - method = PUT, - path = "/authz/perm/:type/:instance/:action", - params = {"type|string|true", - "instance|string|true", - "action|string|true"}, - expectedCode = 200, - errorCodes = { 404,406, 409 }, - text = { "Rename the Permission referenced by :type :instance :action, and " - + "rename (copy/delete) to the Permission described in PermRequest" } - ) - @Override - public Result renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) { - final Result newPd = mapper.perm(trans, rreq); - final ServiceValidator v = new ServiceValidator(); - if(v.perm(newPd).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) { - return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", - newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action); - } - - Result nss = ques.deriveNsSplit(trans, origType); - Result> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction); - - if(origRlpd.notOKorIsEmpty()) { - return Result.err(Status.ERR_PermissionNotFound, - "Permission [%s|%s|%s] does not exist", - origType,origInstance,origAction); - } - - PermDAO.Data origPd = origRlpd.value.get(0); - - if (!origPd.ns.equals(newPd.value.ns)) { - return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " + - " must start with [" + origPd.ns + "]"); - } - - if ( origPd.type.equals(newPd.value.type) && - origPd.action.equals(newPd.value.action) && - origPd.instance.equals(newPd.value.instance) ) { - return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission"); - } - - Set origRoles = origPd.roles(false); - if (!origRoles.isEmpty()) { - Set roles = newPd.value.roles(true); - for (String role : origPd.roles) { - roles.add(role); - } - } - - newPd.value.description = origPd.description; - - Result rv = null; - - rv = func.createPerm(trans, newPd.value, false); - if (rv.isOK()) { - rv = func.deletePerm(trans, origPd, true, false); - } - return rv; - } - - @ApiDoc( - method = PUT, - path = "/authz/perm", - params = {}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "Add Description Data to Perm" } - ) - @Override - public Result updatePermDescription(AuthzTrans trans, REQUEST from) { - final Result pd = mapper.perm(trans, from); - final ServiceValidator v = new ServiceValidator(); - if(v.perm(pd).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - if(v.nullOrBlank("description", pd.value.description).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - final PermDAO.Data perm = pd.value; - if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) { - return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist", - perm.ns,perm.type,perm.instance,perm.action); - } - - if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) { - return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", - perm.ns,perm.type,perm.instance,perm.action); - } - - Result> nsr = ques.nsDAO.read(trans, pd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance, - perm.action, perm.description); - if(rdr.isOK()) { - return Result.ok(); - } else { - return Result.err(rdr); - } - - } - + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object, boolean, java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List) + */ + @ApiDoc( + method = POST, + path = "/authz/perm", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "Permission consists of:", + "
    • type - a Namespace qualified identifier specifying what kind of resource " + + "is being protected
    • ", + "
    • instance - a key, possibly multi-dimensional, that identifies a specific " + + " instance of the type
    • ", + "
    • action - what kind of action is allowed
    ", + "Note: instance and action can be an *" + } + ) + @Override + public Result createPerm(final AuthzTrans trans,REQUEST rreq) { + final Result newPd = mapper.perm(trans, rreq); + final ServiceValidator v = new ServiceValidator(); + if(v.perm(newPd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false, + new Mapper.Memo() { + @Override + public String get() { + return "Create Permission [" + + newPd.value.fullType() + '|' + + newPd.value.instance + '|' + + newPd.value.action + ']'; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write); + } + return nsd; + } + }); + Result> nsr = ques.nsDAO.read(trans, newPd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans,fd.value, + newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action, + trans.user(), + nsr.value.get(0), + FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", + newPd.value.ns, + newPd.value.type, + newPd.value.instance, + newPd.value.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.createPerm(trans, newPd.value, true); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = GET, + path = "/authz/perms/:type", + params = {"type|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match the :type element of the key" } + ) + @Override + public Result getPermsByType(AuthzTrans trans, final String permType) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("PermType", permType).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlpd = ques.getPermsByType(trans, permType); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + +// We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper? +// Result r; +// if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r); + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/:type/:instance/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List Permissions that match key; :type, :instance and :action" } + ) + @Override + public Result getPermsByName(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("PermType", type).err() + || v.nullOrBlank("PermInstance", instance).err() + || v.nullOrBlank("PermAction", action).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlpd = ques.getPermsByName(trans, type, instance, action); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/user/:user", + params = {"user|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user", + "

    'user' must be expressed as full identity (ex: id@full.domain.com)

    "} + ) + @Override + public Result getPermsByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlpd = ques.getPermsByUser(trans, user, + trans.requested(force)); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + !user.equals(trans.user())); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/user/:user/scope/:scope", + params = {"user|string|true","scope|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user, filtered by NS (Scope)", + "

    'user' must be expressed as full identity (ex: id@full.domain.com)

    ", + "

    'scope' must be expressed as NSs separated by ':'

    " + } + ) + @Override + public Result getPermsByUserScope(AuthzTrans trans, String user, String[] scopes) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlpd = ques.getPermsByUser(trans, user, trans.requested(force)); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + scopes, + !user.equals(trans.user())); + } + + @ApiDoc( + method = POST, + path = "/authz/perms/user/:user", + params = {"user|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user", + "

    'user' must be expressed as full identity (ex: id@full.domain.com)

    ", + "", + "Present Queries as one or more Permissions (see ContentType Links below for format).", + "", + "If the Caller is Granted this specific Permission, and the Permission is valid", + " for the User, it will be included in response Permissions, along with", + " all the normal permissions on the 'GET' version of this call. If it is not", + " valid, or Caller does not have permission to see, it will be removed from the list", + "", + " *Note: This design allows you to make one call for all expected permissions", + " The permission to be included MUST be:", + " .access|:[:key]|", + " examples:", + " com.att.myns.access|:ns|write", + " com.att.myns.access|:role:myrole|create", + " com.att.myns.access|:perm:mytype:myinstance:myaction|read", + "" + } + ) + @Override + public Result getPermsByUser(AuthzTrans trans, PERMS _perms, String user) { + PERMS perms = _perms; + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + ////////////// + Result> rlpd = ques.getPermsByUser(trans, user,trans.requested(force)); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + /*//TODO + 1) See if allowed to query + 2) See if User is allowed + */ + Result> in = mapper.perms(trans, perms); + if(in.isOKhasData()) { + List out = rlpd.value; + boolean ok; + for(PermDAO.Data pdd : in.value) { + ok = false; + if("access".equals(pdd.type)) { + Access access = Access.valueOf(pdd.action); + String[] mdkey = Split.splitTrim(':',pdd.instance); + if(mdkey.length>1) { + String type = mdkey[1]; + if("role".equals(type)) { + if(mdkey.length>2) { + RoleDAO.Data rdd = new RoleDAO.Data(); + rdd.ns=pdd.ns; + rdd.name=mdkey[2]; + ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK(); + } + } else if("perm".equals(type)) { + if(mdkey.length>4) { // also need instance/action + PermDAO.Data p = new PermDAO.Data(); + p.ns=pdd.ns; + p.type=mdkey[2]; + p.instance=mdkey[3]; + p.action=mdkey[4]; + ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK(); + } + } else if("ns".equals(type)) { + NsDAO.Data ndd = new NsDAO.Data(); + ndd.name=pdd.ns; + ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK(); + } + } + } + if(ok) { + out.add(pdd); + } + } + } + + perms = mapper.newInstance(API.PERMS); + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + !user.equals(trans.user())); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/role/:role", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that are granted to :role" } + ) + @Override + public Result getPermsByRole(AuthzTrans trans,String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role", role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rrdd = RoleDAO.Data.decode(trans, ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + Result r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); + if(r.notOK()) { + return Result.err(r); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + Result> rlpd = ques.getPermsByRole(trans, role, trans.requested(force)); + if(rlpd.isOKhasData()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/ns/:ns", + params = {"ns|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that are in Namespace :ns" } + ) + @Override + public Result getPermsByNS(AuthzTrans trans,String ns) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rnd = ques.deriveNs(trans, ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Result> rlpd = ques.permDAO.readNS(trans, ns); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value,perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = PUT, + path = "/authz/perm/:type/:instance/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406, 409 }, + text = { "Rename the Permission referenced by :type :instance :action, and " + + "rename (copy/delete) to the Permission described in PermRequest" } + ) + @Override + public Result renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) { + final Result newPd = mapper.perm(trans, rreq); + final ServiceValidator v = new ServiceValidator(); + if(v.perm(newPd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", + newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action); + } + + Result nss = ques.deriveNsSplit(trans, origType); + Result> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction); + + if(origRlpd.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s|%s|%s] does not exist", + origType,origInstance,origAction); + } + + PermDAO.Data origPd = origRlpd.value.get(0); + + if (!origPd.ns.equals(newPd.value.ns)) { + return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " + + " must start with [" + origPd.ns + "]"); + } + + if ( origPd.type.equals(newPd.value.type) && + origPd.action.equals(newPd.value.action) && + origPd.instance.equals(newPd.value.instance) ) { + return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission"); + } + + Set origRoles = origPd.roles(false); + if (!origRoles.isEmpty()) { + Set roles = newPd.value.roles(true); + for (String role : origPd.roles) { + roles.add(role); + } + } + + newPd.value.description = origPd.description; + + Result rv = null; + + rv = func.createPerm(trans, newPd.value, false); + if (rv.isOK()) { + rv = func.deletePerm(trans, origPd, true, false); + } + return rv; + } + + @ApiDoc( + method = PUT, + path = "/authz/perm", + params = {}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Add Description Data to Perm" } + ) + @Override + public Result updatePermDescription(AuthzTrans trans, REQUEST from) { + final Result pd = mapper.perm(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.perm(pd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + if(v.nullOrBlank("description", pd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final PermDAO.Data perm = pd.value; + if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist", + perm.ns,perm.type,perm.instance,perm.action); + } + + if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", + perm.ns,perm.type,perm.instance,perm.action); + } + + Result> nsr = ques.nsDAO.read(trans, pd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance, + perm.action, perm.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + + } + @ApiDoc( method = PUT, path = "/authz/role/perm", @@ -1270,192 +1270,192 @@ public class AuthzCassServiceImpl resetPermRoles(final AuthzTrans trans, REQUEST rreq) { - final Result updt = mapper.permFromRPRequest(trans, rreq); - if(updt.notOKorIsEmpty()) { - return Result.err(updt); - } - - final ServiceValidator v = new ServiceValidator(); - if(v.perm(updt).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write); - if (nsd.notOK()) { - return Result.err(nsd); - } - - // Read full set to get CURRENT values - Result> rcurr = ques.permDAO.read(trans, - updt.value.ns, - updt.value.type, - updt.value.instance, - updt.value.action); - - if(rcurr.notOKorIsEmpty()) { - return Result.err(Status.ERR_PermissionNotFound, - "Permission [%s.%s|%s|%s] does not exist", - updt.value.ns,updt.value.type,updt.value.instance,updt.value.action); - } - - // Create a set of Update Roles, which are in Internal Format - Set updtRoles = new HashSet<>(); - Result nss; - for(String role : updt.value.roles(false)) { - nss = ques.deriveNsSplit(trans, role); - if(nss.isOK()) { - updtRoles.add(nss.value.ns + '|' + nss.value.name); - } else { - trans.error().log(nss.errorString()); - } - } - - Result rv = null; - - for(PermDAO.Data curr : rcurr.value) { - Set currRoles = curr.roles(false); - // must add roles to this perm, and add this perm to each role - // in the update, but not in the current - for (String role : updtRoles) { - if (!currRoles.contains(role)) { - Result key = RoleDAO.Data.decode(trans, ques, role); - if(key.isOKhasData()) { - Result> rrd = ques.roleDAO.read(trans, key.value); - if(rrd.isOKhasData()) { - for(RoleDAO.Data r : rrd.value) { - rv = func.addPermToRole(trans, r, curr, false); - if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) { - return Result.err(rv); - } - } - } else { - return Result.err(rrd); - } - } - } - } - // similarly, must delete roles from this perm, and delete this perm from each role - // in the update, but not in the current - for (String role : currRoles) { - if (!updtRoles.contains(role)) { - Result key = RoleDAO.Data.decode(trans, ques, role); - if(key.isOKhasData()) { - Result> rdd = ques.roleDAO.read(trans, key.value); - if(rdd.isOKhasData()) { - for(RoleDAO.Data r : rdd.value) { - rv = func.delPermFromRole(trans, r, curr, true); - if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) { - return Result.err(rv); - } - } - } - } - } - } - } - return rv==null?Result.ok():rv; - } - - @ApiDoc( - method = DELETE, - path = "/authz/perm", - params = {}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "Delete the Permission referenced by PermKey.", - "You cannot normally delete a permission which is still granted to roles,", - "however the \"force\" property allows you to do just that. To do this: Add", - "'force=true' as a query parameter.", - "

    WARNING: Using force will ungrant this permission from all roles. Use with care.

    " } - ) - @Override - public Result deletePerm(final AuthzTrans trans, REQUEST from) { - Result pd = mapper.perm(trans, from); - if(pd.notOK()) { - return Result.err(pd); - } - final ServiceValidator v = new ServiceValidator(); - if(v.nullOrBlank(pd.value).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - final PermDAO.Data perm = pd.value; - if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) { - return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist", - perm.ns,perm.type,perm.instance,perm.action ); - } - - Result fd = mapper.future(trans,PermDAO.TABLE,from,perm,false, - new Mapper.Memo() { - @Override - public String get() { - return "Delete Permission [" + perm.fullPerm() + ']'; - } - }, - new MayChange() { - private Result nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), perm, Access.write); - } - return nsd; - } - }); - - switch(fd.status) { - case OK: - Result> nsr = ques.nsDAO.read(trans, perm.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result rfc = func.createFuture(trans, fd.value, - perm.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode()); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - return func.deletePerm(trans,perm,trans.requested(force), false); - default: - return Result.err(fd); - } - } - - @ApiDoc( - method = DELETE, - path = "/authz/perm/:name/:type/:action", - params = {"type|string|true", - "instance|string|true", - "action|string|true"}, - expectedCode = 200, - errorCodes = { 404,406 }, - text = { "Delete the Permission referenced by :type :instance :action", - "You cannot normally delete a permission which is still granted to roles,", - "however the \"force\" property allows you to do just that. To do this: Add", - "'force=true' as a query parameter", - "

    WARNING: Using force will ungrant this permission from all roles. Use with care.

    "} - ) - @Override - public Result deletePerm(AuthzTrans trans, String type, String instance, String action) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Type",type) - .nullOrBlank("Instance",instance) - .nullOrBlank("Action",action) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result pd = ques.permFrom(trans, type, instance, action); - if(pd.isOK()) { - return func.deletePerm(trans, pd.value, trans.requested(force), false); - } else { - return Result.err(pd); - } - } + @Override + public Result resetPermRoles(final AuthzTrans trans, REQUEST rreq) { + final Result updt = mapper.permFromRPRequest(trans, rreq); + if(updt.notOKorIsEmpty()) { + return Result.err(updt); + } + + final ServiceValidator v = new ServiceValidator(); + if(v.perm(updt).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write); + if (nsd.notOK()) { + return Result.err(nsd); + } + + // Read full set to get CURRENT values + Result> rcurr = ques.permDAO.read(trans, + updt.value.ns, + updt.value.type, + updt.value.instance, + updt.value.action); + + if(rcurr.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s.%s|%s|%s] does not exist", + updt.value.ns,updt.value.type,updt.value.instance,updt.value.action); + } + + // Create a set of Update Roles, which are in Internal Format + Set updtRoles = new HashSet<>(); + Result nss; + for(String role : updt.value.roles(false)) { + nss = ques.deriveNsSplit(trans, role); + if(nss.isOK()) { + updtRoles.add(nss.value.ns + '|' + nss.value.name); + } else { + trans.error().log(nss.errorString()); + } + } + + Result rv = null; + + for(PermDAO.Data curr : rcurr.value) { + Set currRoles = curr.roles(false); + // must add roles to this perm, and add this perm to each role + // in the update, but not in the current + for (String role : updtRoles) { + if (!currRoles.contains(role)) { + Result key = RoleDAO.Data.decode(trans, ques, role); + if(key.isOKhasData()) { + Result> rrd = ques.roleDAO.read(trans, key.value); + if(rrd.isOKhasData()) { + for(RoleDAO.Data r : rrd.value) { + rv = func.addPermToRole(trans, r, curr, false); + if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) { + return Result.err(rv); + } + } + } else { + return Result.err(rrd); + } + } + } + } + // similarly, must delete roles from this perm, and delete this perm from each role + // in the update, but not in the current + for (String role : currRoles) { + if (!updtRoles.contains(role)) { + Result key = RoleDAO.Data.decode(trans, ques, role); + if(key.isOKhasData()) { + Result> rdd = ques.roleDAO.read(trans, key.value); + if(rdd.isOKhasData()) { + for(RoleDAO.Data r : rdd.value) { + rv = func.delPermFromRole(trans, r, curr, true); + if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) { + return Result.err(rv); + } + } + } + } + } + } + } + return rv==null?Result.ok():rv; + } + + @ApiDoc( + method = DELETE, + path = "/authz/perm", + params = {}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Delete the Permission referenced by PermKey.", + "You cannot normally delete a permission which is still granted to roles,", + "however the \"force\" property allows you to do just that. To do this: Add", + "'force=true' as a query parameter.", + "

    WARNING: Using force will ungrant this permission from all roles. Use with care.

    " } + ) + @Override + public Result deletePerm(final AuthzTrans trans, REQUEST from) { + Result pd = mapper.perm(trans, from); + if(pd.notOK()) { + return Result.err(pd); + } + final ServiceValidator v = new ServiceValidator(); + if(v.nullOrBlank(pd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final PermDAO.Data perm = pd.value; + if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist", + perm.ns,perm.type,perm.instance,perm.action ); + } + + Result fd = mapper.future(trans,PermDAO.TABLE,from,perm,false, + new Mapper.Memo() { + @Override + public String get() { + return "Delete Permission [" + perm.fullPerm() + ']'; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), perm, Access.write); + } + return nsd; + } + }); + + switch(fd.status) { + case OK: + Result> nsr = ques.nsDAO.read(trans, perm.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result rfc = func.createFuture(trans, fd.value, + perm.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode()); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.deletePerm(trans,perm,trans.requested(force), false); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = DELETE, + path = "/authz/perm/:name/:type/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Delete the Permission referenced by :type :instance :action", + "You cannot normally delete a permission which is still granted to roles,", + "however the \"force\" property allows you to do just that. To do this: Add", + "'force=true' as a query parameter", + "

    WARNING: Using force will ungrant this permission from all roles. Use with care.

    "} + ) + @Override + public Result deletePerm(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Type",type) + .nullOrBlank("Instance",instance) + .nullOrBlank("Action",action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result pd = ques.permFrom(trans, type, instance, action); + if(pd.isOK()) { + return func.deletePerm(trans, pd.value, trans.requested(force), false); + } else { + return Result.err(pd); + } + } /*********************************** * ROLE @@ -1481,69 +1481,69 @@ public class AuthzCassServiceImpl 'Does this person perform this Job Function?'" } ) - @Override - public Result createRole(final AuthzTrans trans, REQUEST from) { - final Result rd = mapper.role(trans, from); - final ServiceValidator v = new ServiceValidator(); - if(v.role(rd).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - final RoleDAO.Data role = rd.value; - if(ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists"); - } - - Result fd = mapper.future(trans,RoleDAO.TABLE,from,role,false, - new Mapper.Memo() { - @Override - public String get() { - return "Create Role [" + - rd.value.fullName() + - ']'; - } - }, - new MayChange() { - private Result nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), role, Access.write); - } - return nsd; - } - }); - - Result> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans, fd.value, - role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.C); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing", - rd.value.ns, - rd.value.name); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - Result rdr = ques.roleDAO.create(trans, role); - if(rdr.isOK()) { - return Result.ok(); - } else { - return Result.err(rdr); - } - default: - return Result.err(fd); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) - */ + @Override + public Result createRole(final AuthzTrans trans, REQUEST from) { + final Result rd = mapper.role(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.role(rd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final RoleDAO.Data role = rd.value; + if(ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists"); + } + + Result fd = mapper.future(trans,RoleDAO.TABLE,from,role,false, + new Mapper.Memo() { + @Override + public String get() { + return "Create Role [" + + rd.value.fullName() + + ']'; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), role, Access.write); + } + return nsd; + } + }); + + Result> nsr = ques.nsDAO.read(trans, rd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans, fd.value, + role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing", + rd.value.ns, + rd.value.name); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Result rdr = ques.roleDAO.create(trans, role); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + default: + return Result.err(fd); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ @ApiDoc( method = GET, path = "/authz/roles/:role", @@ -1551,42 +1551,42 @@ public class AuthzCassServiceImpl getRolesByName(AuthzTrans trans, String role) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role", role).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // Determine if User can ask this question - Result rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.isOKhasData()) { - Result r; - if((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) { - return Result.err(r); - } - } else { - return Result.err(rrdd); - } - - // Look up data - int query = role.indexOf('?'); - Result> rlrd = ques.getRolesByName(trans, query<0?role:role.substring(0, query)); - if(rlrd.isOK()) { - // Note: Mapper will restrict what can be viewed - ROLES roles = mapper.newInstance(API.ROLES); - return mapper.roles(trans, rlrd.value, roles, true); - } else { - return Result.err(rlrd); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) - */ + @Override + public Result getRolesByName(AuthzTrans trans, String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role", role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Determine if User can ask this question + Result rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.isOKhasData()) { + Result r; + if((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) { + return Result.err(r); + } + } else { + return Result.err(rrdd); + } + + // Look up data + int query = role.indexOf('?'); + Result> rlrd = ques.getRolesByName(trans, query<0?role:role.substring(0, query)); + if(rlrd.isOK()) { + // Note: Mapper will restrict what can be viewed + ROLES roles = mapper.newInstance(API.ROLES); + return mapper.roles(trans, rlrd.value, roles, true); + } else { + return Result.err(rlrd); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ @ApiDoc( method = GET, path = "/authz/roles/user/:name", @@ -1594,39 +1594,39 @@ public class AuthzCassServiceImpl getRolesByUser(AuthzTrans trans, String user) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - ROLES roles = mapper.newInstance(API.ROLES); - // Get list of roles per user, then add to Roles as we go - Result> rlrd; - Result> rlurd = ques.userRoleDAO.readByUser(trans, user); - if(rlurd.isOKhasData()) { - for(UserRoleDAO.Data urd : rlurd.value ) { - rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname); - // Note: Mapper will restrict what can be viewed - // if user is the same as that which is looked up, no filtering is required - if(rlrd.isOKhasData()) { - mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user())); - } - } - } - return Result.ok(roles); - } - - /* - * (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) - */ + @Override + public Result getRolesByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result> rlrd; + Result> rlurd = ques.userRoleDAO.readByUser(trans, user); + if(rlurd.isOKhasData()) { + for(UserRoleDAO.Data urd : rlurd.value ) { + rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname); + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + if(rlrd.isOKhasData()) { + mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user())); + } + } + } + return Result.ok(roles); + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ @ApiDoc( method = GET, path = "/authz/roles/ns/:ns", @@ -1634,50 +1634,50 @@ public class AuthzCassServiceImpl getRolesByNS(AuthzTrans trans, String ns) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", ns).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // check if user is allowed to view NS - Result rnsd = ques.deriveNs(trans, ns); - if(rnsd.notOK()) { - return Result.err(rnsd); - } - rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read); - if(rnsd.notOK()) { - return Result.err(rnsd); - } - - TimeTaken tt = trans.start("MAP Roles by NS to Roles", Env.SUB); - try { - ROLES roles = mapper.newInstance(API.ROLES); - // Get list of roles per user, then add to Roles as we go - Result> rlrd = ques.roleDAO.readNS(trans, ns); - if(rlrd.isOK()) { - if(!rlrd.isEmpty()) { - // Note: Mapper doesn't need to restrict what can be viewed, because we did it already. - mapper.roles(trans,rlrd.value,roles,false); - } - return Result.ok(roles); - } else { - return Result.err(rlrd); - } - } finally { - tt.done(); - } - } - - /* - * (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) - */ + @Override + public Result getRolesByNS(AuthzTrans trans, String ns) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // check if user is allowed to view NS + Result rnsd = ques.deriveNs(trans, ns); + if(rnsd.notOK()) { + return Result.err(rnsd); + } + rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read); + if(rnsd.notOK()) { + return Result.err(rnsd); + } + + TimeTaken tt = trans.start("MAP Roles by NS to Roles", Env.SUB); + try { + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result> rlrd = ques.roleDAO.readNS(trans, ns); + if(rlrd.isOK()) { + if(!rlrd.isEmpty()) { + // Note: Mapper doesn't need to restrict what can be viewed, because we did it already. + mapper.roles(trans,rlrd.value,roles,false); + } + return Result.ok(roles); + } else { + return Result.err(rlrd); + } + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ @ApiDoc( method = GET, path = "/authz/roles/name/:name", @@ -1685,36 +1685,36 @@ public class AuthzCassServiceImpl getRolesByNameOnly(AuthzTrans trans, String name) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Name", name).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // User Mapper to make sure user is allowed to view NS - - TimeTaken tt = trans.start("MAP Roles by Name to Roles", Env.SUB); - try { - ROLES roles = mapper.newInstance(API.ROLES); - // Get list of roles per user, then add to Roles as we go - Result> rlrd = ques.roleDAO.readName(trans, name); - if(rlrd.isOK()) { - if(!rlrd.isEmpty()) { - // Note: Mapper will restrict what can be viewed - mapper.roles(trans,rlrd.value,roles,true); - } - return Result.ok(roles); - } else { - return Result.err(rlrd); - } - } finally { - tt.done(); - } - } + @Override + public Result getRolesByNameOnly(AuthzTrans trans, String name) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Name", name).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // User Mapper to make sure user is allowed to view NS + + TimeTaken tt = trans.start("MAP Roles by Name to Roles", Env.SUB); + try { + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result> rlrd = ques.roleDAO.readName(trans, name); + if(rlrd.isOK()) { + if(!rlrd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + mapper.roles(trans,rlrd.value,roles,true); + } + return Result.ok(roles); + } else { + return Result.err(rlrd); + } + } finally { + tt.done(); + } + } @ApiDoc( method = GET, @@ -1732,52 +1732,52 @@ public class AuthzCassServiceImpl ", "
  • action - what kind of action is allowed
  • ", "Notes: instance and action can be an *", - " You must have permission to see any given role" + " You must have permission to see any given role" } ) - @Override - public Result getRolesByPerm(AuthzTrans trans, String type, String instance, String action) { - final Validator v = new ServiceValidator(); - if(v.permType(type) - .permInstance(instance) - .permAction(action) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - TimeTaken tt = trans.start("Map Perm Roles Roles", Env.SUB); - try { - ROLES roles = mapper.newInstance(API.ROLES); - // Get list of roles per user, then add to Roles as we go - Result nsSplit = ques.deriveNsSplit(trans, type); - if(nsSplit.isOK()) { - PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action); - Result res; - if((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) { - return Result.err(res); - } - - Result> pdlr = ques.permDAO.read(trans, pdd); - if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) { - Result> rlrd; - for(String r : pd.roles) { - Result rs = RoleDAO.Data.decodeToArray(trans, ques, r); - if(rs.isOK()) { - rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]); - // Note: Mapper will restrict what can be viewed - if(rlrd.isOKhasData()) { - mapper.roles(trans,rlrd.value,roles,true); - } - } - } - } - } - return Result.ok(roles); - } finally { - tt.done(); - } - } + @Override + public Result getRolesByPerm(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.permType(type) + .permInstance(instance) + .permAction(action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + TimeTaken tt = trans.start("Map Perm Roles Roles", Env.SUB); + try { + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result nsSplit = ques.deriveNsSplit(trans, type); + if(nsSplit.isOK()) { + PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action); + Result res; + if((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) { + return Result.err(res); + } + + Result> pdlr = ques.permDAO.read(trans, pdd); + if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) { + Result> rlrd; + for(String r : pd.roles) { + Result rs = RoleDAO.Data.decodeToArray(trans, ques, r); + if(rs.isOK()) { + rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]); + // Note: Mapper will restrict what can be viewed + if(rlrd.isOKhasData()) { + mapper.roles(trans,rlrd.value,roles,true); + } + } + } + } + } + return Result.ok(roles); + } finally { + tt.done(); + } + } @ApiDoc( method = PUT, @@ -1788,40 +1788,40 @@ public class AuthzCassServiceImpl updateRoleDescription(AuthzTrans trans, REQUEST from) { - final Result rd = mapper.role(trans, from); - final ServiceValidator v = new ServiceValidator(); - if(v.role(rd).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } { - if(v.nullOrBlank("description", rd.value.description).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - } - final RoleDAO.Data role = rd.value; - if(ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) { - return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist"); - } - - if (ques.mayUser(trans, trans.user(), role, Access.write).notOK()) { - return Result.err(Status.ERR_Denied, "You do not have approval to change " + role.fullName()); - } - - Result> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description); - if(rdr.isOK()) { - return Result.ok(); - } else { - return Result.err(rdr); - } - - } - + @Override + public Result updateRoleDescription(AuthzTrans trans, REQUEST from) { + final Result rd = mapper.role(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.role(rd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } { + if(v.nullOrBlank("description", rd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + } + final RoleDAO.Data role = rd.value; + if(ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist"); + } + + if (ques.mayUser(trans, trans.user(), role, Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change " + role.fullName()); + } + + Result> nsr = ques.nsDAO.read(trans, rd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + + } + @ApiDoc( method = POST, path = "/authz/role/perm", @@ -1839,117 +1839,117 @@ public class AuthzCassServiceImpl addPermToRole(final AuthzTrans trans, REQUEST rreq) { - // Translate Request into Perm and Role Objects - final Result rpd = mapper.permFromRPRequest(trans, rreq); - if(rpd.notOKorIsEmpty()) { - return Result.err(rpd); - } - final Result rrd = mapper.roleFromRPRequest(trans, rreq); - if(rrd.notOKorIsEmpty()) { - return Result.err(rrd); - } - - // Validate Role and Perm values - final ServiceValidator v = new ServiceValidator(); - if(v.perm(rpd.value) - .role(rrd.value) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name); - if(rlrd.notOKorIsEmpty()) { - return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName()); - } - - // Check Status of Data in DB (does it exist) - Result> rlpd = ques.permDAO.read(trans, rpd.value.ns, - rpd.value.type, rpd.value.instance, rpd.value.action); - PermDAO.Data createPerm = null; // if not null, create first - if(rlpd.notOKorIsEmpty()) { // Permission doesn't exist - if(trans.requested(force)) { - // Remove roles from perm data object so we just create the perm here - createPerm = rpd.value; - createPerm.roles.clear(); - } else { - return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist", - rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action); - } - } else { - if (rlpd.value.get(0).roles(false).contains(rrd.value.encode())) { - return Result.err(Status.ERR_ConflictAlreadyExists, - "Permission [%s.%s|%s|%s] already granted to Role [%s.%s]", - rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action, - rrd.value.ns,rrd.value.name - ); - } - } - - - Result fd = mapper.future(trans, PermDAO.TABLE, rreq, rpd.value,true, // Allow grants to create Approvals - new Mapper.Memo() { - @Override - public String get() { - return "Grant Permission [" + rpd.value.fullPerm() + ']' + - " to Role [" + rrd.value.fullName() + "]"; - } - }, - new MayChange() { - private Result nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write); - } - return nsd; - } - }); - Result> nsr = ques.nsDAO.read(trans, rpd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans,fd.value, - rpd.value.fullPerm(), - trans.user(), - nsr.value.get(0), - FUTURE_OP.G); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", - rpd.value.ns, - rpd.value.type, - rpd.value.instance, - rpd.value.action); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - Result rv = null; - if(createPerm!=null) {// has been validated for creating - rv = func.createPerm(trans, createPerm, false); - } - if(rv==null || rv.isOK()) { - rv = func.addPermToRole(trans, rrd.value, rpd.value, false); - } - return rv; - default: - return Result.err(fd); - } - - } - - /** - * Delete Perms from Roles (UnGrant) - * @param trans - * @param roleFullName - * @return - */ + @Override + public Result addPermToRole(final AuthzTrans trans, REQUEST rreq) { + // Translate Request into Perm and Role Objects + final Result rpd = mapper.permFromRPRequest(trans, rreq); + if(rpd.notOKorIsEmpty()) { + return Result.err(rpd); + } + final Result rrd = mapper.roleFromRPRequest(trans, rreq); + if(rrd.notOKorIsEmpty()) { + return Result.err(rrd); + } + + // Validate Role and Perm values + final ServiceValidator v = new ServiceValidator(); + if(v.perm(rpd.value) + .role(rrd.value) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name); + if(rlrd.notOKorIsEmpty()) { + return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName()); + } + + // Check Status of Data in DB (does it exist) + Result> rlpd = ques.permDAO.read(trans, rpd.value.ns, + rpd.value.type, rpd.value.instance, rpd.value.action); + PermDAO.Data createPerm = null; // if not null, create first + if(rlpd.notOKorIsEmpty()) { // Permission doesn't exist + if(trans.requested(force)) { + // Remove roles from perm data object so we just create the perm here + createPerm = rpd.value; + createPerm.roles.clear(); + } else { + return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist", + rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action); + } + } else { + if (rlpd.value.get(0).roles(false).contains(rrd.value.encode())) { + return Result.err(Status.ERR_ConflictAlreadyExists, + "Permission [%s.%s|%s|%s] already granted to Role [%s.%s]", + rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action, + rrd.value.ns,rrd.value.name + ); + } + } + + + Result fd = mapper.future(trans, PermDAO.TABLE, rreq, rpd.value,true, // Allow grants to create Approvals + new Mapper.Memo() { + @Override + public String get() { + return "Grant Permission [" + rpd.value.fullPerm() + ']' + + " to Role [" + rrd.value.fullName() + "]"; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write); + } + return nsd; + } + }); + Result> nsr = ques.nsDAO.read(trans, rpd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans,fd.value, + rpd.value.fullPerm(), + trans.user(), + nsr.value.get(0), + FUTURE_OP.G); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", + rpd.value.ns, + rpd.value.type, + rpd.value.instance, + rpd.value.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Result rv = null; + if(createPerm!=null) {// has been validated for creating + rv = func.createPerm(trans, createPerm, false); + } + if(rv==null || rv.isOK()) { + rv = func.addPermToRole(trans, rrd.value, rpd.value, false); + } + return rv; + default: + return Result.err(fd); + } + + } + + /** + * Delete Perms from Roles (UnGrant) + * @param trans + * @param roleFullName + * @return + */ @ApiDoc( method = DELETE, path = "/authz/role/:role/perm", @@ -1959,132 +1959,132 @@ public class AuthzCassServiceImpl delPermFromRole(final AuthzTrans trans, REQUEST rreq) { - final Result updt = mapper.permFromRPRequest(trans, rreq); - if(updt.notOKorIsEmpty()) { - return Result.err(updt); - } - final Result rrd = mapper.roleFromRPRequest(trans, rreq); - if(rrd.notOKorIsEmpty()) { - return Result.err(rrd); - } - - final ServiceValidator v = new ServiceValidator(); - if(v.nullOrBlank(updt.value) - .nullOrBlank(rrd.value) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - return delPermFromRole(trans, updt.value,rrd.value, rreq); + @Override + public Result delPermFromRole(final AuthzTrans trans, REQUEST rreq) { + final Result updt = mapper.permFromRPRequest(trans, rreq); + if(updt.notOKorIsEmpty()) { + return Result.err(updt); + } + final Result rrd = mapper.roleFromRPRequest(trans, rreq); + if(rrd.notOKorIsEmpty()) { + return Result.err(rrd); + } + + final ServiceValidator v = new ServiceValidator(); + if(v.nullOrBlank(updt.value) + .nullOrBlank(rrd.value) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + return delPermFromRole(trans, updt.value,rrd.value, rreq); + } + + private Result delPermFromRole(final AuthzTrans trans, PermDAO.Data pdd, RoleDAO.Data rdd, REQUEST rreq) { + Result> rlpd = ques.permDAO.read(trans, pdd.ns, pdd.type, + pdd.instance, pdd.action); + + if(rlpd.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s.%s|%s|%s] does not exist", + pdd.ns,pdd.type,pdd.instance,pdd.action); + } + + Result fd = mapper.future(trans, PermDAO.TABLE, rreq, pdd,true, // allow ungrants requests + new Mapper.Memo() { + @Override + public String get() { + return "Ungrant Permission [" + pdd.fullPerm() + ']' + + " from Role [" + rdd.fullName() + "]"; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), pdd, Access.write); + } + return nsd; + } + }); + Result> nsr = ques.nsDAO.read(trans, pdd.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans,fd.value, + pdd.fullPerm(), + trans.user(), + nsr.value.get(0), + FUTURE_OP.UG + ); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", + pdd.ns, + pdd.type, + pdd.instance, + pdd.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.delPermFromRole(trans, rdd, pdd, false); + default: + return Result.err(fd); + } } - - private Result delPermFromRole(final AuthzTrans trans, PermDAO.Data pdd, RoleDAO.Data rdd, REQUEST rreq) { - Result> rlpd = ques.permDAO.read(trans, pdd.ns, pdd.type, - pdd.instance, pdd.action); - - if(rlpd.notOKorIsEmpty()) { - return Result.err(Status.ERR_PermissionNotFound, - "Permission [%s.%s|%s|%s] does not exist", - pdd.ns,pdd.type,pdd.instance,pdd.action); - } - - Result fd = mapper.future(trans, PermDAO.TABLE, rreq, pdd,true, // allow ungrants requests - new Mapper.Memo() { - @Override - public String get() { - return "Ungrant Permission [" + pdd.fullPerm() + ']' + - " from Role [" + rdd.fullName() + "]"; - } - }, - new MayChange() { - private Result nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), pdd, Access.write); - } - return nsd; - } - }); - Result> nsr = ques.nsDAO.read(trans, pdd.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans,fd.value, - pdd.fullPerm(), - trans.user(), - nsr.value.get(0), - FUTURE_OP.UG - ); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", - pdd.ns, - pdd.type, - pdd.instance, - pdd.action); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - return func.delPermFromRole(trans, rdd, pdd, false); - default: - return Result.err(fd); - } - } /* @ApiDoc( method = DELETE, path = "/authz/role/:role/perm/:type/:instance/:action", params = {"role|string|true", - "perm type|string|true", - "perm instance|string|true", - "perm action|string|true" - }, + "perm type|string|true", + "perm instance|string|true", + "perm action|string|true" + }, expectedCode = 200, errorCodes = {404,406}, text = { "Ungrant a single permission from Role :role with direct key" } ) */ - @Override + @Override public Result delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action) { - Result rpns = ques.deriveNs(trans, type); - if(rpns.notOKorIsEmpty()) { - return Result.err(rpns); - } - - final Validator v = new ServiceValidator(); - if(v.role(role) - .permType(rpns.value.name,rpns.value.parent) - .permInstance(instance) - .permAction(action) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rrns = ques.deriveNs(trans, role); - if(rrns.notOKorIsEmpty()) { - return Result.err(rrns); - } - - final Result> rrd = ques.roleDAO.read(trans, rrns.value.parent, rrns.value.name); - if(rrd.notOKorIsEmpty()) { - return Result.err(rrd); - } - - final Result> rpd = ques.permDAO.read(trans, rpns.value.parent, rpns.value.name, instance, action); - if(rpd.notOKorIsEmpty()) { - return Result.err(rpd); - } - - - return delPermFromRole(trans,rpd.value.get(0), rrd.value.get(0), mapper.ungrantRequest(trans, role, type, instance, action)); - } - + Result rpns = ques.deriveNs(trans, type); + if(rpns.notOKorIsEmpty()) { + return Result.err(rpns); + } + + final Validator v = new ServiceValidator(); + if(v.role(role) + .permType(rpns.value.name,rpns.value.parent) + .permInstance(instance) + .permAction(action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rrns = ques.deriveNs(trans, role); + if(rrns.notOKorIsEmpty()) { + return Result.err(rrns); + } + + final Result> rrd = ques.roleDAO.read(trans, rrns.value.parent, rrns.value.name); + if(rrd.notOKorIsEmpty()) { + return Result.err(rrd); + } + + final Result> rpd = ques.permDAO.read(trans, rpns.value.parent, rpns.value.name, instance, action); + if(rpd.notOKorIsEmpty()) { + return Result.err(rpd); + } + + + return delPermFromRole(trans,rpd.value.get(0), rrd.value.get(0), mapper.ungrantRequest(trans, role, type, instance, action)); + } + @ApiDoc( method = DELETE, path = "/authz/role/:role", @@ -2094,19 +2094,19 @@ public class AuthzCassServiceImpl deleteRole(AuthzTrans trans, String role) { - Result rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.isOKhasData()) { - final ServiceValidator v = new ServiceValidator(); - if(v.nullOrBlank(rrdd.value).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - return func.deleteRole(trans, rrdd.value, false, false); - } else { - return Result.err(rrdd); - } - } + @Override + public Result deleteRole(AuthzTrans trans, String role) { + Result rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.isOKhasData()) { + final ServiceValidator v = new ServiceValidator(); + if(v.nullOrBlank(rrdd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + return func.deleteRole(trans, rrdd.value, false, false); + } else { + return Result.err(rrdd); + } + } @ApiDoc( method = DELETE, @@ -2115,2134 +2115,2134 @@ public class AuthzCassServiceImpl WARNING: Using force will remove all users and permission from this role. Use with care.

    "} + "You cannot normally delete a role which still has permissions granted or users assigned to it,", + "however the \"force\" property allows you to do just that. To do this: Add 'force=true'", + "as a query parameter.", + "

    WARNING: Using force will remove all users and permission from this role. Use with care.

    "} ) - @Override - public Result deleteRole(final AuthzTrans trans, REQUEST from) { - final Result rd = mapper.role(trans, from); - final ServiceValidator v = new ServiceValidator(); - if(rd==null) { - return Result.err(Status.ERR_BadData,"Request does not contain Role"); - } - if(v.nullOrBlank(rd.value).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - final RoleDAO.Data role = rd.value; - if(ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) { - return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist"); - } - - Result fd = mapper.future(trans,RoleDAO.TABLE,from,role,false, - new Mapper.Memo() { - @Override - public String get() { - return "Delete Role [" + role.fullName() + ']' - + " and all attached user roles"; - } - }, - new MayChange() { - private Result nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), role, Access.write); - } - return nsd; - } - }); - - switch(fd.status) { - case OK: - Result> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result rfc = func.createFuture(trans, fd.value, - role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing", - rd.value.ns, - rd.value.name); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - return func.deleteRole(trans,role,trans.requested(force), true /*preapproved*/); - default: - return Result.err(fd); - } - - } + @Override + public Result deleteRole(final AuthzTrans trans, REQUEST from) { + final Result rd = mapper.role(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(rd==null) { + return Result.err(Status.ERR_BadData,"Request does not contain Role"); + } + if(v.nullOrBlank(rd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final RoleDAO.Data role = rd.value; + if(ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) { + return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist"); + } + + Result fd = mapper.future(trans,RoleDAO.TABLE,from,role,false, + new Mapper.Memo() { + @Override + public String get() { + return "Delete Role [" + role.fullName() + ']' + + " and all attached user roles"; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), role, Access.write); + } + return nsd; + } + }); + + switch(fd.status) { + case OK: + Result> nsr = ques.nsDAO.read(trans, rd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result rfc = func.createFuture(trans, fd.value, + role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing", + rd.value.ns, + rd.value.name); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.deleteRole(trans,role,trans.requested(force), true /*preapproved*/); + default: + return Result.err(fd); + } + + } /*********************************** * CRED ***********************************/ - private class MayCreateCred implements MayChange { - private Result nsd; - private AuthzTrans trans; - private CredDAO.Data cred; - private Executor exec; - - public MayCreateCred(AuthzTrans trans, CredDAO.Data cred, Executor exec) { - this.trans = trans; - this.cred = cred; - this.exec = exec; - } - - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.validNSOfDomain(trans, cred.id); - } - // is Ns of CredID valid? - if(nsd.isOK()) { - try { - // Check Org Policy - if(trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) { - return Result.ok(); - } else { - Result rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write); - if(rmc.isOKhasData()) { - return rmc; - } - } - } catch (Exception e) { - trans.warn().log(e); - } - } else { - trans.warn().log(nsd.errorString()); - } - return Result.err(Status.ERR_Denied,"%s is not allowed to create %s in %s",trans.user(),cred.id,cred.ns); - } - } - - private class MayChangeCred implements MayChange { - - private Result nsd; - private AuthzTrans trans; - private CredDAO.Data cred; - public MayChangeCred(AuthzTrans trans, CredDAO.Data cred) { - this.trans = trans; - this.cred = cred; - } - - @Override - public Result mayChange() { - // User can change himself (but not create) - if(trans.user().equals(cred.id)) { - return Result.ok(); - } - if(nsd==null) { - nsd = ques.validNSOfDomain(trans, cred.id); - } - // Get the Namespace - if(nsd.isOK()) { - if(ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) { - return Result.ok(); - } - String user[] = Split.split('.',trans.user()); - if(user.length>2) { - String company = user[user.length-1] + '.' + user[user.length-2]; - if(ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) { - return Result.ok(); - } - } - } - return Result.err(Status.ERR_Denied,"%s is not allowed to change %s in %s",trans.user(),cred.id,cred.ns); - } - - } - - private final long DAY_IN_MILLIS = 24*3600*1000L; - - @ApiDoc( - method = POST, - path = "/authn/cred", - params = {}, - expectedCode = 201, - errorCodes = {403,404,406,409}, - text = { "A credential consists of:", - "
    • id - the ID to create within AAF. The domain is in reverse", - "order of Namespace (i.e. Users of Namespace com.att.myapp would be", - "AB1234@myapp.att.com
    • ", - "
    • password - Company Policy Compliant Password
    ", - "Note: AAF does support multiple credentials with the same ID.", - "Check with your organization if you have this implemented." - } - ) - @Override - public Result createUserCred(final AuthzTrans trans, REQUEST from) { - final String cmdDescription = ("Create User Credential"); - TimeTaken tt = trans.start(cmdDescription, Env.SUB); - - try { - Result rcred = mapper.cred(trans, from, true); - if(rcred.isOKhasData()) { - byte[] rawCred = rcred.value.cred.array(); - rcred = ques.userCredSetup(trans, rcred.value); - - final ServiceValidator v = new ServiceValidator(); - - if(v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations - return Result.err(Status.ERR_BadData,v.errs()); - } - - - // 2016-4 Jonathan, New Behavior - If MechID is not registered with Org, deny creation - Identity mechID = null; - Organization org = trans.org(); - try { - mechID = org.getIdentity(trans, rcred.value.id); - } catch (Exception e1) { - trans.error().log(e1,rcred.value.id,"cannot be validated at this time"); - } - if(mechID==null || !mechID.isFound()) { - return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName()); - } - - Result> nsr = ques.nsDAO.read(trans, rcred.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns); - } - - - boolean firstID = false; - MayChange mc; - - CassExecutor exec = new CassExecutor(trans, func); - Result> rlcd = ques.credDAO.readID(trans, rcred.value.id); - if (rlcd.isOKhasData()) { - if (!org.canHaveMultipleCreds(rcred.value.id)) { - return Result.err(Status.ERR_ConflictAlreadyExists, "Credential exists"); - } - Result rb; - for (CredDAO.Data curr : rlcd.value) { - // May not use the same password in the list - // Note: ASPR specifies character differences, but we don't actually store the - // password to validate char differences. - - rb = ques.userCredCheck(trans, curr, rawCred); - if(rb.notOK()) { - return Result.err(rb); - } else if(rb.value){ - return Result.err(Status.ERR_Policy, "Credential content cannot be reused."); - } else if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) { - return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'"); - } - } - } else { - try { - // 2016-04-12 Jonathan If Caller is the Sponsor and is also an Owner of NS, allow without special Perm - String theMechID = rcred.value.id; - Boolean otherMechIDs = false; - // find out if this is the only mechID. other MechIDs mean special handling (not automated) - for(CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) { - if(!cd.id.equals(theMechID)) { - otherMechIDs = true; - break; - } - } - String reason; - // We can say "ID does not exist" here - if((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) { - return Result.err(Status.ERR_Denied, reason); - } - firstID=true; - } catch (Exception e) { - return Result.err(e); - } - } - - mc = new MayCreateCred(trans, rcred.value, exec); - - final CredDAO.Data cdd = rcred.value; - Result fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, // may want to enable in future. - new Mapper.Memo() { - @Override - public String get() { - return cmdDescription + " [" + - cdd.id + '|' - + cdd.type + '|' - + cdd.expires + ']'; - } - }, - mc); - - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans, fd.value, - rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, - trans.user(), nsr.value.get(0), FUTURE_OP.C); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing", - rcred.value.id, - Integer.toString(rcred.value.type), - rcred.value.expires.toString()); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - try { - if(firstID) { - // && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) { - Result> admins = func.getAdmins(trans, nsr.value.get(0).name, false); - // OK, it's a first ID, and not by NS Admin, so let's set TempPassword length - // Note, we only do this on First time, because of possibility of - // prematurely expiring a production id - if(admins.isOKhasData() && !admins.value.contains(trans.user())) { - rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime(); - } - } - } catch (Exception e) { - trans.error().log(e, "While setting expiration to TempPassword"); - } - Resultudr = ques.credDAO.create(trans, rcred.value); - if(udr.isOK()) { - return Result.ok(); - } - return Result.err(udr); - default: - return Result.err(fd); - } - - } else { - return Result.err(rcred); - } - } finally { - tt.done(); - } - } - - @ApiDoc( - method = GET, - path = "/authn/creds/ns/:ns", - params = {"ns|string|true"}, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Return all IDs in Namespace :ns" - } - ) - @Override - public Result getCredsByNS(AuthzTrans trans, String ns) { - final Validator v = new ServiceValidator(); - if(v.ns(ns).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // check if user is allowed to view NS - Result rnd = ques.deriveNs(trans,ns); - if(rnd.notOK()) { - return Result.err(rnd); - } - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - TimeTaken tt = trans.start("MAP Creds by NS to Creds", Env.SUB); - try { - USERS users = mapper.newInstance(API.USERS); - Result> rlcd = ques.credDAO.readNS(trans, ns); - - if(rlcd.isOK()) { - if(!rlcd.isEmpty()) { - return mapper.cred(rlcd.value, users); - } - return Result.ok(users); - } else { - return Result.err(rlcd); - } - } finally { - tt.done(); - } - - } - - @ApiDoc( - method = GET, - path = "/authn/creds/id/:ns", - params = {"id|string|true"}, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Return all IDs in for ID" - ,"(because IDs are multiple, due to multiple Expiration Dates)" - } - ) - @Override - public Result getCredsByID(AuthzTrans trans, String id) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("ID",id).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - String ns = Question.domain2ns(id); - // check if user is allowed to view NS - Result rnd = ques.deriveNs(trans,ns); - if(rnd.notOK()) { - return Result.err(rnd); - } - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - TimeTaken tt = trans.start("MAP Creds by ID to Creds", Env.SUB); - try { - USERS users = mapper.newInstance(API.USERS); - Result> rlcd = ques.credDAO.readID(trans, id); - - if(rlcd.isOK()) { - if(!rlcd.isEmpty()) { - return mapper.cred(rlcd.value, users); - } - return Result.ok(users); - } else { - return Result.err(rlcd); - } - } finally { - tt.done(); - } - - } - - @ApiDoc( - method = GET, - path = "/authn/certs/id/:id", - params = {"id|string|true"}, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Return Cert Info for ID" - } - ) - @Override - public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id) { - TimeTaken tt = trans.start("Get Cert Info by ID", Env.SUB); - try { - CERTS certs = mapper.newInstance(API.CERTS); - Result> rlcd = ques.certDAO.readID(trans, id); - - if(rlcd.isOK()) { - if(!rlcd.isEmpty()) { - return mapper.cert(rlcd.value, certs); - } - return Result.ok(certs); - } else { - return Result.err(rlcd); - } - } finally { - tt.done(); - } - - } - - @ApiDoc( - method = PUT, - path = "/authn/cred", - params = {}, - expectedCode = 200, - errorCodes = {300,403,404,406}, - text = { "Reset a Credential Password. If multiple credentials exist for this", - "ID, you will need to specify which entry you are resetting in the", - "CredRequest object" - } - ) - @Override - public Result changeUserCred(final AuthzTrans trans, REQUEST from) { - final String cmdDescription = "Update User Credential"; - TimeTaken tt = trans.start(cmdDescription, Env.SUB); - try { - Result rcred = mapper.cred(trans, from, true); - if(rcred.isOKhasData()) { - rcred = ques.userCredSetup(trans, rcred.value); - - final ServiceValidator v = new ServiceValidator(); - - if(v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations - return Result.err(Status.ERR_BadData,v.errs()); - } - Result> rlcd = ques.credDAO.readID(trans, rcred.value.id); - if(rlcd.notOKorIsEmpty()) { - return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); - } - - MayChange mc = new MayChangeCred(trans, rcred.value); - Result rmc = mc.mayChange(); - if (rmc.notOK()) { - return Result.err(rmc); - } - - Result ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); - if(ri.notOK()) { - return Result.err(ri); - } - int entry = ri.value; - - - final CredDAO.Data cred = rcred.value; - - Result fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, - new Mapper.Memo() { - @Override - public String get() { - return cmdDescription + " [" + - cred.id + '|' - + cred.type + '|' - + cred.expires + ']'; - } - }, - mc); - - Result> nsr = ques.nsDAO.read(trans, rcred.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans, fd.value, - rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, - trans.user(), nsr.value.get(0), FUTURE_OP.U); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]", - rcred.value.id, - Integer.toString(rcred.value.type), - rcred.value.expires.toString()); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - Resultudr = null; - // If we are Resetting Password on behalf of someone else (am not the Admin) - // use TempPassword Expiration time. - Expiration exp; - if(ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) { - exp = Expiration.Password; - } else { - exp = Expiration.TempPassword; - } - - Organization org = trans.org(); - CredDAO.Data current = rlcd.value.get(entry); - // If user resets password in same day, we will have a primary key conflict, so subtract 1 day - if (current.expires.equals(rcred.value.expires) - && rlcd.value.get(entry).type==rcred.value.type) { - GregorianCalendar gc = org.expiration(null, exp,rcred.value.id); - gc = Chrono.firstMomentOfDay(gc); - gc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay()); - rcred.value.expires = new Date(gc.getTimeInMillis() - DAY_IN_MILLIS); - } else { - rcred.value.expires = org.expiration(null,exp).getTime(); - } - // Copy in other fields 10/21/2016 - rcred.value.notes=current.notes; - - udr = ques.credDAO.create(trans, rcred.value); - if(udr.isOK()) { - udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); - } - if (udr.isOK()) { - return Result.ok(); - } - - return Result.err(udr); - default: - return Result.err(fd); - } - } else { - return Result.err(rcred); - } - } finally { - tt.done(); - } - } - - /* - * Codify the way to get Either Choice Needed or actual Integer from Credit Request - */ - private Result selectEntryIfMultiple(final CredRequest cr, List lcd) { - int entry = 0; - if (lcd.size() > 1) { - String inputOption = cr.getEntry(); - if (inputOption == null) { - String message = selectCredFromList(lcd, false); - String[] variables = buildVariables(lcd); - return Result.err(Status.ERR_ChoiceNeeded, message, variables); - } else { - entry = Integer.parseInt(inputOption) - 1; - } - if (entry < 0 || entry >= lcd.size()) { - return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); - } - } - return Result.ok(entry); - } - - @ApiDoc( - method = PUT, - path = "/authn/cred/:days", - params = {"days|string|true"}, - expectedCode = 200, - errorCodes = {300,403,404,406}, - text = { "Extend a Credential Expiration Date. The intention of this API is", - "to avoid an outage in PROD due to a Credential expiring before it", - "can be configured correctly. Measures are being put in place ", - "so that this is not abused." - } - ) - @Override - public Result extendUserCred(final AuthzTrans trans, REQUEST from, String days) { - TimeTaken tt = trans.start("Extend User Credential", Env.SUB); - try { - Result cred = mapper.cred(trans, from, false); - Organization org = trans.org(); - final ServiceValidator v = new ServiceValidator(); - if(v.notOK(cred).err() || - v.nullOrBlank(cred.value.id, "Invalid ID").err() || - v.user(org,cred.value.id).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - try { - String reason; - if ((reason=org.validate(trans, Policy.MAY_EXTEND_CRED_EXPIRES, new CassExecutor(trans,func)))!=null) { - return Result.err(Status.ERR_Policy,reason); - } - } catch (Exception e) { - String msg; - trans.error().log(e, msg="Could not contact Organization for User Validation"); - return Result.err(Status.ERR_Denied, msg); - } - - // Get the list of Cred Entries - Result> rlcd = ques.credDAO.readID(trans, cred.value.id); - if(rlcd.notOKorIsEmpty()) { - return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); - } - - //Need to do the "Pick Entry" mechanism - Result ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); - if(ri.notOK()) { - return Result.err(ri); - } - - CredDAO.Data found = rlcd.value.get(ri.value); - CredDAO.Data cd = cred.value; - // Copy over the cred - cd.id = found.id; - cd.cred = found.cred; - cd.other = found.other; - cd.type = found.type; - cd.notes = found.notes; - cd.ns = found.ns; - cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime(); - - cred = ques.credDAO.create(trans, cd); - if(cred.isOK()) { - return Result.ok(); - } - return Result.err(cred); - } finally { - tt.done(); - } - } - - private String[] buildVariables(List value) { - // ensure credentials are sorted so we can fully automate Cred regression test - Collections.sort(value, new Comparator() { - @Override - public int compare(CredDAO.Data cred1, CredDAO.Data cred2) { - return cred1.expires.compareTo(cred2.expires); - } - }); - String [] vars = new String[value.size()+1]; - vars[0]="Choice"; - for (int i = 0; i < value.size(); i++) { - vars[i+1] = value.get(i).id + " " + value.get(i).type - + " |" + value.get(i).expires; - } - return vars; - } - - private String selectCredFromList(List value, boolean isDelete) { - StringBuilder errMessage = new StringBuilder(); - String userPrompt = isDelete?"Select which cred to delete (set force=true to delete all):":"Select which cred to update:"; - int numSpaces = value.get(0).id.length() - "Id".length(); - - errMessage.append(userPrompt + '\n'); - errMessage.append(" Id"); - for (int i = 0; i < numSpaces; i++) { - errMessage.append(' '); - } - errMessage.append(" Type Expires" + '\n'); - for(int i=0;i deleteUserCred(AuthzTrans trans, REQUEST from) { - final Result cred = mapper.cred(trans, from, false); - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("cred", cred.value.id).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rlcd = ques.credDAO.readID(trans, cred.value.id); - if(rlcd.notOKorIsEmpty()) { - // Empty Creds should have no user_roles. - Result> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - ques.userRoleDAO.delete(trans, data, false); - } - } - return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); - } - boolean isLastCred = rlcd.value.size()==1; - - MayChange mc = new MayChangeCred(trans,cred.value); - Result rmc = mc.mayChange(); - if (rmc.notOK()) { - return Result.err(rmc); - } - - int entry = 0; - if(!trans.requested(force)) { - if (rlcd.value.size() > 1) { - CredRequest cr = (CredRequest)from; - String inputOption = cr.getEntry(); - if (inputOption == null) { - String message = selectCredFromList(rlcd.value, true); - String[] variables = buildVariables(rlcd.value); - return Result.err(Status.ERR_ChoiceNeeded, message, variables); - } else { - try { - if(inputOption.length()>5) { // should be a date - Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime(); - entry = 0; - for(CredDAO.Data cd : rlcd.value) { - if(cd.type.equals(cr.getType()) && cd.expires.equals(d)) { - break; - } - ++entry; - } - } else { - entry = Integer.parseInt(inputOption) - 1; - } - } catch(NullPointerException e) { - return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry"); - } catch(NumberFormatException e) { - return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); - } - } - isLastCred = (entry==-1)?true:false; - } else { - isLastCred = true; - } - if (entry < -1 || entry >= rlcd.value.size()) { - return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); - } - } - - Result fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false, - new Mapper.Memo() { - @Override - public String get() { - return "Delete Credential [" + - cred.value.id + - ']'; - } - }, - mc); - - Result> nsr = ques.nsDAO.read(trans, cred.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans, fd.value, cred.value.id, - trans.user(), nsr.value.get(0), FUTURE_OP.D); - - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - Resultudr = null; - if (!trans.requested(force)) { - if(entry<0 || entry >= rlcd.value.size()) { - return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id); - } - udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); - } else { - for (CredDAO.Data curr : rlcd.value) { - udr = ques.credDAO.delete(trans, curr, false); - if (udr.notOK()) { - return Result.err(udr); - } - } - } - if(isLastCred) { - Result> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - ques.userRoleDAO.delete(trans, data, false); - } - } - } - if(udr==null) { - return Result.err(Result.ERR_NotFound,"No User Data found"); - } - if (udr.isOK()) { - return Result.ok(); - } - return Result.err(udr); - default: - return Result.err(fd); - } - - } - - - @Override - public Result doesCredentialMatch(AuthzTrans trans, REQUEST credReq) { - TimeTaken tt = trans.start("Does Credential Match", Env.SUB); - try { - // Note: Mapper assigns RAW type - Result data = mapper.cred(trans, credReq,false); - if(data.notOKorIsEmpty()) { - return Result.err(data); - } - CredDAO.Data cred = data.value; // of the Mapped Cred - if(cred.cred==null) { - return Result.err(Result.ERR_BadData,"No Password"); - } else { - return ques.doesUserCredMatch(trans, cred.id, cred.cred.array()); - } - - } catch (DAOException e) { - trans.error().log(e,"Error looking up cred"); - return Result.err(Status.ERR_Denied,"Credential does not match"); - } finally { - tt.done(); - } - } - - @ApiDoc( - method = GET, - path = "/authn/basicAuth", - params = {}, - expectedCode = 200, - errorCodes = { 403 }, - text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n" - + "Use /authn/validate instead\n" - + "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast" - + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth " - + "security, and 403 if it does not." } - ) - private void basicAuth() { - // This is a place holder for Documentation. The real BasicAuth API does not call Service. - } - - @ApiDoc( - method = POST, - path = "/authn/validate", - params = {}, - expectedCode = 200, - errorCodes = { 403 }, - text = { "Validate a Credential given a Credential Structure. This is a more comprehensive validation, can " - + "do more than BasicAuth as Credential types exp" } - ) - @Override - public Result validateBasicAuth(AuthzTrans trans, String basicAuth) { - //TODO how to make sure people don't use this in browsers? Do we care? - TimeTaken tt = trans.start("Validate Basic Auth", Env.SUB); - try { - BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm()); - Result rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred()); - // Note: Only want to log problem, don't want to send back to end user - if(rq.isOK()) { - return rq; - } else { - trans.audit().log(rq.errorString()); - } - } catch (Exception e) { - trans.warn().log(e); - } finally { - tt.done(); - } - return Result.err(Status.ERR_Denied,"Bad Basic Auth"); - } + private class MayCreateCred implements MayChange { + private Result nsd; + private AuthzTrans trans; + private CredDAO.Data cred; + private Executor exec; + + public MayCreateCred(AuthzTrans trans, CredDAO.Data cred, Executor exec) { + this.trans = trans; + this.cred = cred; + this.exec = exec; + } + + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.validNSOfDomain(trans, cred.id); + } + // is Ns of CredID valid? + if(nsd.isOK()) { + try { + // Check Org Policy + if(trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) { + return Result.ok(); + } else { + Result rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write); + if(rmc.isOKhasData()) { + return rmc; + } + } + } catch (Exception e) { + trans.warn().log(e); + } + } else { + trans.warn().log(nsd.errorString()); + } + return Result.err(Status.ERR_Denied,"%s is not allowed to create %s in %s",trans.user(),cred.id,cred.ns); + } + } + + private class MayChangeCred implements MayChange { + + private Result nsd; + private AuthzTrans trans; + private CredDAO.Data cred; + public MayChangeCred(AuthzTrans trans, CredDAO.Data cred) { + this.trans = trans; + this.cred = cred; + } + + @Override + public Result mayChange() { + // User can change himself (but not create) + if(trans.user().equals(cred.id)) { + return Result.ok(); + } + if(nsd==null) { + nsd = ques.validNSOfDomain(trans, cred.id); + } + // Get the Namespace + if(nsd.isOK()) { + if(ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) { + return Result.ok(); + } + String user[] = Split.split('.',trans.user()); + if(user.length>2) { + String company = user[user.length-1] + '.' + user[user.length-2]; + if(ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) { + return Result.ok(); + } + } + } + return Result.err(Status.ERR_Denied,"%s is not allowed to change %s in %s",trans.user(),cred.id,cred.ns); + } + + } + + private final long DAY_IN_MILLIS = 24*3600*1000L; + + @ApiDoc( + method = POST, + path = "/authn/cred", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "A credential consists of:", + "
    • id - the ID to create within AAF. The domain is in reverse", + "order of Namespace (i.e. Users of Namespace com.att.myapp would be", + "AB1234@myapp.att.com
    • ", + "
    • password - Company Policy Compliant Password
    ", + "Note: AAF does support multiple credentials with the same ID.", + "Check with your organization if you have this implemented." + } + ) + @Override + public Result createUserCred(final AuthzTrans trans, REQUEST from) { + final String cmdDescription = ("Create User Credential"); + TimeTaken tt = trans.start(cmdDescription, Env.SUB); + + try { + Result rcred = mapper.cred(trans, from, true); + if(rcred.isOKhasData()) { + byte[] rawCred = rcred.value.cred.array(); + rcred = ques.userCredSetup(trans, rcred.value); + + final ServiceValidator v = new ServiceValidator(); + + if(v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations + return Result.err(Status.ERR_BadData,v.errs()); + } + + + // 2016-4 Jonathan, New Behavior - If MechID is not registered with Org, deny creation + Identity mechID = null; + Organization org = trans.org(); + try { + mechID = org.getIdentity(trans, rcred.value.id); + } catch (Exception e1) { + trans.error().log(e1,rcred.value.id,"cannot be validated at this time"); + } + if(mechID==null || !mechID.isFound()) { + return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName()); + } + + Result> nsr = ques.nsDAO.read(trans, rcred.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns); + } + + + boolean firstID = false; + MayChange mc; + + CassExecutor exec = new CassExecutor(trans, func); + Result> rlcd = ques.credDAO.readID(trans, rcred.value.id); + if (rlcd.isOKhasData()) { + if (!org.canHaveMultipleCreds(rcred.value.id)) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Credential exists"); + } + Result rb; + for (CredDAO.Data curr : rlcd.value) { + // May not use the same password in the list + // Note: ASPR specifies character differences, but we don't actually store the + // password to validate char differences. + + rb = ques.userCredCheck(trans, curr, rawCred); + if(rb.notOK()) { + return Result.err(rb); + } else if(rb.value){ + return Result.err(Status.ERR_Policy, "Credential content cannot be reused."); + } else if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'"); + } + } + } else { + try { + // 2016-04-12 Jonathan If Caller is the Sponsor and is also an Owner of NS, allow without special Perm + String theMechID = rcred.value.id; + Boolean otherMechIDs = false; + // find out if this is the only mechID. other MechIDs mean special handling (not automated) + for(CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) { + if(!cd.id.equals(theMechID)) { + otherMechIDs = true; + break; + } + } + String reason; + // We can say "ID does not exist" here + if((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) { + return Result.err(Status.ERR_Denied, reason); + } + firstID=true; + } catch (Exception e) { + return Result.err(e); + } + } + + mc = new MayCreateCred(trans, rcred.value, exec); + + final CredDAO.Data cdd = rcred.value; + Result fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, // may want to enable in future. + new Mapper.Memo() { + @Override + public String get() { + return cmdDescription + " [" + + cdd.id + '|' + + cdd.type + '|' + + cdd.expires + ']'; + } + }, + mc); + + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans, fd.value, + rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, + trans.user(), nsr.value.get(0), FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing", + rcred.value.id, + Integer.toString(rcred.value.type), + rcred.value.expires.toString()); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + try { + if(firstID) { + // && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) { + Result> admins = func.getAdmins(trans, nsr.value.get(0).name, false); + // OK, it's a first ID, and not by NS Admin, so let's set TempPassword length + // Note, we only do this on First time, because of possibility of + // prematurely expiring a production id + if(admins.isOKhasData() && !admins.value.contains(trans.user())) { + rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime(); + } + } + } catch (Exception e) { + trans.error().log(e, "While setting expiration to TempPassword"); + } + Resultudr = ques.credDAO.create(trans, rcred.value); + if(udr.isOK()) { + return Result.ok(); + } + return Result.err(udr); + default: + return Result.err(fd); + } + + } else { + return Result.err(rcred); + } + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authn/creds/ns/:ns", + params = {"ns|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Return all IDs in Namespace :ns" + } + ) + @Override + public Result getCredsByNS(AuthzTrans trans, String ns) { + final Validator v = new ServiceValidator(); + if(v.ns(ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // check if user is allowed to view NS + Result rnd = ques.deriveNs(trans,ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + TimeTaken tt = trans.start("MAP Creds by NS to Creds", Env.SUB); + try { + USERS users = mapper.newInstance(API.USERS); + Result> rlcd = ques.credDAO.readNS(trans, ns); + + if(rlcd.isOK()) { + if(!rlcd.isEmpty()) { + return mapper.cred(rlcd.value, users); + } + return Result.ok(users); + } else { + return Result.err(rlcd); + } + } finally { + tt.done(); + } + + } + + @ApiDoc( + method = GET, + path = "/authn/creds/id/:ns", + params = {"id|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Return all IDs in for ID" + ,"(because IDs are multiple, due to multiple Expiration Dates)" + } + ) + @Override + public Result getCredsByID(AuthzTrans trans, String id) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("ID",id).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + String ns = Question.domain2ns(id); + // check if user is allowed to view NS + Result rnd = ques.deriveNs(trans,ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + TimeTaken tt = trans.start("MAP Creds by ID to Creds", Env.SUB); + try { + USERS users = mapper.newInstance(API.USERS); + Result> rlcd = ques.credDAO.readID(trans, id); + + if(rlcd.isOK()) { + if(!rlcd.isEmpty()) { + return mapper.cred(rlcd.value, users); + } + return Result.ok(users); + } else { + return Result.err(rlcd); + } + } finally { + tt.done(); + } + + } + + @ApiDoc( + method = GET, + path = "/authn/certs/id/:id", + params = {"id|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Return Cert Info for ID" + } + ) + @Override + public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id) { + TimeTaken tt = trans.start("Get Cert Info by ID", Env.SUB); + try { + CERTS certs = mapper.newInstance(API.CERTS); + Result> rlcd = ques.certDAO.readID(trans, id); + + if(rlcd.isOK()) { + if(!rlcd.isEmpty()) { + return mapper.cert(rlcd.value, certs); + } + return Result.ok(certs); + } else { + return Result.err(rlcd); + } + } finally { + tt.done(); + } + + } + + @ApiDoc( + method = PUT, + path = "/authn/cred", + params = {}, + expectedCode = 200, + errorCodes = {300,403,404,406}, + text = { "Reset a Credential Password. If multiple credentials exist for this", + "ID, you will need to specify which entry you are resetting in the", + "CredRequest object" + } + ) + @Override + public Result changeUserCred(final AuthzTrans trans, REQUEST from) { + final String cmdDescription = "Update User Credential"; + TimeTaken tt = trans.start(cmdDescription, Env.SUB); + try { + Result rcred = mapper.cred(trans, from, true); + if(rcred.isOKhasData()) { + rcred = ques.userCredSetup(trans, rcred.value); + + final ServiceValidator v = new ServiceValidator(); + + if(v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations + return Result.err(Status.ERR_BadData,v.errs()); + } + Result> rlcd = ques.credDAO.readID(trans, rcred.value.id); + if(rlcd.notOKorIsEmpty()) { + return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); + } + + MayChange mc = new MayChangeCred(trans, rcred.value); + Result rmc = mc.mayChange(); + if (rmc.notOK()) { + return Result.err(rmc); + } + + Result ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); + if(ri.notOK()) { + return Result.err(ri); + } + int entry = ri.value; + + + final CredDAO.Data cred = rcred.value; + + Result fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, + new Mapper.Memo() { + @Override + public String get() { + return cmdDescription + " [" + + cred.id + '|' + + cred.type + '|' + + cred.expires + ']'; + } + }, + mc); + + Result> nsr = ques.nsDAO.read(trans, rcred.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans, fd.value, + rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, + trans.user(), nsr.value.get(0), FUTURE_OP.U); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]", + rcred.value.id, + Integer.toString(rcred.value.type), + rcred.value.expires.toString()); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Resultudr = null; + // If we are Resetting Password on behalf of someone else (am not the Admin) + // use TempPassword Expiration time. + Expiration exp; + if(ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) { + exp = Expiration.Password; + } else { + exp = Expiration.TempPassword; + } + + Organization org = trans.org(); + CredDAO.Data current = rlcd.value.get(entry); + // If user resets password in same day, we will have a primary key conflict, so subtract 1 day + if (current.expires.equals(rcred.value.expires) + && rlcd.value.get(entry).type==rcred.value.type) { + GregorianCalendar gc = org.expiration(null, exp,rcred.value.id); + gc = Chrono.firstMomentOfDay(gc); + gc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay()); + rcred.value.expires = new Date(gc.getTimeInMillis() - DAY_IN_MILLIS); + } else { + rcred.value.expires = org.expiration(null,exp).getTime(); + } + // Copy in other fields 10/21/2016 + rcred.value.notes=current.notes; + + udr = ques.credDAO.create(trans, rcred.value); + if(udr.isOK()) { + udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); + } + if (udr.isOK()) { + return Result.ok(); + } + + return Result.err(udr); + default: + return Result.err(fd); + } + } else { + return Result.err(rcred); + } + } finally { + tt.done(); + } + } + + /* + * Codify the way to get Either Choice Needed or actual Integer from Credit Request + */ + private Result selectEntryIfMultiple(final CredRequest cr, List lcd) { + int entry = 0; + if (lcd.size() > 1) { + String inputOption = cr.getEntry(); + if (inputOption == null) { + String message = selectCredFromList(lcd, false); + String[] variables = buildVariables(lcd); + return Result.err(Status.ERR_ChoiceNeeded, message, variables); + } else { + entry = Integer.parseInt(inputOption) - 1; + } + if (entry < 0 || entry >= lcd.size()) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + return Result.ok(entry); + } + + @ApiDoc( + method = PUT, + path = "/authn/cred/:days", + params = {"days|string|true"}, + expectedCode = 200, + errorCodes = {300,403,404,406}, + text = { "Extend a Credential Expiration Date. The intention of this API is", + "to avoid an outage in PROD due to a Credential expiring before it", + "can be configured correctly. Measures are being put in place ", + "so that this is not abused." + } + ) + @Override + public Result extendUserCred(final AuthzTrans trans, REQUEST from, String days) { + TimeTaken tt = trans.start("Extend User Credential", Env.SUB); + try { + Result cred = mapper.cred(trans, from, false); + Organization org = trans.org(); + final ServiceValidator v = new ServiceValidator(); + if(v.notOK(cred).err() || + v.nullOrBlank(cred.value.id, "Invalid ID").err() || + v.user(org,cred.value.id).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + try { + String reason; + if ((reason=org.validate(trans, Policy.MAY_EXTEND_CRED_EXPIRES, new CassExecutor(trans,func)))!=null) { + return Result.err(Status.ERR_Policy,reason); + } + } catch (Exception e) { + String msg; + trans.error().log(e, msg="Could not contact Organization for User Validation"); + return Result.err(Status.ERR_Denied, msg); + } + + // Get the list of Cred Entries + Result> rlcd = ques.credDAO.readID(trans, cred.value.id); + if(rlcd.notOKorIsEmpty()) { + return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); + } + + //Need to do the "Pick Entry" mechanism + Result ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); + if(ri.notOK()) { + return Result.err(ri); + } + + CredDAO.Data found = rlcd.value.get(ri.value); + CredDAO.Data cd = cred.value; + // Copy over the cred + cd.id = found.id; + cd.cred = found.cred; + cd.other = found.other; + cd.type = found.type; + cd.notes = found.notes; + cd.ns = found.ns; + cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime(); + + cred = ques.credDAO.create(trans, cd); + if(cred.isOK()) { + return Result.ok(); + } + return Result.err(cred); + } finally { + tt.done(); + } + } + + private String[] buildVariables(List value) { + // ensure credentials are sorted so we can fully automate Cred regression test + Collections.sort(value, new Comparator() { + @Override + public int compare(CredDAO.Data cred1, CredDAO.Data cred2) { + return cred1.expires.compareTo(cred2.expires); + } + }); + String [] vars = new String[value.size()+1]; + vars[0]="Choice"; + for (int i = 0; i < value.size(); i++) { + vars[i+1] = value.get(i).id + " " + value.get(i).type + + " |" + value.get(i).expires; + } + return vars; + } + + private String selectCredFromList(List value, boolean isDelete) { + StringBuilder errMessage = new StringBuilder(); + String userPrompt = isDelete?"Select which cred to delete (set force=true to delete all):":"Select which cred to update:"; + int numSpaces = value.get(0).id.length() - "Id".length(); + + errMessage.append(userPrompt + '\n'); + errMessage.append(" Id"); + for (int i = 0; i < numSpaces; i++) { + errMessage.append(' '); + } + errMessage.append(" Type Expires" + '\n'); + for(int i=0;i deleteUserCred(AuthzTrans trans, REQUEST from) { + final Result cred = mapper.cred(trans, from, false); + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("cred", cred.value.id).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlcd = ques.credDAO.readID(trans, cred.value.id); + if(rlcd.notOKorIsEmpty()) { + // Empty Creds should have no user_roles. + Result> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + ques.userRoleDAO.delete(trans, data, false); + } + } + return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); + } + boolean isLastCred = rlcd.value.size()==1; + + MayChange mc = new MayChangeCred(trans,cred.value); + Result rmc = mc.mayChange(); + if (rmc.notOK()) { + return Result.err(rmc); + } + + int entry = 0; + if(!trans.requested(force)) { + if (rlcd.value.size() > 1) { + CredRequest cr = (CredRequest)from; + String inputOption = cr.getEntry(); + if (inputOption == null) { + String message = selectCredFromList(rlcd.value, true); + String[] variables = buildVariables(rlcd.value); + return Result.err(Status.ERR_ChoiceNeeded, message, variables); + } else { + try { + if(inputOption.length()>5) { // should be a date + Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime(); + entry = 0; + for(CredDAO.Data cd : rlcd.value) { + if(cd.type.equals(cr.getType()) && cd.expires.equals(d)) { + break; + } + ++entry; + } + } else { + entry = Integer.parseInt(inputOption) - 1; + } + } catch(NullPointerException e) { + return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry"); + } catch(NumberFormatException e) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + isLastCred = (entry==-1)?true:false; + } else { + isLastCred = true; + } + if (entry < -1 || entry >= rlcd.value.size()) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + + Result fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false, + new Mapper.Memo() { + @Override + public String get() { + return "Delete Credential [" + + cred.value.id + + ']'; + } + }, + mc); + + Result> nsr = ques.nsDAO.read(trans, cred.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans, fd.value, cred.value.id, + trans.user(), nsr.value.get(0), FUTURE_OP.D); + + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Resultudr = null; + if (!trans.requested(force)) { + if(entry<0 || entry >= rlcd.value.size()) { + return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id); + } + udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); + } else { + for (CredDAO.Data curr : rlcd.value) { + udr = ques.credDAO.delete(trans, curr, false); + if (udr.notOK()) { + return Result.err(udr); + } + } + } + if(isLastCred) { + Result> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + ques.userRoleDAO.delete(trans, data, false); + } + } + } + if(udr==null) { + return Result.err(Result.ERR_NotFound,"No User Data found"); + } + if (udr.isOK()) { + return Result.ok(); + } + return Result.err(udr); + default: + return Result.err(fd); + } + + } + + + @Override + public Result doesCredentialMatch(AuthzTrans trans, REQUEST credReq) { + TimeTaken tt = trans.start("Does Credential Match", Env.SUB); + try { + // Note: Mapper assigns RAW type + Result data = mapper.cred(trans, credReq,false); + if(data.notOKorIsEmpty()) { + return Result.err(data); + } + CredDAO.Data cred = data.value; // of the Mapped Cred + if(cred.cred==null) { + return Result.err(Result.ERR_BadData,"No Password"); + } else { + return ques.doesUserCredMatch(trans, cred.id, cred.cred.array()); + } + + } catch (DAOException e) { + trans.error().log(e,"Error looking up cred"); + return Result.err(Status.ERR_Denied,"Credential does not match"); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authn/basicAuth", + params = {}, + expectedCode = 200, + errorCodes = { 403 }, + text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n" + + "Use /authn/validate instead\n" + + "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast" + + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth " + + "security, and 403 if it does not." } + ) + private void basicAuth() { + // This is a place holder for Documentation. The real BasicAuth API does not call Service. + } + + @ApiDoc( + method = POST, + path = "/authn/validate", + params = {}, + expectedCode = 200, + errorCodes = { 403 }, + text = { "Validate a Credential given a Credential Structure. This is a more comprehensive validation, can " + + "do more than BasicAuth as Credential types exp" } + ) + @Override + public Result validateBasicAuth(AuthzTrans trans, String basicAuth) { + //TODO how to make sure people don't use this in browsers? Do we care? + TimeTaken tt = trans.start("Validate Basic Auth", Env.SUB); + try { + BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm()); + Result rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred()); + // Note: Only want to log problem, don't want to send back to end user + if(rq.isOK()) { + return rq; + } else { + trans.audit().log(rq.errorString()); + } + } catch (Exception e) { + trans.warn().log(e); + } finally { + tt.done(); + } + return Result.err(Status.ERR_Denied,"Bad Basic Auth"); + } /*********************************** * USER-ROLE ***********************************/ - @ApiDoc( - method = POST, - path = "/authz/userRole", - params = {}, - expectedCode = 201, - errorCodes = {403,404,406,409}, - text = { "Create a UserRole relationship (add User to Role)", - "A UserRole is an object Representation of membership of a Role for limited time.", - "If a shorter amount of time for Role ownership is required, use the 'End' field.", - "** Note: Owners of Namespaces will be required to revalidate users in these roles ", - "before Expirations expire. Namespace owners will be notified by email." - } - ) - @Override - public Result createUserRole(final AuthzTrans trans, REQUEST from) { - TimeTaken tt = trans.start("Create UserRole", Env.SUB); - try { - Result urr = mapper.userRole(trans, from); - if(urr.notOKorIsEmpty()) { - return Result.err(urr); - } - final UserRoleDAO.Data userRole = urr.value; - - final ServiceValidator v = new ServiceValidator(); - if(v.user_role(userRole).err() || - v.user(trans.org(), userRole.user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - - - // Check if user can change first - Result fd = mapper.future(trans,UserRoleDAO.TABLE,from,urr.value,true, // may request Approvals - new Mapper.Memo() { - @Override - public String get() { - return "Add User [" + userRole.user + "] to Role [" + - userRole.role + - ']'; - } - }, - new MayChange() { - private Result nsd; - @Override - public Result mayChange() { - if(nsd==null) { - RoleDAO.Data r = RoleDAO.Data.decode(userRole); - nsd = ques.mayUser(trans, trans.user(), r, Access.write); - } - return nsd; - } - }); - Result nsr = ques.deriveNs(trans, userRole.role); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname, - userRole.user, nsr.value, FUTURE_OP.C); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing", - userRole.user, - userRole.ns, - userRole.rname); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - return func.addUserRole(trans, userRole); - default: - return Result.err(fd); - } - } finally { - tt.done(); - } - } - - /** - * getUserRolesByRole - */ - @ApiDoc( - method = GET, - path = "/authz/userRoles/role/:role", - params = {"role|string|true"}, - expectedCode = 200, - errorCodes = {404,406}, - text = { "List all Users that are attached to Role specified in :role", - } - ) - @Override - public Result getUserRolesByRole(AuthzTrans trans, String role) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role",role).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rrdd; - rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - // May Requester see result? - Result ns = ques.mayUser(trans,trans.user(), rrdd.value,Access.read); - if (ns.notOK()) { - return Result.err(ns); - } - - // boolean filter = true; - // if (ns.value.isAdmin(trans.user()) || ns.value.isResponsible(trans.user())) - // filter = false; - - // Get list of roles per user, then add to Roles as we go - HashSet userSet = new HashSet<>(); - Result> rlurd = ques.userRoleDAO.readByRole(trans, role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - userSet.add(data); - } - } - - @SuppressWarnings("unchecked") - USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES); - // Checked for permission - mapper.userRoles(trans, userSet, users); - return Result.ok(users); - } - /** - * getUserRolesByRole - */ - @ApiDoc( - method = GET, - path = "/authz/userRoles/user/:user", - params = {"role|string|true"}, - expectedCode = 200, - errorCodes = {404,406}, - text = { "List all UserRoles for :user", - } - ) - @Override - public Result getUserRolesByUser(AuthzTrans trans, String user) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User",user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // Get list of roles per user, then add to Roles as we go - Result> rlurd = ques.userRoleDAO.readByUser(trans, user); - if(rlurd.notOK()) { - return Result.err(rlurd); - } - - /* Check for - * 1) is User - * 2) is User's Supervisor - * 3) Has special global access =read permission - * - * If none of the 3, then filter results to NSs in which Calling User has Ns.access * read - */ - boolean mustFilter; - String callingUser = trans.getUserPrincipal().getName(); - NsDAO.Data ndd = new NsDAO.Data(); - - if(user.equals(callingUser)) { - mustFilter = false; - } else { - Organization org = trans.org(); - try { - Identity orgID = org.getIdentity(trans, user); - Identity manager = orgID==null?null:orgID.responsibleTo(); - if(orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) { - mustFilter = false; - } else if(ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) { - mustFilter=false; - } else { - mustFilter = true; - } - } catch (OrganizationException e) { - trans.env().log(e); - mustFilter = true; - } - } - - List content; - if(mustFilter) { - content = new ArrayList<>(rlurd.value.size()); // avoid multi-memory redos - - for(UserRoleDAO.Data data : rlurd.value) { - ndd.name=data.ns; - Result mur = ques.mayUser(trans, callingUser, ndd, Access.read); - if(mur.isOK()){ - content.add(data); - } - } - - } else { - content = rlurd.value; - } - - - @SuppressWarnings("unchecked") - USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES); - // Checked for permission - mapper.userRoles(trans, content, users); - return Result.ok(users); - } - - - @ApiDoc( - method = PUT, - path = "/authz/userRole/user", - params = {}, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Set a User's roles to the roles specified in the UserRoleRequest object.", - "WARNING: Roles supplied will be the ONLY roles attached to this user", - "If no roles are supplied, user's roles are reset." - } - ) - @Override - public Result resetRolesForUser(AuthzTrans trans, REQUEST rreq) { - Result rurdd = mapper.userRole(trans, rreq); - final ServiceValidator v = new ServiceValidator(); - if(rurdd.notOKorIsEmpty()) { - return Result.err(rurdd); - } - if (v.user(trans.org(), rurdd.value.user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Set currRoles = new HashSet<>(); - Result> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - currRoles.add(data.role); - } - } - - Result rv = null; - String[] roles; - if(rurdd.value.role==null) { - roles = new String[0]; - } else { - roles = rurdd.value.role.split(","); - } - - for (String role : roles) { - if (v.role(role).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - Result rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - rurdd.value.role(rrdd.value); - - Result nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write); - if (nsd.notOK()) { - return Result.err(nsd); - } - Result nsr = ques.deriveNs(trans, role); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - if(currRoles.contains(role)) { - currRoles.remove(role); - } else { - rv = func.addUserRole(trans, rurdd.value); - if (rv.notOK()) { - return rv; - } - } - } - - for (String role : currRoles) { - rurdd.value.role(trans,ques,role); - rv = ques.userRoleDAO.delete(trans, rurdd.value, false); - if(rv.notOK()) { - trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist"); - // return rv; // if it doesn't exist, don't error out - } - - } - - return Result.ok(); - - } - - @ApiDoc( - method = PUT, - path = "/authz/userRole/role", - params = {}, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Set a Role's users to the users specified in the UserRoleRequest object.", - "WARNING: Users supplied will be the ONLY users attached to this role", - "If no users are supplied, role's users are reset." - } - ) - @Override - public Result resetUsersForRole(AuthzTrans trans, REQUEST rreq) { - Result rurdd = mapper.userRole(trans, rreq); - if(rurdd.notOKorIsEmpty()) { - return Result.err(rurdd); - } - final ServiceValidator v = new ServiceValidator(); - if (v.user_role(rurdd.value).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - RoleDAO.Data rd = RoleDAO.Data.decode(rurdd.value); - - Result nsd = ques.mayUser(trans, trans.user(), rd, Access.write); - if (nsd.notOK()) { - return Result.err(nsd); - } - - Result nsr = ques.deriveNs(trans, rurdd.value.role); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Set currUsers = new HashSet<>(); - Result> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - currUsers.add(data.user); - } - } - - // found when connected remotely to DEVL, can't replicate locally - // inconsistent errors with cmd: role user setTo [nothing] - // deleteUserRole --> read --> get --> cacheIdx(?) - // sometimes returns idx for last added user instead of user passed in - // cache bug? - - - Result rv = null; - String[] users = {}; - if (rurdd.value.user != null) { - users = rurdd.value.user.split(","); - } - - for (String user : users) { - if (v.user(trans.org(), user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - rurdd.value.user = user; - - if(currUsers.contains(user)) { - currUsers.remove(user); - } else { - rv = func.addUserRole(trans, rurdd.value); - if (rv.notOK()) { - return rv; - } - } - } - - for (String user : currUsers) { - rurdd.value.user = user; - rv = ques.userRoleDAO.delete(trans, rurdd.value, false); - if(rv.notOK()) { - trans.info().log(rurdd.value, "expected to be deleted, but not exists"); - return rv; - } - } - - return Result.ok(); - } - - @ApiDoc( - method = GET, - path = "/authz/userRole/extend/:user/:role", - params = { "user|string|true", - "role|string|true" - }, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Extend the Expiration of this User Role by the amount set by Organization", - "Requestor must be allowed to modify the role" - } - ) - @Override - public Result extendUserRole(AuthzTrans trans, String user, String role) { - Organization org = trans.org(); - final ServiceValidator v = new ServiceValidator(); - if(v.user(org, user) - .role(role) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - Result rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write); - boolean mayNotChange; - if((mayNotChange = rcr.notOK()) && !trans.requested(future)) { - return Result.err(rcr); - } - - Result> rr = ques.userRoleDAO.read(trans, user,role); - if(rr.notOK()) { - return Result.err(rr); - } - for(UserRoleDAO.Data userRole : rr.value) { - if(mayNotChange) { // Function exited earlier if !trans.futureRequested - FutureDAO.Data fto = new FutureDAO.Data(); - fto.target=UserRoleDAO.TABLE; - fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]"; - GregorianCalendar now = new GregorianCalendar(); - fto.start = now.getTime(); - fto.expires = org.expiration(now, Expiration.Future).getTime(); - try { - fto.construct = userRole.bytify(); - } catch (IOException e) { - trans.error().log(e, "Error while bytifying UserRole for Future"); - return Result.err(e); - } - - Result rfc = func.createFuture(trans, fto, - userRole.user+'|'+userRole.role, userRole.user, rcr.value, FUTURE_OP.U); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", - userRole.user, - userRole.role); - } else { - return Result.err(rfc); - } - } else { - return func.extendUserRole(trans, userRole, false); - } - } - return Result.err(Result.ERR_NotFound,"This user and role doesn't exist"); - } - - @ApiDoc( - method = DELETE, - path = "/authz/userRole/:user/:role", - params = { "user|string|true", - "role|string|true" - }, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Remove Role :role from User :user." - } - ) - @Override - public Result deleteUserRole(AuthzTrans trans, String usr, String role) { - Validator val = new ServiceValidator(); - if(val.nullOrBlank("User", usr) - .nullOrBlank("Role", role).err()) { - return Result.err(Status.ERR_BadData, val.errs()); - } - - boolean mayNotChange; - Result rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - RoleDAO.Data rdd = rrdd.value; - Result rns = ques.mayUser(trans, trans.user(), rdd, Access.write); - - // Make sure we don't delete the last owner of valid NS - if(rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) { - return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns ); - } - - if(mayNotChange=rns.notOK()) { - if(!trans.requested(future)) { - return Result.err(rns); - } - } - - Result> rulr; - if((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) { - return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not " - + "Assigned to the Role [ " + role + " ]"); - } - - UserRoleDAO.Data userRole = rulr.value.get(0); - if(mayNotChange) { // Function exited earlier if !trans.futureRequested - FutureDAO.Data fto = new FutureDAO.Data(); - fto.target=UserRoleDAO.TABLE; - fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]"; - GregorianCalendar now = new GregorianCalendar(); - fto.start = now.getTime(); - fto.expires = trans.org().expiration(now, Expiration.Future).getTime(); - - Result rfc = func.createFuture(trans, fto, - userRole.user+'|'+userRole.role, userRole.user, rns.value, FUTURE_OP.D); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", - userRole.user, - userRole.role); - } else { - return Result.err(rfc); - } - } else { - return ques.userRoleDAO.delete(trans, rulr.value.get(0), false); - } - } - - @ApiDoc( - method = GET, - path = "/authz/userRole/:user/:role", - params = {"user|string|true", - "role|string|true"}, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Returns the User (with Expiration date from listed User/Role) if it exists" - } - ) - @Override - public Result getUserInRole(AuthzTrans trans, String user, String role) { - final Validator v = new ServiceValidator(); - if(v.role(role).nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - -// Result ns = ques.deriveNs(trans, role); -// if (ns.notOK()) return Result.err(ns); -// -// Result rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); - // May calling user see by virtue of the Role - Result rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - Result rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - HashSet userSet = new HashSet<>(); - Result> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - userSet.add(data); - } - } - - @SuppressWarnings("unchecked") - USERS users = (USERS) mapper.newInstance(API.USERS); - mapper.users(trans, userSet, users); - return Result.ok(users); - } - - @ApiDoc( - method = GET, - path = "/authz/users/role/:role", - params = {"user|string|true", - "role|string|true"}, - expectedCode = 200, - errorCodes = {403,404,406}, - text = { "Returns the User (with Expiration date from listed User/Role) if it exists" - } - ) - @Override - public Result getUsersByRole(AuthzTrans trans, String role) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role",role).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - -// Result ns = ques.deriveNs(trans, role); -// if (ns.notOK()) return Result.err(ns); -// -// Result rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); - // May calling user see by virtue of the Role - Result rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - boolean contactOnly = false; - // Allow the request of any valid user to find the contact of the NS (Owner) - Result rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); - if(rnd.notOK()) { - if(Question.OWNER.equals(rrdd.value.name)) { - contactOnly = true; - } else { - return Result.err(rnd); - } - } - - HashSet userSet = new HashSet<>(); - Result> rlurd = ques.userRoleDAO.readByRole(trans, role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - if(contactOnly) { //scrub data - // Can't change actual object, or will mess up the cache. - UserRoleDAO.Data scrub = new UserRoleDAO.Data(); - scrub.ns = data.ns; - scrub.rname = data.rname; - scrub.role = data.role; - scrub.user = data.user; - userSet.add(scrub); - } else { - userSet.add(data); - } - } - } - - @SuppressWarnings("unchecked") - USERS users = (USERS) mapper.newInstance(API.USERS); - mapper.users(trans, userSet, users); - return Result.ok(users); - } - - /** - * getUsersByPermission - */ + @ApiDoc( + method = POST, + path = "/authz/userRole", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "Create a UserRole relationship (add User to Role)", + "A UserRole is an object Representation of membership of a Role for limited time.", + "If a shorter amount of time for Role ownership is required, use the 'End' field.", + "** Note: Owners of Namespaces will be required to revalidate users in these roles ", + "before Expirations expire. Namespace owners will be notified by email." + } + ) + @Override + public Result createUserRole(final AuthzTrans trans, REQUEST from) { + TimeTaken tt = trans.start("Create UserRole", Env.SUB); + try { + Result urr = mapper.userRole(trans, from); + if(urr.notOKorIsEmpty()) { + return Result.err(urr); + } + final UserRoleDAO.Data userRole = urr.value; + + final ServiceValidator v = new ServiceValidator(); + if(v.user_role(userRole).err() || + v.user(trans.org(), userRole.user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + + + // Check if user can change first + Result fd = mapper.future(trans,UserRoleDAO.TABLE,from,urr.value,true, // may request Approvals + new Mapper.Memo() { + @Override + public String get() { + return "Add User [" + userRole.user + "] to Role [" + + userRole.role + + ']'; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + RoleDAO.Data r = RoleDAO.Data.decode(userRole); + nsd = ques.mayUser(trans, trans.user(), r, Access.write); + } + return nsd; + } + }); + Result nsr = ques.deriveNs(trans, userRole.role); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname, + userRole.user, nsr.value, FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing", + userRole.user, + userRole.ns, + userRole.rname); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.addUserRole(trans, userRole); + default: + return Result.err(fd); + } + } finally { + tt.done(); + } + } + + /** + * getUserRolesByRole + */ + @ApiDoc( + method = GET, + path = "/authz/userRoles/role/:role", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all Users that are attached to Role specified in :role", + } + ) + @Override + public Result getUserRolesByRole(AuthzTrans trans, String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role",role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rrdd; + rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + // May Requester see result? + Result ns = ques.mayUser(trans,trans.user(), rrdd.value,Access.read); + if (ns.notOK()) { + return Result.err(ns); + } + + // boolean filter = true; + // if (ns.value.isAdmin(trans.user()) || ns.value.isResponsible(trans.user())) + // filter = false; + + // Get list of roles per user, then add to Roles as we go + HashSet userSet = new HashSet<>(); + Result> rlurd = ques.userRoleDAO.readByRole(trans, role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + userSet.add(data); + } + } + + @SuppressWarnings("unchecked") + USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES); + // Checked for permission + mapper.userRoles(trans, userSet, users); + return Result.ok(users); + } + /** + * getUserRolesByRole + */ + @ApiDoc( + method = GET, + path = "/authz/userRoles/user/:user", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all UserRoles for :user", + } + ) + @Override + public Result getUserRolesByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User",user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Get list of roles per user, then add to Roles as we go + Result> rlurd = ques.userRoleDAO.readByUser(trans, user); + if(rlurd.notOK()) { + return Result.err(rlurd); + } + + /* Check for + * 1) is User + * 2) is User's Supervisor + * 3) Has special global access =read permission + * + * If none of the 3, then filter results to NSs in which Calling User has Ns.access * read + */ + boolean mustFilter; + String callingUser = trans.getUserPrincipal().getName(); + NsDAO.Data ndd = new NsDAO.Data(); + + if(user.equals(callingUser)) { + mustFilter = false; + } else { + Organization org = trans.org(); + try { + Identity orgID = org.getIdentity(trans, user); + Identity manager = orgID==null?null:orgID.responsibleTo(); + if(orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) { + mustFilter = false; + } else if(ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) { + mustFilter=false; + } else { + mustFilter = true; + } + } catch (OrganizationException e) { + trans.env().log(e); + mustFilter = true; + } + } + + List content; + if(mustFilter) { + content = new ArrayList<>(rlurd.value.size()); // avoid multi-memory redos + + for(UserRoleDAO.Data data : rlurd.value) { + ndd.name=data.ns; + Result mur = ques.mayUser(trans, callingUser, ndd, Access.read); + if(mur.isOK()){ + content.add(data); + } + } + + } else { + content = rlurd.value; + } + + + @SuppressWarnings("unchecked") + USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES); + // Checked for permission + mapper.userRoles(trans, content, users); + return Result.ok(users); + } + + + @ApiDoc( + method = PUT, + path = "/authz/userRole/user", + params = {}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Set a User's roles to the roles specified in the UserRoleRequest object.", + "WARNING: Roles supplied will be the ONLY roles attached to this user", + "If no roles are supplied, user's roles are reset." + } + ) + @Override + public Result resetRolesForUser(AuthzTrans trans, REQUEST rreq) { + Result rurdd = mapper.userRole(trans, rreq); + final ServiceValidator v = new ServiceValidator(); + if(rurdd.notOKorIsEmpty()) { + return Result.err(rurdd); + } + if (v.user(trans.org(), rurdd.value.user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Set currRoles = new HashSet<>(); + Result> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + currRoles.add(data.role); + } + } + + Result rv = null; + String[] roles; + if(rurdd.value.role==null) { + roles = new String[0]; + } else { + roles = rurdd.value.role.split(","); + } + + for (String role : roles) { + if (v.role(role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + Result rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + rurdd.value.role(rrdd.value); + + Result nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write); + if (nsd.notOK()) { + return Result.err(nsd); + } + Result nsr = ques.deriveNs(trans, role); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + if(currRoles.contains(role)) { + currRoles.remove(role); + } else { + rv = func.addUserRole(trans, rurdd.value); + if (rv.notOK()) { + return rv; + } + } + } + + for (String role : currRoles) { + rurdd.value.role(trans,ques,role); + rv = ques.userRoleDAO.delete(trans, rurdd.value, false); + if(rv.notOK()) { + trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist"); + // return rv; // if it doesn't exist, don't error out + } + + } + + return Result.ok(); + + } + + @ApiDoc( + method = PUT, + path = "/authz/userRole/role", + params = {}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Set a Role's users to the users specified in the UserRoleRequest object.", + "WARNING: Users supplied will be the ONLY users attached to this role", + "If no users are supplied, role's users are reset." + } + ) + @Override + public Result resetUsersForRole(AuthzTrans trans, REQUEST rreq) { + Result rurdd = mapper.userRole(trans, rreq); + if(rurdd.notOKorIsEmpty()) { + return Result.err(rurdd); + } + final ServiceValidator v = new ServiceValidator(); + if (v.user_role(rurdd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + RoleDAO.Data rd = RoleDAO.Data.decode(rurdd.value); + + Result nsd = ques.mayUser(trans, trans.user(), rd, Access.write); + if (nsd.notOK()) { + return Result.err(nsd); + } + + Result nsr = ques.deriveNs(trans, rurdd.value.role); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Set currUsers = new HashSet<>(); + Result> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + currUsers.add(data.user); + } + } + + // found when connected remotely to DEVL, can't replicate locally + // inconsistent errors with cmd: role user setTo [nothing] + // deleteUserRole --> read --> get --> cacheIdx(?) + // sometimes returns idx for last added user instead of user passed in + // cache bug? + + + Result rv = null; + String[] users = {}; + if (rurdd.value.user != null) { + users = rurdd.value.user.split(","); + } + + for (String user : users) { + if (v.user(trans.org(), user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + rurdd.value.user = user; + + if(currUsers.contains(user)) { + currUsers.remove(user); + } else { + rv = func.addUserRole(trans, rurdd.value); + if (rv.notOK()) { + return rv; + } + } + } + + for (String user : currUsers) { + rurdd.value.user = user; + rv = ques.userRoleDAO.delete(trans, rurdd.value, false); + if(rv.notOK()) { + trans.info().log(rurdd.value, "expected to be deleted, but not exists"); + return rv; + } + } + + return Result.ok(); + } + + @ApiDoc( + method = GET, + path = "/authz/userRole/extend/:user/:role", + params = { "user|string|true", + "role|string|true" + }, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Extend the Expiration of this User Role by the amount set by Organization", + "Requestor must be allowed to modify the role" + } + ) + @Override + public Result extendUserRole(AuthzTrans trans, String user, String role) { + Organization org = trans.org(); + final ServiceValidator v = new ServiceValidator(); + if(v.user(org, user) + .role(role) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + Result rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write); + boolean mayNotChange; + if((mayNotChange = rcr.notOK()) && !trans.requested(future)) { + return Result.err(rcr); + } + + Result> rr = ques.userRoleDAO.read(trans, user,role); + if(rr.notOK()) { + return Result.err(rr); + } + for(UserRoleDAO.Data userRole : rr.value) { + if(mayNotChange) { // Function exited earlier if !trans.futureRequested + FutureDAO.Data fto = new FutureDAO.Data(); + fto.target=UserRoleDAO.TABLE; + fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]"; + GregorianCalendar now = new GregorianCalendar(); + fto.start = now.getTime(); + fto.expires = org.expiration(now, Expiration.Future).getTime(); + try { + fto.construct = userRole.bytify(); + } catch (IOException e) { + trans.error().log(e, "Error while bytifying UserRole for Future"); + return Result.err(e); + } + + Result rfc = func.createFuture(trans, fto, + userRole.user+'|'+userRole.role, userRole.user, rcr.value, FUTURE_OP.U); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", + userRole.user, + userRole.role); + } else { + return Result.err(rfc); + } + } else { + return func.extendUserRole(trans, userRole, false); + } + } + return Result.err(Result.ERR_NotFound,"This user and role doesn't exist"); + } + + @ApiDoc( + method = DELETE, + path = "/authz/userRole/:user/:role", + params = { "user|string|true", + "role|string|true" + }, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Remove Role :role from User :user." + } + ) + @Override + public Result deleteUserRole(AuthzTrans trans, String usr, String role) { + Validator val = new ServiceValidator(); + if(val.nullOrBlank("User", usr) + .nullOrBlank("Role", role).err()) { + return Result.err(Status.ERR_BadData, val.errs()); + } + + boolean mayNotChange; + Result rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + RoleDAO.Data rdd = rrdd.value; + Result rns = ques.mayUser(trans, trans.user(), rdd, Access.write); + + // Make sure we don't delete the last owner of valid NS + if(rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) { + return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns ); + } + + if(mayNotChange=rns.notOK()) { + if(!trans.requested(future)) { + return Result.err(rns); + } + } + + Result> rulr; + if((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) { + return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not " + + "Assigned to the Role [ " + role + " ]"); + } + + UserRoleDAO.Data userRole = rulr.value.get(0); + if(mayNotChange) { // Function exited earlier if !trans.futureRequested + FutureDAO.Data fto = new FutureDAO.Data(); + fto.target=UserRoleDAO.TABLE; + fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]"; + GregorianCalendar now = new GregorianCalendar(); + fto.start = now.getTime(); + fto.expires = trans.org().expiration(now, Expiration.Future).getTime(); + + Result rfc = func.createFuture(trans, fto, + userRole.user+'|'+userRole.role, userRole.user, rns.value, FUTURE_OP.D); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", + userRole.user, + userRole.role); + } else { + return Result.err(rfc); + } + } else { + return ques.userRoleDAO.delete(trans, rulr.value.get(0), false); + } + } + + @ApiDoc( + method = GET, + path = "/authz/userRole/:user/:role", + params = {"user|string|true", + "role|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Returns the User (with Expiration date from listed User/Role) if it exists" + } + ) + @Override + public Result getUserInRole(AuthzTrans trans, String user, String role) { + final Validator v = new ServiceValidator(); + if(v.role(role).nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + +// Result ns = ques.deriveNs(trans, role); +// if (ns.notOK()) return Result.err(ns); +// +// Result rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); + // May calling user see by virtue of the Role + Result rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + Result rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + HashSet userSet = new HashSet<>(); + Result> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + userSet.add(data); + } + } + + @SuppressWarnings("unchecked") + USERS users = (USERS) mapper.newInstance(API.USERS); + mapper.users(trans, userSet, users); + return Result.ok(users); + } + + @ApiDoc( + method = GET, + path = "/authz/users/role/:role", + params = {"user|string|true", + "role|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Returns the User (with Expiration date from listed User/Role) if it exists" + } + ) + @Override + public Result getUsersByRole(AuthzTrans trans, String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role",role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + +// Result ns = ques.deriveNs(trans, role); +// if (ns.notOK()) return Result.err(ns); +// +// Result rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); + // May calling user see by virtue of the Role + Result rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + boolean contactOnly = false; + // Allow the request of any valid user to find the contact of the NS (Owner) + Result rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); + if(rnd.notOK()) { + if(Question.OWNER.equals(rrdd.value.name)) { + contactOnly = true; + } else { + return Result.err(rnd); + } + } + + HashSet userSet = new HashSet<>(); + Result> rlurd = ques.userRoleDAO.readByRole(trans, role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + if(contactOnly) { //scrub data + // Can't change actual object, or will mess up the cache. + UserRoleDAO.Data scrub = new UserRoleDAO.Data(); + scrub.ns = data.ns; + scrub.rname = data.rname; + scrub.role = data.role; + scrub.user = data.user; + userSet.add(scrub); + } else { + userSet.add(data); + } + } + } + + @SuppressWarnings("unchecked") + USERS users = (USERS) mapper.newInstance(API.USERS); + mapper.users(trans, userSet, users); + return Result.ok(users); + } + + /** + * getUsersByPermission + */ @ApiDoc( method = GET, path = "/authz/users/perm/:type/:instance/:action", - params = { "type|string|true", - "instance|string|true", - "action|string|true" - }, + params = { "type|string|true", + "instance|string|true", + "action|string|true" + }, expectedCode = 200, errorCodes = {404,406}, text = { "List all Users that have Permission specified by :type :instance :action", - } + } ) - @Override - public Result getUsersByPermission(AuthzTrans trans, String type, String instance, String action) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Type",type) - .nullOrBlank("Instance",instance) - .nullOrBlank("Action",action) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result nss = ques.deriveNsSplit(trans, type); - if(nss.notOK()) { - return Result.err(nss); - } - - Result> nsd = ques.nsDAO.read(trans, nss.value.ns); - if (nsd.notOK()) { - return Result.err(nsd); - } - - boolean allInstance = ASTERIX.equals(instance); - boolean allAction = ASTERIX.equals(action); - // Get list of roles per Permission, - // Then loop through Roles to get Users - // Note: Use Sets to avoid processing or responding with Duplicates - Set roleUsed = new HashSet<>(); - Set userSet = new HashSet<>(); - - if(!nss.isEmpty()) { - Result> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name); - if(rlp.isOKhasData()) { - for(PermDAO.Data pd : rlp.value) { - if((allInstance || pd.instance.equals(instance)) && - (allAction || pd.action.equals(action))) { - if(ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) { - for(String role : pd.roles) { - if(!roleUsed.contains(role)) { // avoid evaluating Role many times - roleUsed.add(role); - Result> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.')); - if(rlurd.isOKhasData()) { - for(UserRoleDAO.Data urd : rlurd.value) { - userSet.add(urd); - } - } - } - } - } - } - } - } - } - @SuppressWarnings("unchecked") - USERS users = (USERS) mapper.newInstance(API.USERS); - mapper.users(trans, userSet, users); - return Result.ok(users); - } + @Override + public Result getUsersByPermission(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Type",type) + .nullOrBlank("Instance",instance) + .nullOrBlank("Action",action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result nss = ques.deriveNsSplit(trans, type); + if(nss.notOK()) { + return Result.err(nss); + } + + Result> nsd = ques.nsDAO.read(trans, nss.value.ns); + if (nsd.notOK()) { + return Result.err(nsd); + } + + boolean allInstance = ASTERIX.equals(instance); + boolean allAction = ASTERIX.equals(action); + // Get list of roles per Permission, + // Then loop through Roles to get Users + // Note: Use Sets to avoid processing or responding with Duplicates + Set roleUsed = new HashSet<>(); + Set userSet = new HashSet<>(); + + if(!nss.isEmpty()) { + Result> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name); + if(rlp.isOKhasData()) { + for(PermDAO.Data pd : rlp.value) { + if((allInstance || pd.instance.equals(instance)) && + (allAction || pd.action.equals(action))) { + if(ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) { + for(String role : pd.roles) { + if(!roleUsed.contains(role)) { // avoid evaluating Role many times + roleUsed.add(role); + Result> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.')); + if(rlurd.isOKhasData()) { + for(UserRoleDAO.Data urd : rlurd.value) { + userSet.add(urd); + } + } + } + } + } + } + } + } + } + @SuppressWarnings("unchecked") + USERS users = (USERS) mapper.newInstance(API.USERS); + mapper.users(trans, userSet, users); + return Result.ok(users); + } /*********************************** * HISTORY - ***********************************/ - @Override - public Result getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User",user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rnd; - // Users may look at their own data - if(trans.user().equals(user)) { - // Users may look at their own data - } else { - int at = user.indexOf('@'); - if(at>=0 && trans.org().getRealm().equals(user.substring(at+1))) { - NsDAO.Data nsd = new NsDAO.Data(); - nsd.name = Question.domain2ns(user); - rnd = ques.mayUser(trans, trans.user(), nsd, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - } else { - rnd = ques.validNSOfDomain(trans, user); - if(rnd.notOK()) { - return Result.err(rnd); - } - - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - } - } - Result> resp = ques.historyDAO.readByUser(trans, user, yyyymm); - if(resp.notOK()) { - return Result.err(resp); - } - return mapper.history(trans, resp.value,sort); - } - - @Override - public Result getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role",role).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - Result rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - Result> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm); - if(resp.notOK()) { - return Result.err(resp); - } - return mapper.history(trans, resp.value,sort); - } - - @Override - public Result getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Type",type) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of") - Result rnd = ques.deriveNs(trans,type); - if(rnd.notOK()) { - return Result.err(rnd); - } - - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - Result> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm); - if(resp.notOK()) { - return Result.err(resp); - } - return mapper.history(trans, resp.value,sort); - } - - @Override - public Result getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS",ns) - .err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result rnd = ques.deriveNs(trans,ns); - if(rnd.notOK()) { - return Result.err(rnd); - } - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - Result> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm); - if(resp.notOK()) { - return Result.err(resp); - } - return mapper.history(trans, resp.value,sort); - } + ***********************************/ + @Override + public Result getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User",user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rnd; + // Users may look at their own data + if(trans.user().equals(user)) { + // Users may look at their own data + } else { + int at = user.indexOf('@'); + if(at>=0 && trans.org().getRealm().equals(user.substring(at+1))) { + NsDAO.Data nsd = new NsDAO.Data(); + nsd.name = Question.domain2ns(user); + rnd = ques.mayUser(trans, trans.user(), nsd, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + } else { + rnd = ques.validNSOfDomain(trans, user); + if(rnd.notOK()) { + return Result.err(rnd); + } + + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + } + } + Result> resp = ques.historyDAO.readByUser(trans, user, yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } + + @Override + public Result getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role",role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + Result rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + Result> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } + + @Override + public Result getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Type",type) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of") + Result rnd = ques.deriveNs(trans,type); + if(rnd.notOK()) { + return Result.err(rnd); + } + + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + Result> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } + + @Override + public Result getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS",ns) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rnd = ques.deriveNs(trans,ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Result> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } /*********************************** * DELEGATE ***********************************/ - @Override - public Result createDelegate(final AuthzTrans trans, REQUEST base) { - return createOrUpdateDelegate(trans, base, Question.Access.create); - } - - @Override - public Result updateDelegate(AuthzTrans trans, REQUEST base) { - return createOrUpdateDelegate(trans, base, Question.Access.write); - } - - - private Result createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) { - final Result rd = mapper.delegate(trans, base); - final ServiceValidator v = new ServiceValidator(); - if(v.delegate(trans.org(),rd).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - final DelegateDAO.Data dd = rd.value; - - Result> ddr = ques.delegateDAO.read(trans, dd); - if(access==Access.create && ddr.isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate); - } else if(access!=Access.create && ddr.notOKorIsEmpty()) { - return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name()); - } - Result rv = ques.mayUser(trans, dd, access); - if(rv.notOK()) { - return rv; - } - - Result fd = mapper.future(trans,DelegateDAO.TABLE,base, dd, false, - new Mapper.Memo() { - @Override - public String get() { - StringBuilder sb = new StringBuilder(); - sb.append(access.name()); - sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); - sb.append("Delegate "); - sb.append(access==Access.create?"[":"to ["); - sb.append(rd.value.delegate); - sb.append("] for ["); - sb.append(rd.value.user); - sb.append(']'); - return sb.toString(); - } - }, - new MayChange() { - @Override - public Result mayChange() { - return Result.ok(); // Validate in code above - } - }); - - switch(fd.status) { - case OK: - Result rfc = func.createFuture(trans, fd.value, - dd.user, trans.user(),null, access==Access.create?FUTURE_OP.C:FUTURE_OP.U); - if(rfc.isOK()) { - return Result.err(Status.ACC_Future, "Delegate for [%s]", - dd.user); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - if(access==Access.create) { - Result rdr = ques.delegateDAO.create(trans, dd); - if(rdr.isOK()) { - return Result.ok(); - } else { - return Result.err(rdr); - } - } else { - return ques.delegateDAO.update(trans, dd); - } - default: - return Result.err(fd); - } - } - - @Override - public Result deleteDelegate(AuthzTrans trans, REQUEST base) { - final Result rd = mapper.delegate(trans, base); - final Validator v = new ServiceValidator(); - if(v.notOK(rd).nullOrBlank("User", rd.value.user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> ddl; - if((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) { - return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); - } - final DelegateDAO.Data dd = ddl.value.get(0); - Result rv = ques.mayUser(trans, dd, Access.write); - if(rv.notOK()) { - return rv; - } - - return ques.delegateDAO.delete(trans, dd, false); - } - - @Override - public Result deleteDelegate(AuthzTrans trans, String userName) { - DelegateDAO.Data dd = new DelegateDAO.Data(); - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", userName).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - dd.user = userName; - Result> ddl; - if((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) { - return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); - } - dd = ddl.value.get(0); - Result rv = ques.mayUser(trans, dd, Access.write); - if(rv.notOK()) { - return rv; - } - - return ques.delegateDAO.delete(trans, dd, false); - } - - @Override - public Result getDelegatesByUser(AuthzTrans trans, String user) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - DelegateDAO.Data ddd = new DelegateDAO.Data(); - ddd.user = user; - ddd.delegate = null; - Result rv = ques.mayUser(trans, ddd, Access.read); - if(rv.notOK()) { - return Result.err(rv); - } - - TimeTaken tt = trans.start("Get delegates for a user", Env.SUB); - - Result> dbDelgs = ques.delegateDAO.read(trans, user); - try { - if (dbDelgs.isOKhasData()) { - return mapper.delegate(dbDelgs.value); - } else { - return Result.err(Status.ERR_DelegateNotFound,"No Delegate found for [%s]",user); - } - } finally { - tt.done(); - } - } - - @Override - public Result getDelegatesByDelegate(AuthzTrans trans, String delegate) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Delegate", delegate).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - DelegateDAO.Data ddd = new DelegateDAO.Data(); - ddd.user = delegate; - Result rv = ques.mayUser(trans, ddd, Access.read); - if(rv.notOK()) { - return Result.err(rv); - } - - TimeTaken tt = trans.start("Get users for a delegate", Env.SUB); - - Result> dbDelgs = ques.delegateDAO.readByDelegate(trans, delegate); - try { - if (dbDelgs.isOKhasData()) { - return mapper.delegate(dbDelgs.value); - } else { - return Result.err(Status.ERR_DelegateNotFound,"Delegate [%s] is not delegating for anyone.",delegate); - } - } finally { - tt.done(); - } - } + @Override + public Result createDelegate(final AuthzTrans trans, REQUEST base) { + return createOrUpdateDelegate(trans, base, Question.Access.create); + } + + @Override + public Result updateDelegate(AuthzTrans trans, REQUEST base) { + return createOrUpdateDelegate(trans, base, Question.Access.write); + } + + + private Result createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) { + final Result rd = mapper.delegate(trans, base); + final ServiceValidator v = new ServiceValidator(); + if(v.delegate(trans.org(),rd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + final DelegateDAO.Data dd = rd.value; + + Result> ddr = ques.delegateDAO.read(trans, dd); + if(access==Access.create && ddr.isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate); + } else if(access!=Access.create && ddr.notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name()); + } + Result rv = ques.mayUser(trans, dd, access); + if(rv.notOK()) { + return rv; + } + + Result fd = mapper.future(trans,DelegateDAO.TABLE,base, dd, false, + new Mapper.Memo() { + @Override + public String get() { + StringBuilder sb = new StringBuilder(); + sb.append(access.name()); + sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); + sb.append("Delegate "); + sb.append(access==Access.create?"[":"to ["); + sb.append(rd.value.delegate); + sb.append("] for ["); + sb.append(rd.value.user); + sb.append(']'); + return sb.toString(); + } + }, + new MayChange() { + @Override + public Result mayChange() { + return Result.ok(); // Validate in code above + } + }); + + switch(fd.status) { + case OK: + Result rfc = func.createFuture(trans, fd.value, + dd.user, trans.user(),null, access==Access.create?FUTURE_OP.C:FUTURE_OP.U); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Delegate for [%s]", + dd.user); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + if(access==Access.create) { + Result rdr = ques.delegateDAO.create(trans, dd); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + } else { + return ques.delegateDAO.update(trans, dd); + } + default: + return Result.err(fd); + } + } + + @Override + public Result deleteDelegate(AuthzTrans trans, REQUEST base) { + final Result rd = mapper.delegate(trans, base); + final Validator v = new ServiceValidator(); + if(v.notOK(rd).nullOrBlank("User", rd.value.user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> ddl; + if((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) { + return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); + } + final DelegateDAO.Data dd = ddl.value.get(0); + Result rv = ques.mayUser(trans, dd, Access.write); + if(rv.notOK()) { + return rv; + } + + return ques.delegateDAO.delete(trans, dd, false); + } + + @Override + public Result deleteDelegate(AuthzTrans trans, String userName) { + DelegateDAO.Data dd = new DelegateDAO.Data(); + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", userName).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + dd.user = userName; + Result> ddl; + if((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) { + return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); + } + dd = ddl.value.get(0); + Result rv = ques.mayUser(trans, dd, Access.write); + if(rv.notOK()) { + return rv; + } + + return ques.delegateDAO.delete(trans, dd, false); + } + + @Override + public Result getDelegatesByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + DelegateDAO.Data ddd = new DelegateDAO.Data(); + ddd.user = user; + ddd.delegate = null; + Result rv = ques.mayUser(trans, ddd, Access.read); + if(rv.notOK()) { + return Result.err(rv); + } + + TimeTaken tt = trans.start("Get delegates for a user", Env.SUB); + + Result> dbDelgs = ques.delegateDAO.read(trans, user); + try { + if (dbDelgs.isOKhasData()) { + return mapper.delegate(dbDelgs.value); + } else { + return Result.err(Status.ERR_DelegateNotFound,"No Delegate found for [%s]",user); + } + } finally { + tt.done(); + } + } + + @Override + public Result getDelegatesByDelegate(AuthzTrans trans, String delegate) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Delegate", delegate).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + DelegateDAO.Data ddd = new DelegateDAO.Data(); + ddd.user = delegate; + Result rv = ques.mayUser(trans, ddd, Access.read); + if(rv.notOK()) { + return Result.err(rv); + } + + TimeTaken tt = trans.start("Get users for a delegate", Env.SUB); + + Result> dbDelgs = ques.delegateDAO.readByDelegate(trans, delegate); + try { + if (dbDelgs.isOKhasData()) { + return mapper.delegate(dbDelgs.value); + } else { + return Result.err(Status.ERR_DelegateNotFound,"Delegate [%s] is not delegating for anyone.",delegate); + } + } finally { + tt.done(); + } + } /*********************************** * APPROVAL ***********************************/ - private static final String APPR_FMT = "actor=%s, action=%s, operation=\"%s\", requestor=%s, delegator=%s"; - @Override - public Result updateApproval(AuthzTrans trans, APPROVALS approvals) { - Result> rlad = mapper.approvals(approvals); - if(rlad.notOK()) { - return Result.err(rlad); - } - int numApprs = rlad.value.size(); - if(numApprs<1) { - return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating"); - } - int numProcessed = 0; - String user = trans.user(); - - Result> curr; - Lookup> apprByTicket=null; - for(ApprovalDAO.Data updt : rlad.value) { - if(updt.ticket!=null) { - curr = ques.approvalDAO.readByTicket(trans, updt.ticket); - if(curr.isOKhasData()) { - final List add = curr.value; - apprByTicket = new Lookup>() { // Store a Pre-Lookup - @Override - public List get(AuthzTrans trans, Object ... noop) { - return add; - } - }; - } - } else if(updt.id!=null) { - curr = ques.approvalDAO.read(trans, updt); - } else if(updt.approver!=null) { - curr = ques.approvalDAO.readByApprover(trans, updt.approver); - } else { - return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update"); - } - - if(curr.isOKhasData()) { - Map>> delegateCache = new HashMap<>(); - Map futureCache = new HashMap<>(); - FutureDAO.Data hasDeleted = new FutureDAO.Data(); - - for(ApprovalDAO.Data cd : curr.value) { - if("pending".equals(cd.status)) { - // Check for right record. Need ID, or (Ticket&Trans.User==Appr) - // If Default ID - boolean delegatedAction = ques.isDelegated(trans, user, cd.approver, delegateCache); - String delegator = cd.approver; - if(updt.id!=null || - (updt.ticket!=null && user.equals(cd.approver)) || - (updt.ticket!=null && delegatedAction)) { - if(updt.ticket.equals(cd.ticket)) { - Changed ch = new Changed(); - cd.id = ch.changed(cd.id,updt.id); -// cd.ticket = changed(cd.ticket,updt.ticket); - cd.user = ch.changed(cd.user,updt.user); - cd.approver = ch.changed(cd.approver,updt.approver); - cd.type = ch.changed(cd.type,updt.type); - cd.status = ch.changed(cd.status,updt.status); - cd.memo = ch.changed(cd.memo,updt.memo); - cd.operation = ch.changed(cd.operation,updt.operation); - cd.updated = ch.changed(cd.updated,updt.updated==null?new Date():updt.updated); - if(updt.status.equals("denied")) { - cd.last_notified = null; - } - if(cd.ticket!=null) { - FutureDAO.Data fdd = futureCache.get(cd.ticket); - if(fdd==null) { // haven't processed ticket yet - Result rfdd = ques.futureDAO.readPrimKey(trans, cd.ticket); - if(rfdd.isOK()) { - fdd = rfdd.value; // null is ok - } else { - fdd = hasDeleted; - } - futureCache.put(cd.ticket, fdd); // processed this Ticket... don't do others on this ticket - } - if(fdd==hasDeleted) { // YES, by Object - cd.ticket = null; - cd.status = "ticketDeleted"; - ch.hasChanged(true); - } else { - FUTURE_OP fop = FUTURE_OP.toFO(cd.operation); - if(fop==null) { - trans.info().printf("Approval Status %s is not actionable",cd.status); - } else if(apprByTicket!=null) { - Result rv = func.performFutureOp(trans, fop, fdd, apprByTicket,func.urDBLookup); - if (rv.isOK()) { - switch(rv.value) { - case E: - if (delegatedAction) { - trans.audit().printf(APPR_FMT,user,updt.status,cd.memo,cd.user,delegator); - } - futureCache.put(cd.ticket, hasDeleted); - break; - case D: - case L: - ch.hasChanged(true); - trans.audit().printf(APPR_FMT,user,rv.value.desc(),cd.memo,cd.user,delegator); - futureCache.put(cd.ticket, hasDeleted); - break; - default: - } - } else { - trans.info().log(rv.toString()); - } - } - - } - ++numProcessed; - } - if(ch.hasChanged()) { - ques.approvalDAO.update(trans, cd, true); - } - } - } - } - } - } - } - - if(numApprs==numProcessed) { - return Result.ok(); - } - return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed"); - - } - - private static class Changed { - private boolean hasChanged = false; - - public T changed(T src, T proposed) { - if(proposed==null || (src!=null && src.equals(proposed))) { - return src; - } - hasChanged=true; - return proposed; - } - - public void hasChanged(boolean b) { - hasChanged=b; - } - - public boolean hasChanged() { - return hasChanged; - } - } - - @Override - public Result getApprovalsByUser(AuthzTrans trans, String user) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - Result> rapd = ques.approvalDAO.readByUser(trans, user); - if(rapd.isOK()) { - return mapper.approvals(rapd.value); - } else { - return Result.err(rapd); - } + private static final String APPR_FMT = "actor=%s, action=%s, operation=\"%s\", requestor=%s, delegator=%s"; + @Override + public Result updateApproval(AuthzTrans trans, APPROVALS approvals) { + Result> rlad = mapper.approvals(approvals); + if(rlad.notOK()) { + return Result.err(rlad); + } + int numApprs = rlad.value.size(); + if(numApprs<1) { + return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating"); + } + int numProcessed = 0; + String user = trans.user(); + + Result> curr; + Lookup> apprByTicket=null; + for(ApprovalDAO.Data updt : rlad.value) { + if(updt.ticket!=null) { + curr = ques.approvalDAO.readByTicket(trans, updt.ticket); + if(curr.isOKhasData()) { + final List add = curr.value; + apprByTicket = new Lookup>() { // Store a Pre-Lookup + @Override + public List get(AuthzTrans trans, Object ... noop) { + return add; + } + }; + } + } else if(updt.id!=null) { + curr = ques.approvalDAO.read(trans, updt); + } else if(updt.approver!=null) { + curr = ques.approvalDAO.readByApprover(trans, updt.approver); + } else { + return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update"); + } + + if(curr.isOKhasData()) { + Map>> delegateCache = new HashMap<>(); + Map futureCache = new HashMap<>(); + FutureDAO.Data hasDeleted = new FutureDAO.Data(); + + for(ApprovalDAO.Data cd : curr.value) { + if("pending".equals(cd.status)) { + // Check for right record. Need ID, or (Ticket&Trans.User==Appr) + // If Default ID + boolean delegatedAction = ques.isDelegated(trans, user, cd.approver, delegateCache); + String delegator = cd.approver; + if(updt.id!=null || + (updt.ticket!=null && user.equals(cd.approver)) || + (updt.ticket!=null && delegatedAction)) { + if(updt.ticket.equals(cd.ticket)) { + Changed ch = new Changed(); + cd.id = ch.changed(cd.id,updt.id); +// cd.ticket = changed(cd.ticket,updt.ticket); + cd.user = ch.changed(cd.user,updt.user); + cd.approver = ch.changed(cd.approver,updt.approver); + cd.type = ch.changed(cd.type,updt.type); + cd.status = ch.changed(cd.status,updt.status); + cd.memo = ch.changed(cd.memo,updt.memo); + cd.operation = ch.changed(cd.operation,updt.operation); + cd.updated = ch.changed(cd.updated,updt.updated==null?new Date():updt.updated); + if(updt.status.equals("denied")) { + cd.last_notified = null; + } + if(cd.ticket!=null) { + FutureDAO.Data fdd = futureCache.get(cd.ticket); + if(fdd==null) { // haven't processed ticket yet + Result rfdd = ques.futureDAO.readPrimKey(trans, cd.ticket); + if(rfdd.isOK()) { + fdd = rfdd.value; // null is ok + } else { + fdd = hasDeleted; + } + futureCache.put(cd.ticket, fdd); // processed this Ticket... don't do others on this ticket + } + if(fdd==hasDeleted) { // YES, by Object + cd.ticket = null; + cd.status = "ticketDeleted"; + ch.hasChanged(true); + } else { + FUTURE_OP fop = FUTURE_OP.toFO(cd.operation); + if(fop==null) { + trans.info().printf("Approval Status %s is not actionable",cd.status); + } else if(apprByTicket!=null) { + Result rv = func.performFutureOp(trans, fop, fdd, apprByTicket,func.urDBLookup); + if (rv.isOK()) { + switch(rv.value) { + case E: + if (delegatedAction) { + trans.audit().printf(APPR_FMT,user,updt.status,cd.memo,cd.user,delegator); + } + futureCache.put(cd.ticket, hasDeleted); + break; + case D: + case L: + ch.hasChanged(true); + trans.audit().printf(APPR_FMT,user,rv.value.desc(),cd.memo,cd.user,delegator); + futureCache.put(cd.ticket, hasDeleted); + break; + default: + } + } else { + trans.info().log(rv.toString()); + } + } + + } + ++numProcessed; + } + if(ch.hasChanged()) { + ques.approvalDAO.update(trans, cd, true); + } + } + } + } + } + } + } + + if(numApprs==numProcessed) { + return Result.ok(); + } + return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed"); + + } + + private static class Changed { + private boolean hasChanged = false; + + public T changed(T src, T proposed) { + if(proposed==null || (src!=null && src.equals(proposed))) { + return src; + } + hasChanged=true; + return proposed; + } + + public void hasChanged(boolean b) { + hasChanged=b; + } + + public boolean hasChanged() { + return hasChanged; + } + } + + @Override + public Result getApprovalsByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rapd = ques.approvalDAO.readByUser(trans, user); + if(rapd.isOK()) { + return mapper.approvals(rapd.value); + } else { + return Result.err(rapd); + } } - @Override - public Result getApprovalsByTicket(AuthzTrans trans, String ticket) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Ticket", ticket).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - UUID uuid; - try { - uuid = UUID.fromString(ticket); - } catch (IllegalArgumentException e) { - return Result.err(Status.ERR_BadData,e.getMessage()); - } - - Result> rapd = ques.approvalDAO.readByTicket(trans, uuid); - if(rapd.isOK()) { - return mapper.approvals(rapd.value); - } else { - return Result.err(rapd); - } - } - - @Override - public Result getApprovalsByApprover(AuthzTrans trans, String approver) { - final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Approver", approver).err()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - List listRapds = new ArrayList<>(); - - Result> myRapd = ques.approvalDAO.readByApprover(trans, approver); - if(myRapd.notOK()) { - return Result.err(myRapd); - } - - listRapds.addAll(myRapd.value); - - Result> delegatedFor = ques.delegateDAO.readByDelegate(trans, approver); - if (delegatedFor.isOK()) { - for (DelegateDAO.Data dd : delegatedFor.value) { - if (dd.expires.after(new Date())) { - String delegator = dd.user; - Result> rapd = ques.approvalDAO.readByApprover(trans, delegator); - if (rapd.isOK()) { - for (ApprovalDAO.Data d : rapd.value) { - if (!d.user.equals(trans.user())) { - listRapds.add(d); - } - } - } - } - } - } - - return mapper.approvals(listRapds); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#clearCache(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) - */ - @Override - public Result cacheClear(AuthzTrans trans, String cname) { - if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { - return ques.clearCache(trans,cname); - } - return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear", - trans.user(),ROOT_NS,CACHE,cname); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer) - */ - @Override - public Result cacheClear(AuthzTrans trans, String cname, int[] segment) { - if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { - Result v=null; - for(int i: segment) { - v=ques.cacheClear(trans,cname,i); - } - if(v!=null) { - return v; - } - } - return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear", - trans.user(),ROOT_NS,CACHE,cname); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.AuthzService#dbReset(org.onap.aaf.auth.env.test.AuthzTrans) - */ - @Override - public void dbReset(AuthzTrans trans) { - ques.historyDAO.reportPerhapsReset(trans, null); - } + @Override + public Result getApprovalsByTicket(AuthzTrans trans, String ticket) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Ticket", ticket).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + UUID uuid; + try { + uuid = UUID.fromString(ticket); + } catch (IllegalArgumentException e) { + return Result.err(Status.ERR_BadData,e.getMessage()); + } + + Result> rapd = ques.approvalDAO.readByTicket(trans, uuid); + if(rapd.isOK()) { + return mapper.approvals(rapd.value); + } else { + return Result.err(rapd); + } + } + + @Override + public Result getApprovalsByApprover(AuthzTrans trans, String approver) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Approver", approver).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + List listRapds = new ArrayList<>(); + + Result> myRapd = ques.approvalDAO.readByApprover(trans, approver); + if(myRapd.notOK()) { + return Result.err(myRapd); + } + + listRapds.addAll(myRapd.value); + + Result> delegatedFor = ques.delegateDAO.readByDelegate(trans, approver); + if (delegatedFor.isOK()) { + for (DelegateDAO.Data dd : delegatedFor.value) { + if (dd.expires.after(new Date())) { + String delegator = dd.user; + Result> rapd = ques.approvalDAO.readByApprover(trans, delegator); + if (rapd.isOK()) { + for (ApprovalDAO.Data d : rapd.value) { + if (!d.user.equals(trans.user())) { + listRapds.add(d); + } + } + } + } + } + } + + return mapper.approvals(listRapds); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#clearCache(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @Override + public Result cacheClear(AuthzTrans trans, String cname) { + if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { + return ques.clearCache(trans,cname); + } + return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear", + trans.user(),ROOT_NS,CACHE,cname); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer) + */ + @Override + public Result cacheClear(AuthzTrans trans, String cname, int[] segment) { + if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { + Result v=null; + for(int i: segment) { + v=ques.cacheClear(trans,cname,i); + } + if(v!=null) { + return v; + } + } + return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear", + trans.user(),ROOT_NS,CACHE,cname); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#dbReset(org.onap.aaf.auth.env.test.AuthzTrans) + */ + @Override + public void dbReset(AuthzTrans trans) { + ques.historyDAO.reportPerhapsReset(trans, null); + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java index 01e18510..6d4836d7 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java @@ -32,737 +32,737 @@ import org.onap.aaf.auth.layer.Result; import org.onap.aaf.auth.service.mapper.Mapper; public interface AuthzService { - public Mapper mapper(); - + public Mapper mapper(); + /*********************************** * NAMESPACE ***********************************/ - /** - * - * @param trans - * @param user - * @param ns - * @return - * @throws DAOException - * @throws - */ - public Result createNS(AuthzTrans trans, REQUEST request, NsType type); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result addAdminNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result delAdminNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @param id - * @return - */ - public Result addResponsibleNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @param id - * @return - */ - public Result delResponsibleNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @param key - * @param value - * @return - */ - public Result createNsAttrib(AuthzTrans trans, String ns, String key, String value); - - /** - * - * @param trans - * @param ns - * @param key - * @param value - * @return - */ - public Result updateNsAttrib(AuthzTrans trans, String ns, String key, String value); - - /** - * - * @param trans - * @param ns - * @param key - * @return - */ - public Result deleteNsAttrib(AuthzTrans trans, String ns, String key); - - /** - * - * @param trans - * @param ns - * @param key - * @return - */ - public Result readNsByAttrib(AuthzTrans trans, String key); - - - /** - * - * @param trans - * @param ns - * @return - */ - public Result getNSbyName(AuthzTrans trans, String ns); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getNSbyAdmin(AuthzTrans trans, String user, boolean full); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getNSbyResponsible(AuthzTrans trans, String user, boolean full); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getNSbyEither(AuthzTrans trans, String user, boolean full); - - /** - * - * @param trans - * @param parent - * @return - */ - public Result getNSsChildren(AuthzTrans trans, String parent); - - /** - * - * @param trans - * @param req - * @return - */ - public Result updateNsDescription(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param ns - * @param user - * @return - * @throws DAOException - */ - public Result deleteNS(AuthzTrans trans, String ns); + /** + * + * @param trans + * @param user + * @param ns + * @return + * @throws DAOException + * @throws + */ + public Result createNS(AuthzTrans trans, REQUEST request, NsType type); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result addAdminNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result delAdminNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @param id + * @return + */ + public Result addResponsibleNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @param id + * @return + */ + public Result delResponsibleNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @param key + * @param value + * @return + */ + public Result createNsAttrib(AuthzTrans trans, String ns, String key, String value); + + /** + * + * @param trans + * @param ns + * @param key + * @param value + * @return + */ + public Result updateNsAttrib(AuthzTrans trans, String ns, String key, String value); + + /** + * + * @param trans + * @param ns + * @param key + * @return + */ + public Result deleteNsAttrib(AuthzTrans trans, String ns, String key); + + /** + * + * @param trans + * @param ns + * @param key + * @return + */ + public Result readNsByAttrib(AuthzTrans trans, String key); + + + /** + * + * @param trans + * @param ns + * @return + */ + public Result getNSbyName(AuthzTrans trans, String ns); + + /** + * + * @param trans + * @param user + * @return + */ + public Result getNSbyAdmin(AuthzTrans trans, String user, boolean full); + + /** + * + * @param trans + * @param user + * @return + */ + public Result getNSbyResponsible(AuthzTrans trans, String user, boolean full); + + /** + * + * @param trans + * @param user + * @return + */ + public Result getNSbyEither(AuthzTrans trans, String user, boolean full); + + /** + * + * @param trans + * @param parent + * @return + */ + public Result getNSsChildren(AuthzTrans trans, String parent); + + /** + * + * @param trans + * @param req + * @return + */ + public Result updateNsDescription(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param ns + * @param user + * @return + * @throws DAOException + */ + public Result deleteNS(AuthzTrans trans, String ns); /*********************************** * PERM ***********************************/ - /** - * - * @param trans - * @param rreq - * @return - * @throws DAOException - * @throws MappingException - */ - public Result createPerm(AuthzTrans trans, REQUEST rreq); - - /** - * - * @param trans - * @param childPerm - * @return - * @throws DAOException - */ - public Result getPermsByType(AuthzTrans trans, String perm); - - /** - * - * @param trans - * @param type - * @param instance - * @param action - * @return - */ - public Result getPermsByName(AuthzTrans trans, String type, - String instance, String action); - - /** - * Gets all the permissions for a user across all the roles it is assigned to - * @param userName - * @return - * @throws Exception - * @throws Exception - */ - public Result getPermsByUser(AuthzTrans trans, String userName); - - /** - * Gets all the permissions for a user across all the roles it is assigned to, filtered by NS (Scope) - * - * @param trans - * @param user - * @param scopes - * @return - */ - public Result getPermsByUserScope(AuthzTrans trans, String user, String[] scopes); - - - /** - * Gets all the permissions for a user across all the roles it is assigned to - * - * Add AAF Perms representing the "MayUser" calls if - * 1) Allowed - * 2) User has equivalent permission - * - * @param userName - * @return - * @throws Exception - * @throws Exception - */ - public Result getPermsByUser(AuthzTrans trans, PERMS perms, String userName); - - /** - * - * Gets all the permissions for a user across all the roles it is assigned to - * - * @param roleName - * @return - * @throws Exception - */ - public Result getPermsByRole(AuthzTrans trans, String roleName); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result getPermsByNS(AuthzTrans trans, String ns); - - /** - * rename permission - * - * @param trans - * @param rreq - * @param isRename - * @param origType - * @param origInstance - * @param origAction - * @return - */ - public Result renamePerm(AuthzTrans trans, REQUEST rreq, String origType, String origInstance, String origAction); - - /** - * - * @param trans - * @param req - * @return - */ - public Result updatePermDescription(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param from - * @return - */ - public Result resetPermRoles(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @return - * @throws Exception - */ - public Result deletePerm(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param user - * @param perm - * @param type - * @param action - * @return - * @throws Exception - */ - Result deletePerm(AuthzTrans trans, String perm, String type, String action); + /** + * + * @param trans + * @param rreq + * @return + * @throws DAOException + * @throws MappingException + */ + public Result createPerm(AuthzTrans trans, REQUEST rreq); + + /** + * + * @param trans + * @param childPerm + * @return + * @throws DAOException + */ + public Result getPermsByType(AuthzTrans trans, String perm); + + /** + * + * @param trans + * @param type + * @param instance + * @param action + * @return + */ + public Result getPermsByName(AuthzTrans trans, String type, + String instance, String action); + + /** + * Gets all the permissions for a user across all the roles it is assigned to + * @param userName + * @return + * @throws Exception + * @throws Exception + */ + public Result getPermsByUser(AuthzTrans trans, String userName); + + /** + * Gets all the permissions for a user across all the roles it is assigned to, filtered by NS (Scope) + * + * @param trans + * @param user + * @param scopes + * @return + */ + public Result getPermsByUserScope(AuthzTrans trans, String user, String[] scopes); + + + /** + * Gets all the permissions for a user across all the roles it is assigned to + * + * Add AAF Perms representing the "MayUser" calls if + * 1) Allowed + * 2) User has equivalent permission + * + * @param userName + * @return + * @throws Exception + * @throws Exception + */ + public Result getPermsByUser(AuthzTrans trans, PERMS perms, String userName); + + /** + * + * Gets all the permissions for a user across all the roles it is assigned to + * + * @param roleName + * @return + * @throws Exception + */ + public Result getPermsByRole(AuthzTrans trans, String roleName); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result getPermsByNS(AuthzTrans trans, String ns); + + /** + * rename permission + * + * @param trans + * @param rreq + * @param isRename + * @param origType + * @param origInstance + * @param origAction + * @return + */ + public Result renamePerm(AuthzTrans trans, REQUEST rreq, String origType, String origInstance, String origAction); + + /** + * + * @param trans + * @param req + * @return + */ + public Result updatePermDescription(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param from + * @return + */ + public Result resetPermRoles(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @return + * @throws Exception + */ + public Result deletePerm(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param user + * @param perm + * @param type + * @param action + * @return + * @throws Exception + */ + Result deletePerm(AuthzTrans trans, String perm, String type, String action); /*********************************** * ROLE ***********************************/ - /** - * - * @param trans - * @param user - * @param role - * @param approvers - * @return - * @throws DAOException - * @throws Exception - */ - public Result createRole(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getRolesByName(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param user - * @return - * @throws DAOException - */ - public Result getRolesByUser(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getRolesByNS(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param name - * @return - */ - public Result getRolesByNameOnly(AuthzTrans trans, String name); - - /** - * - * @param trans - * @param type - * @param instance - * @param action - * @return - */ - public Result getRolesByPerm(AuthzTrans trans, String type, String instance, String action); - - /** - * - * @param trans - * @param req - * @return - */ - public Result updateRoleDescription(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param rreq - * @return - * @throws DAOException - */ - public Result addPermToRole(AuthzTrans trans, REQUEST rreq); - - - /** - * - * @param trans - * @param rreq - * @return - * @throws DAOException - */ - Result delPermFromRole(AuthzTrans trans, REQUEST rreq); - - /** - * Itemized key delete - * @param trans - * @param role - * @param type - * @param instance - * @param action - * @return - */ - public Result delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action); - - /** - * - * @param trans - * @param user - * @param role - * @return - * @throws DAOException - * @throws MappingException - */ - public Result deleteRole(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param req - * @return - */ - public Result deleteRole(AuthzTrans trans, REQUEST req); + /** + * + * @param trans + * @param user + * @param role + * @param approvers + * @return + * @throws DAOException + * @throws Exception + */ + public Result createRole(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param role + * @return + */ + public Result getRolesByName(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param user + * @return + * @throws DAOException + */ + public Result getRolesByUser(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param user + * @return + */ + public Result getRolesByNS(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param name + * @return + */ + public Result getRolesByNameOnly(AuthzTrans trans, String name); + + /** + * + * @param trans + * @param type + * @param instance + * @param action + * @return + */ + public Result getRolesByPerm(AuthzTrans trans, String type, String instance, String action); + + /** + * + * @param trans + * @param req + * @return + */ + public Result updateRoleDescription(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param rreq + * @return + * @throws DAOException + */ + public Result addPermToRole(AuthzTrans trans, REQUEST rreq); + + + /** + * + * @param trans + * @param rreq + * @return + * @throws DAOException + */ + Result delPermFromRole(AuthzTrans trans, REQUEST rreq); + + /** + * Itemized key delete + * @param trans + * @param role + * @param type + * @param instance + * @param action + * @return + */ + public Result delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action); + + /** + * + * @param trans + * @param user + * @param role + * @return + * @throws DAOException + * @throws MappingException + */ + public Result deleteRole(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param req + * @return + */ + public Result deleteRole(AuthzTrans trans, REQUEST req); /*********************************** * CRED ***********************************/ - /** - * - * @param trans - * @param from - * @return - */ - Result createUserCred(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @return - */ - Result changeUserCred(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @param days - * @return - */ - Result extendUserCred(AuthzTrans trans, REQUEST from, String days); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result getCredsByNS(AuthzTrans trans, String ns); - - /** - * - * @param trans - * @param id - * @return - */ - public Result getCredsByID(AuthzTrans trans, String id); - - /** - * - * @param trans - * @param req - * @param id - * @return - */ - public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id); - - /** - * - * @param trans - * @param credReq - * @return - */ - public Result deleteUserCred(AuthzTrans trans, REQUEST credReq); - - /** - * - * @param trans - * @param user - * @return - * @throws Exception - */ - public Result doesCredentialMatch(AuthzTrans trans, REQUEST credReq); - - /** - * - * @param trans - * @param basicAuth - * @return - */ - public Result validateBasicAuth(AuthzTrans trans, String basicAuth); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUsersByRole(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUserInRole(AuthzTrans trans, String user, String role); - - /** - * - * @param trans - * @param type - * @param instance - * @param action - * @return - */ - public Result getUsersByPermission(AuthzTrans trans,String type, String instance, String action); - - + /** + * + * @param trans + * @param from + * @return + */ + Result createUserCred(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @return + */ + Result changeUserCred(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @param days + * @return + */ + Result extendUserCred(AuthzTrans trans, REQUEST from, String days); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result getCredsByNS(AuthzTrans trans, String ns); + + /** + * + * @param trans + * @param id + * @return + */ + public Result getCredsByID(AuthzTrans trans, String id); + + /** + * + * @param trans + * @param req + * @param id + * @return + */ + public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id); + + /** + * + * @param trans + * @param credReq + * @return + */ + public Result deleteUserCred(AuthzTrans trans, REQUEST credReq); + + /** + * + * @param trans + * @param user + * @return + * @throws Exception + */ + public Result doesCredentialMatch(AuthzTrans trans, REQUEST credReq); + + /** + * + * @param trans + * @param basicAuth + * @return + */ + public Result validateBasicAuth(AuthzTrans trans, String basicAuth); + + /** + * + * @param trans + * @param role + * @return + */ + public Result getUsersByRole(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param role + * @return + */ + public Result getUserInRole(AuthzTrans trans, String user, String role); + + /** + * + * @param trans + * @param type + * @param instance + * @param action + * @return + */ + public Result getUsersByPermission(AuthzTrans trans,String type, String instance, String action); + + /*********************************** * USER-ROLE ***********************************/ - /** - * - * @param trans - * @param user - * @param request - * @return - * @throws Exception - */ - public Result createUserRole(AuthzTrans trans, REQUEST request); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUserRolesByRole(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUserRolesByUser(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param from - * @return - */ - public Result resetRolesForUser(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @return - */ - public Result resetUsersForRole(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param user - * @param role - * @return - */ - public Result extendUserRole(AuthzTrans trans, String user, - String role); - - /** - * - * @param trans - * @param user - * @param usr - * @param role - * @return - * @throws DAOException - */ - public Result deleteUserRole(AuthzTrans trans, String usr, String role); + /** + * + * @param trans + * @param user + * @param request + * @return + * @throws Exception + */ + public Result createUserRole(AuthzTrans trans, REQUEST request); + + /** + * + * @param trans + * @param role + * @return + */ + public Result getUserRolesByRole(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param role + * @return + */ + public Result getUserRolesByUser(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param from + * @return + */ + public Result resetRolesForUser(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @return + */ + public Result resetUsersForRole(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param user + * @param role + * @return + */ + public Result extendUserRole(AuthzTrans trans, String user, + String role); + + /** + * + * @param trans + * @param user + * @param usr + * @param role + * @return + * @throws DAOException + */ + public Result deleteUserRole(AuthzTrans trans, String usr, String role); /*********************************** * HISTORY - ***********************************/ - /** - * - * @param trans - * @param user - * @param yyyymm - * @return - */ - public Result getHistoryByUser(AuthzTrans trans, String user, int[] yyyymm, int sort); - - /** - * - * @param trans - * @param subj - * @param yyyymm - * @param sort - * @return - */ - public Result getHistoryByRole(AuthzTrans trans, String subj, int[] yyyymm, int sort); - - /** - * - * @param trans - * @param subj - * @param yyyymm - * @param sort - * @return - */ - public Result getHistoryByPerm(AuthzTrans trans, String subj, int[] yyyymm, int sort); - - /** - * - * @param trans - * @param subj - * @param yyyymm - * @param sort - * @return - */ - public Result getHistoryByNS(AuthzTrans trans, String subj, int[] yyyymm, int sort); + ***********************************/ + /** + * + * @param trans + * @param user + * @param yyyymm + * @return + */ + public Result getHistoryByUser(AuthzTrans trans, String user, int[] yyyymm, int sort); + + /** + * + * @param trans + * @param subj + * @param yyyymm + * @param sort + * @return + */ + public Result getHistoryByRole(AuthzTrans trans, String subj, int[] yyyymm, int sort); + + /** + * + * @param trans + * @param subj + * @param yyyymm + * @param sort + * @return + */ + public Result getHistoryByPerm(AuthzTrans trans, String subj, int[] yyyymm, int sort); + + /** + * + * @param trans + * @param subj + * @param yyyymm + * @param sort + * @return + */ + public Result getHistoryByNS(AuthzTrans trans, String subj, int[] yyyymm, int sort); /*********************************** * DELEGATE ***********************************/ - /** - * - * @param trans - * @param delegates - * @return - * @throws Exception - */ - public Result createDelegate(AuthzTrans trans, REQUEST reqDelegate); - - /** - * - * @param trans - * @param delegates - * @return - * @throws Exception - */ - public Result updateDelegate(AuthzTrans trans, REQUEST reqDelegate); - - /** - * - * @param trans - * @param userName - * @param delegate - * @return - * @throws Exception - */ - public Result deleteDelegate(AuthzTrans trans, REQUEST reqDelegate); - - /** - * - * @param trans - * @param userName - * @return - */ - public Result deleteDelegate(AuthzTrans trans, String userName); - - /** - * - * @param trans - * @param user - * @return - * @throws Exception - */ - public Result getDelegatesByUser(AuthzTrans trans, String user); - - - /** - * - * @param trans - * @param delegate - * @return - */ - public Result getDelegatesByDelegate(AuthzTrans trans, String delegate); + /** + * + * @param trans + * @param delegates + * @return + * @throws Exception + */ + public Result createDelegate(AuthzTrans trans, REQUEST reqDelegate); + + /** + * + * @param trans + * @param delegates + * @return + * @throws Exception + */ + public Result updateDelegate(AuthzTrans trans, REQUEST reqDelegate); + + /** + * + * @param trans + * @param userName + * @param delegate + * @return + * @throws Exception + */ + public Result deleteDelegate(AuthzTrans trans, REQUEST reqDelegate); + + /** + * + * @param trans + * @param userName + * @return + */ + public Result deleteDelegate(AuthzTrans trans, String userName); + + /** + * + * @param trans + * @param user + * @return + * @throws Exception + */ + public Result getDelegatesByUser(AuthzTrans trans, String user); + + + /** + * + * @param trans + * @param delegate + * @return + */ + public Result getDelegatesByDelegate(AuthzTrans trans, String delegate); /*********************************** * APPROVAL ***********************************/ - /** - * - * @param trans - * @param user - * @param approver - * @param status - * @return - */ - public Result updateApproval(AuthzTrans trans, APPROVALS approvals); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getApprovalsByUser(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param ticket - * @return - */ - public Result getApprovalsByTicket(AuthzTrans trans, String ticket); - - /** - * - * @param trans - * @param approver - * @return - */ - public Result getApprovalsByApprover(AuthzTrans trans, String approver); - - /** - * - * @param trans - * @param cname - * @return - */ - public Result cacheClear(AuthzTrans trans, String cname); - - /** - * - * @param trans - * @param cname - * @param segment - * @return - */ - public Result cacheClear(AuthzTrans trans, String cname, int[] segment); - - /** - * - * @param trans - */ - public void dbReset(AuthzTrans trans); + /** + * + * @param trans + * @param user + * @param approver + * @param status + * @return + */ + public Result updateApproval(AuthzTrans trans, APPROVALS approvals); + + /** + * + * @param trans + * @param user + * @return + */ + public Result getApprovalsByUser(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param ticket + * @return + */ + public Result getApprovalsByTicket(AuthzTrans trans, String ticket); + + /** + * + * @param trans + * @param approver + * @return + */ + public Result getApprovalsByApprover(AuthzTrans trans, String approver); + + /** + * + * @param trans + * @param cname + * @return + */ + public Result cacheClear(AuthzTrans trans, String cname); + + /** + * + * @param trans + * @param cname + * @param segment + * @return + */ + public Result cacheClear(AuthzTrans trans, String cname, int[] segment); + + /** + * + * @param trans + */ + public void dbReset(AuthzTrans trans); } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/Code.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/Code.java index ba6e9d10..ac799f4e 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/Code.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/Code.java @@ -26,19 +26,19 @@ import org.onap.aaf.auth.rserv.HttpCode; import org.onap.aaf.auth.service.facade.AuthzFacade; public abstract class Code extends HttpCode implements Cloneable { - public boolean useJSON; + public boolean useJSON; - public Code(AuthzFacade facade, String description, boolean useJSON, String ... roles) { - super(facade, description, roles); - this.useJSON = useJSON; - } - - public D clone(AuthzFacade facade, boolean useJSON) throws Exception { - @SuppressWarnings("unchecked") - D d = (D)clone(); - d.useJSON = useJSON; - d.context = facade; - return d; - } - + public Code(AuthzFacade facade, String description, boolean useJSON, String ... roles) { + super(facade, description, roles); + this.useJSON = useJSON; + } + + public D clone(AuthzFacade facade, boolean useJSON) throws Exception { + @SuppressWarnings("unchecked") + D d = (D)clone(); + d.useJSON = useJSON; + d.context = facade; + return d; + } + } \ No newline at end of file diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/MayChange.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/MayChange.java index 7df43a4c..a1ceb75a 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/MayChange.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/MayChange.java @@ -29,5 +29,5 @@ import org.onap.aaf.auth.layer.Result; * */ public interface MayChange { - public Result mayChange(); + public Result mayChange(); } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java index 79dda326..5213a6e9 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java @@ -40,53 +40,53 @@ import org.onap.aaf.cadi.Symm; * */ public class API_Api { - // Hide Public Constructor - private API_Api() {} - - /** - * Normal Init level APIs - * - * @param authzAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { - //////// - // Overall APIs - /////// - authzAPI.route(HttpMethods.GET,"/api",API.API,new Code(facade,"Document API", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getAPI(trans,resp,authzAPI); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + // Hide Public Constructor + private API_Api() {} + + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { + //////// + // Overall APIs + /////// + authzAPI.route(HttpMethods.GET,"/api",API.API,new Code(facade,"Document API", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getAPI(trans,resp,authzAPI); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - //////// - // Overall Examples - /////// - authzAPI.route(HttpMethods.GET,"/api/example/*",API.VOID,new Code(facade,"Document API", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String pathInfo = req.getPathInfo(); - int question = pathInfo.lastIndexOf('?'); - - pathInfo = pathInfo.substring(13, question<0?pathInfo.length():question);// IMPORTANT, this is size of "/api/example/" - String nameOrContextType=Symm.base64noSplit.decode(pathInfo); - Result r = context.getAPIExample(trans,resp,nameOrContextType, - question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1)) - ); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + //////// + // Overall Examples + /////// + authzAPI.route(HttpMethods.GET,"/api/example/*",API.VOID,new Code(facade,"Document API", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String pathInfo = req.getPathInfo(); + int question = pathInfo.lastIndexOf('?'); + + pathInfo = pathInfo.substring(13, question<0?pathInfo.length():question);// IMPORTANT, this is size of "/api/example/" + String nameOrContextType=Symm.base64noSplit.decode(pathInfo); + Result r = context.getAPIExample(trans,resp,nameOrContextType, + question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1)) + ); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - } + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java index e0c07684..c0836038 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java @@ -36,71 +36,71 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.onap.aaf.auth.service.mapper.Mapper.API; public class API_Approval { - // Hide Public Constructor - private API_Approval() {} - - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + // Hide Public Constructor + private API_Approval() {} + + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * Get Approvals by User - */ - authzAPI.route(GET, "/authz/approval/user/:user",API.APPROVALS, - new Code(facade,"Get Approvals by User", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getApprovalsByUser(trans, resp, pathParam(req,"user")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Get Approvals by User + */ + authzAPI.route(GET, "/authz/approval/user/:user",API.APPROVALS, + new Code(facade,"Get Approvals by User", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getApprovalsByUser(trans, resp, pathParam(req,"user")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - /** - * Get Approvals by Ticket - */ - authzAPI.route(GET, "/authz/approval/ticket/:ticket",API.APPROVALS,new Code(facade,"Get Approvals by Ticket ", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getApprovalsByTicket(trans, resp, pathParam(req,"ticket")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Get Approvals by Ticket + */ + authzAPI.route(GET, "/authz/approval/ticket/:ticket",API.APPROVALS,new Code(facade,"Get Approvals by Ticket ", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getApprovalsByTicket(trans, resp, pathParam(req,"ticket")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - /** - * Get Approvals by Approver - */ - authzAPI.route(GET, "/authz/approval/approver/:approver",API.APPROVALS,new Code(facade,"Get Approvals by Approver", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getApprovalsByApprover(trans, resp, pathParam(req,"approver")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Get Approvals by Approver + */ + authzAPI.route(GET, "/authz/approval/approver/:approver",API.APPROVALS,new Code(facade,"Get Approvals by Approver", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getApprovalsByApprover(trans, resp, pathParam(req,"approver")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - /** - * Update an approval - */ - authzAPI.route(PUT, "/authz/approval",API.APPROVALS,new Code(facade,"Update approvals", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.updateApproval(trans, req, resp); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); - } + /** + * Update an approval + */ + authzAPI.route(PUT, "/authz/approval",API.APPROVALS,new Code(facade,"Update approvals", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.updateApproval(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java index 390c3089..68e0f145 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java @@ -56,245 +56,245 @@ import org.onap.aaf.misc.env.TimeTaken; * */ public class API_Creds { - // Hide Public Interface - private API_Creds() {} - // needed to validate Creds even when already Authenticated x509 - /** - * TIME SENSITIVE APIs - * - * These will be first in the list - * - * @param env - * @param authzAPI - * @param facade - * @param directAAFUserPass - * @throws Exception - */ - public static void timeSensitiveInit(Env env, AAF_Service authzAPI, AuthzFacade facade, final DirectAAFUserPass directAAFUserPass) throws Exception { - /** - * Basic Auth, quick Validation - * - * Responds OK or NotAuthorized - */ - authzAPI.route(env, HttpMethods.GET, "/authn/basicAuth", new Code(facade,"Is given BasicAuth valid?",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { + // Hide Public Interface + private API_Creds() {} + // needed to validate Creds even when already Authenticated x509 + /** + * TIME SENSITIVE APIs + * + * These will be first in the list + * + * @param env + * @param authzAPI + * @param facade + * @param directAAFUserPass + * @throws Exception + */ + public static void timeSensitiveInit(Env env, AAF_Service authzAPI, AuthzFacade facade, final DirectAAFUserPass directAAFUserPass) throws Exception { + /** + * Basic Auth, quick Validation + * + * Responds OK or NotAuthorized + */ + authzAPI.route(env, HttpMethods.GET, "/authn/basicAuth", new Code(facade,"Is given BasicAuth valid?",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { - Principal p = trans.getUserPrincipal(); - if (p instanceof BasicPrincipal) { - // the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok - // otherwise, it wouldn't have gotten here. - resp.setStatus(HttpStatus.OK_200); - } else if (p instanceof X509Principal) { - // have to check Basic Auth here, because it might be CSP. - String authz = req.getHeader("Authorization"); - if(authz.startsWith("Basic ")) { - BasicHttpTaf bht = ((X509Principal)p).getBasicHttpTaf(); - if(bht!=null) { - BasicPrincipal bp = new BasicPrincipal(authz,""); - CredVal cv = bht.getCredVal(bp.getDomain()); - if(cv!=null) { - if(cv.validate(bp.getName(), Type.PASSWORD, bp.getCred(), null) ) { - resp.setStatus(HttpStatus.OK_200); - } else { - resp.setStatus(HttpStatus.FORBIDDEN_403); - } - } - } else { - String decoded = Symm.base64noSplit.decode(authz.substring(6)); - int colon = decoded.indexOf(':'); - TimeTaken tt = trans.start("Direct Validation", Env.REMOTE); - try { - if(directAAFUserPass.validate( - decoded.substring(0,colon), - CredVal.Type.PASSWORD , - decoded.substring(colon+1).getBytes(),trans)) { - - resp.setStatus(HttpStatus.OK_200); - } else { - // DME2 at this version crashes without some sort of response - resp.getOutputStream().print(""); - resp.setStatus(HttpStatus.FORBIDDEN_403); - } - } finally { - tt.done(); - } - } - } - } else if(p == null) { - trans.error().log("Transaction not Authenticated... no Principal"); - resp.setStatus(HttpStatus.FORBIDDEN_403); - } else { - trans.checkpoint("Basic Auth Check Failed: This wasn't a Basic Auth Trans"); - // For Auth Security questions, we don't give any info to client on why failed - resp.setStatus(HttpStatus.FORBIDDEN_403); - } - } - },"text/plain","*/*","*"); - - /** - * returns whether a given Credential is valid - */ - authzAPI.route(POST, "/authn/validate", API.CRED_REQ, new Code(facade,"Is given Credential valid?",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.doesCredentialMatch(trans, req, resp); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - // For Security, we don't give any info out on why failed, other than forbidden - // Can't do "401", because that is on the call itself - resp.setStatus(HttpStatus.FORBIDDEN_403); - } - } - }); + Principal p = trans.getUserPrincipal(); + if (p instanceof BasicPrincipal) { + // the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok + // otherwise, it wouldn't have gotten here. + resp.setStatus(HttpStatus.OK_200); + } else if (p instanceof X509Principal) { + // have to check Basic Auth here, because it might be CSP. + String authz = req.getHeader("Authorization"); + if(authz.startsWith("Basic ")) { + BasicHttpTaf bht = ((X509Principal)p).getBasicHttpTaf(); + if(bht!=null) { + BasicPrincipal bp = new BasicPrincipal(authz,""); + CredVal cv = bht.getCredVal(bp.getDomain()); + if(cv!=null) { + if(cv.validate(bp.getName(), Type.PASSWORD, bp.getCred(), null) ) { + resp.setStatus(HttpStatus.OK_200); + } else { + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } + } else { + String decoded = Symm.base64noSplit.decode(authz.substring(6)); + int colon = decoded.indexOf(':'); + TimeTaken tt = trans.start("Direct Validation", Env.REMOTE); + try { + if(directAAFUserPass.validate( + decoded.substring(0,colon), + CredVal.Type.PASSWORD , + decoded.substring(colon+1).getBytes(),trans)) { + + resp.setStatus(HttpStatus.OK_200); + } else { + // DME2 at this version crashes without some sort of response + resp.getOutputStream().print(""); + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } finally { + tt.done(); + } + } + } + } else if(p == null) { + trans.error().log("Transaction not Authenticated... no Principal"); + resp.setStatus(HttpStatus.FORBIDDEN_403); + } else { + trans.checkpoint("Basic Auth Check Failed: This wasn't a Basic Auth Trans"); + // For Auth Security questions, we don't give any info to client on why failed + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } + },"text/plain","*/*","*"); + + /** + * returns whether a given Credential is valid + */ + authzAPI.route(POST, "/authn/validate", API.CRED_REQ, new Code(facade,"Is given Credential valid?",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.doesCredentialMatch(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + // For Security, we don't give any info out on why failed, other than forbidden + // Can't do "401", because that is on the call itself + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } + }); - /** - * returns whether a given Credential is valid - */ - authzAPI.route(GET, "/authn/cert/id/:id", API.CERTS, new Code(facade,"Get Cert Info by ID",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getCertInfoByID(trans, req, resp, pathParam(req,":id") ); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - // For Security, we don't give any info out on why failed, other than forbidden - resp.setStatus(HttpStatus.FORBIDDEN_403); - } - } - }); + /** + * returns whether a given Credential is valid + */ + authzAPI.route(GET, "/authn/cert/id/:id", API.CERTS, new Code(facade,"Get Cert Info by ID",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getCertInfoByID(trans, req, resp, pathParam(req,":id") ); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + // For Security, we don't give any info out on why failed, other than forbidden + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } + }); - } - - /** - * Normal Init level APIs - * - * @param authzAPI - * @param facade - * @throws Exception - */ - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * Create a new ID/Credential - */ - authzAPI.route(POST,"/authn/cred",API.CRED_REQ,new Code(facade,"Add a New ID/Credential", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.createUserCred(trans, req); - if(r.isOK()) { - resp.setStatus(HttpStatus.CREATED_201); - } else { - context.error(trans,resp,r); - } - } - }); - - /** - * gets all credentials by Namespace - */ - authzAPI.route(GET, "/authn/creds/ns/:ns", API.USERS, new Code(facade,"Get Creds for a Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getCredsByNS(trans, resp, pathParam(req, "ns")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } + } + + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Create a new ID/Credential + */ + authzAPI.route(POST,"/authn/cred",API.CRED_REQ,new Code(facade,"Add a New ID/Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.createUserCred(trans, req); + if(r.isOK()) { + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,r); + } + } + }); + + /** + * gets all credentials by Namespace + */ + authzAPI.route(GET, "/authn/creds/ns/:ns", API.USERS, new Code(facade,"Get Creds for a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getCredsByNS(trans, resp, pathParam(req, "ns")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } - }); - - /** - * gets all credentials by ID - */ - authzAPI.route(GET, "/authn/creds/id/:id", API.USERS, new Code(facade,"Get Creds by ID",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getCredsByID(trans, resp, pathParam(req, "id")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } + }); + + /** + * gets all credentials by ID + */ + authzAPI.route(GET, "/authn/creds/id/:id", API.USERS, new Code(facade,"Get Creds by ID",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getCredsByID(trans, resp, pathParam(req, "id")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } - }); + }); - /** - * Update ID/Credential (aka reset) - */ - authzAPI.route(PUT,"/authn/cred",API.CRED_REQ,new Code(facade,"Update an ID/Credential", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - - Result r = context.changeUserCred(trans, req); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Update ID/Credential (aka reset) + */ + authzAPI.route(PUT,"/authn/cred",API.CRED_REQ,new Code(facade,"Update an ID/Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + + Result r = context.changeUserCred(trans, req); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - /** - * Extend ID/Credential - * This behavior will accelerate getting out of P1 outages due to ignoring renewal requests, or - * other expiration issues. - * - * Scenario is that people who are solving Password problems at night, are not necessarily those who - * know what the passwords are supposed to be. Also, changing Password, without changing Configurations - * using that password only exacerbates the P1 Issue. - */ - authzAPI.route(PUT,"/authn/cred/:days",API.CRED_REQ,new Code(facade,"Extend an ID/Credential", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.extendUserCred(trans, req, pathParam(req, "days")); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Extend ID/Credential + * This behavior will accelerate getting out of P1 outages due to ignoring renewal requests, or + * other expiration issues. + * + * Scenario is that people who are solving Password problems at night, are not necessarily those who + * know what the passwords are supposed to be. Also, changing Password, without changing Configurations + * using that password only exacerbates the P1 Issue. + */ + authzAPI.route(PUT,"/authn/cred/:days",API.CRED_REQ,new Code(facade,"Extend an ID/Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.extendUserCred(trans, req, pathParam(req, "days")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - /** - * Delete a ID/Credential by Object - */ - authzAPI.route(DELETE,"/authn/cred",API.CRED_REQ,new Code(facade,"Delete a Credential", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.deleteUserCred(trans, req); - if(r.isOK()) { - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,r); - } - } - }); + /** + * Delete a ID/Credential by Object + */ + authzAPI.route(DELETE,"/authn/cred",API.CRED_REQ,new Code(facade,"Delete a Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.deleteUserCred(trans, req); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); - } + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Delegate.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Delegate.java index 067c9192..ec1824b1 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Delegate.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Delegate.java @@ -39,114 +39,114 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.onap.aaf.auth.service.mapper.Mapper.API; public class API_Delegate { - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * Add a delegate - */ - authzAPI.route(POST, "/authz/delegate",API.DELG_REQ,new Code(facade,"Add a Delegate", true) { + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Add a delegate + */ + authzAPI.route(POST, "/authz/delegate",API.DELG_REQ,new Code(facade,"Add a Delegate", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.createDelegate(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Update a delegate - */ - authzAPI.route(PUT, "/authz/delegate",API.DELG_REQ,new Code(facade,"Update a Delegate", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.createDelegate(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Update a delegate + */ + authzAPI.route(PUT, "/authz/delegate",API.DELG_REQ,new Code(facade,"Update a Delegate", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.updateDelegate(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * DELETE delegates for a user - */ - authzAPI.route(DELETE, "/authz/delegate",API.DELG_REQ,new Code(facade,"Delete delegates for a user", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.updateDelegate(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * DELETE delegates for a user + */ + authzAPI.route(DELETE, "/authz/delegate",API.DELG_REQ,new Code(facade,"Delete delegates for a user", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.deleteDelegate(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * DELETE a delegate - */ - authzAPI.route(DELETE, "/authz/delegate/:user_name",API.VOID,new Code(facade,"Delete a Delegate", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.deleteDelegate(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * DELETE a delegate + */ + authzAPI.route(DELETE, "/authz/delegate/:user_name",API.VOID,new Code(facade,"Delete a Delegate", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.deleteDelegate(trans, pathParam(req, "user_name")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Read who is delegating for User - */ - authzAPI.route(GET, "/authz/delegates/user/:user",API.DELGS,new Code(facade,"Get Delegates by User", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.deleteDelegate(trans, pathParam(req, "user_name")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Read who is delegating for User + */ + authzAPI.route(GET, "/authz/delegates/user/:user",API.DELGS,new Code(facade,"Get Delegates by User", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getDelegatesByUser(trans, pathParam(req, "user"), resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getDelegatesByUser(trans, pathParam(req, "user"), resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * Read for whom the User is delegating - */ - authzAPI.route(GET, "/authz/delegates/delegate/:delegate",API.DELGS,new Code(facade,"Get Delegates by Delegate", true) { + /** + * Read for whom the User is delegating + */ + authzAPI.route(GET, "/authz/delegates/delegate/:delegate",API.DELGS,new Code(facade,"Get Delegates by Delegate", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getDelegatesByDelegate(trans, pathParam(req, "delegate"), resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getDelegatesByDelegate(trans, pathParam(req, "delegate"), resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - } + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java index 9044e177..e0911937 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java @@ -46,7 +46,7 @@ import org.onap.aaf.auth.service.mapper.Mapper.API; * Pull certain types of History Info * * Specify yyyymm as - * single - 201504 + * single - 201504 * commas 201503,201504 * ranges 201501-201504 * combinations 201301,201401,201501-201504 @@ -55,185 +55,185 @@ import org.onap.aaf.auth.service.mapper.Mapper.API; * */ public class API_History { - /** - * Normal Init level APIs - * - * @param authzAPI - * @param facade - * @throws Exception - */ - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * Get History - */ - authzAPI.route(GET,"/authz/hist/user/:user",API.HISTORY,new Code(facade,"Get History by User", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - int[] years; - int descend; - try { - years = getYears(req); - descend = decending(req); - } catch(Exception e) { - context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); - return; - } + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Get History + */ + authzAPI.route(GET,"/authz/hist/user/:user",API.HISTORY,new Code(facade,"Get History by User", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } - Result r = context.getHistoryByUser(trans, resp, pathParam(req,":user"),years,descend); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + Result r = context.getHistoryByUser(trans, resp, pathParam(req,":user"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * Get History by NS - */ - authzAPI.route(GET,"/authz/hist/ns/:ns",API.HISTORY,new Code(facade,"Get History by Namespace", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - int[] years; - int descend; - try { - years = getYears(req); - descend = decending(req); - } catch(Exception e) { - context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); - return; - } - - Result r = context.getHistoryByNS(trans, resp, pathParam(req,":ns"),years,descend); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * Get History by NS + */ + authzAPI.route(GET,"/authz/hist/ns/:ns",API.HISTORY,new Code(facade,"Get History by Namespace", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } + + Result r = context.getHistoryByNS(trans, resp, pathParam(req,":ns"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * Get History by Role - */ - authzAPI.route(GET,"/authz/hist/role/:role",API.HISTORY,new Code(facade,"Get History by Role", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - int[] years; - int descend; - try { - years = getYears(req); - descend = decending(req); - } catch(Exception e) { - context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); - return; - } + /** + * Get History by Role + */ + authzAPI.route(GET,"/authz/hist/role/:role",API.HISTORY,new Code(facade,"Get History by Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } - Result r = context.getHistoryByRole(trans, resp, pathParam(req,":role"),years,descend); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + Result r = context.getHistoryByRole(trans, resp, pathParam(req,":role"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * Get History by Perm Type - */ - authzAPI.route(GET,"/authz/hist/perm/:type",API.HISTORY,new Code(facade,"Get History by Perm Type", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - int[] years; - int descend; - try { - years = getYears(req); - descend = decending(req); - } catch(Exception e) { - context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); - return; - } - - Result r = context.getHistoryByPerm(trans, resp, pathParam(req,":type"),years,descend); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - } + /** + * Get History by Perm Type + */ + authzAPI.route(GET,"/authz/hist/perm/:type",API.HISTORY,new Code(facade,"Get History by Perm Type", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } + + Result r = context.getHistoryByPerm(trans, resp, pathParam(req,":type"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + } - // Check if Ascending - private static int decending(HttpServletRequest req) { - if("true".equalsIgnoreCase(req.getParameter("desc")))return -1; - if("true".equalsIgnoreCase(req.getParameter("asc")))return 1; - return 0; - } - - // Get Common "yyyymm" parameter, or none - - private static int[] getYears(HttpServletRequest req) throws NumberFormatException { - // Sonar says threading issues. - SimpleDateFormat FMT = new SimpleDateFormat("yyyyMM"); - String yyyymm = req.getParameter("yyyymm"); - ArrayList ai= new ArrayList<>(); - if(yyyymm==null) { - GregorianCalendar gc = new GregorianCalendar(); - // three months is the default - for(int i=0;i<3;++i) { - ai.add(Integer.parseInt(FMT.format(gc.getTime()))); - gc.add(GregorianCalendar.MONTH, -1); - } - } else { - for(String ym : yyyymm.split(",")) { - String range[] = ym.split("\\s*-\\s*"); - switch(range.length) { - case 0: - break; - case 1: - if(!ym.endsWith("-")) { - ai.add(getNum(ym)); - break; - } else { - range=new String[] {ym.substring(0, 6),FMT.format(new Date())}; - } - default: - GregorianCalendar gc = new GregorianCalendar(); - gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[1].substring(4,6))-1); - gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[1].substring(0,4))); - int end = getNum(FMT.format(gc.getTime())); - - gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[0].substring(4,6))-1); - gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[0].substring(0,4))); - for(int i=getNum(FMT.format(gc.getTime()));i<=end;gc.add(GregorianCalendar.MONTH, 1),i=getNum(FMT.format(gc.getTime()))) { - ai.add(i); - } + // Check if Ascending + private static int decending(HttpServletRequest req) { + if("true".equalsIgnoreCase(req.getParameter("desc")))return -1; + if("true".equalsIgnoreCase(req.getParameter("asc")))return 1; + return 0; + } + + // Get Common "yyyymm" parameter, or none + + private static int[] getYears(HttpServletRequest req) throws NumberFormatException { + // Sonar says threading issues. + SimpleDateFormat FMT = new SimpleDateFormat("yyyyMM"); + String yyyymm = req.getParameter("yyyymm"); + ArrayList ai= new ArrayList<>(); + if(yyyymm==null) { + GregorianCalendar gc = new GregorianCalendar(); + // three months is the default + for(int i=0;i<3;++i) { + ai.add(Integer.parseInt(FMT.format(gc.getTime()))); + gc.add(GregorianCalendar.MONTH, -1); + } + } else { + for(String ym : yyyymm.split(",")) { + String range[] = ym.split("\\s*-\\s*"); + switch(range.length) { + case 0: + break; + case 1: + if(!ym.endsWith("-")) { + ai.add(getNum(ym)); + break; + } else { + range=new String[] {ym.substring(0, 6),FMT.format(new Date())}; + } + default: + GregorianCalendar gc = new GregorianCalendar(); + gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[1].substring(4,6))-1); + gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[1].substring(0,4))); + int end = getNum(FMT.format(gc.getTime())); + + gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[0].substring(4,6))-1); + gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[0].substring(0,4))); + for(int i=getNum(FMT.format(gc.getTime()));i<=end;gc.add(GregorianCalendar.MONTH, 1),i=getNum(FMT.format(gc.getTime()))) { + ai.add(i); + } - } - } - } - if(ai.size()==0) { - throw new NumberFormatException(yyyymm + " is an invalid number or range"); - } - Collections.sort(ai); - int ym[] = new int[ai.size()]; - for(int i=0;i r = context.cacheClear(trans, pathParam(req,"area"), pathParam(req,"segments")); - switch(r.status) { - case OK: - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Clear Cache - */ - authzAPI.route(DELETE,"/mgmt/cache/:area",API.VOID,new Code(facade,"Clear Cache", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r; - String area; - r = context.cacheClear(trans, area=pathParam(req,"area")); - switch(r.status) { - case OK: - trans.audit().log("Cache " + area + " has been cleared by "+trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * Clear Cache Segment + */ + authzAPI.route(DELETE,"/mgmt/cache/:area/:segments",API.VOID,new Code(facade,"Clear Cache by Segment", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.cacheClear(trans, pathParam(req,"area"), pathParam(req,"segments")); + switch(r.status) { + case OK: + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Clear Cache + */ + authzAPI.route(DELETE,"/mgmt/cache/:area",API.VOID,new Code(facade,"Clear Cache", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r; + String area; + r = context.cacheClear(trans, area=pathParam(req,"area")); + switch(r.status) { + case OK: + trans.audit().log("Cache " + area + " has been cleared by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * Clear DB Sessions - */ - authzAPI.route(DELETE,"/mgmt/dbsession",API.VOID,new Code(facade,"Clear DBSessions", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - try { - if(req.isUserInRole(PERM_DB_POOL_CLEAR)) { - context.dbReset(trans); + /** + * Clear DB Sessions + */ + authzAPI.route(DELETE,"/mgmt/dbsession",API.VOID,new Code(facade,"Clear DBSessions", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + if(req.isUserInRole(PERM_DB_POOL_CLEAR)) { + context.dbReset(trans); - trans.audit().log("DB Sessions have been cleared by "+trans.user()); + trans.audit().log("DB Sessions have been cleared by "+trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.OK_200); - return; - } - context.error(trans,resp,Result.err(Result.ERR_Denied,"%s is not allowed to clear dbsessions",trans.user())); - } catch(Exception e) { - trans.error().log(e, "clearing dbsession"); - context.error(trans,resp,Result.err(e)); - } - } - }); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + return; + } + context.error(trans,resp,Result.err(Result.ERR_Denied,"%s is not allowed to clear dbsessions",trans.user())); + } catch(Exception e) { + trans.error().log(e, "clearing dbsession"); + context.error(trans,resp,Result.err(e)); + } + } + }); - /** - * Deny an IP - */ - authzAPI.route(POST, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Deny IP",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String ip = pathParam(req,":ip"); - if(req.isUserInRole(PERM_DENY_IP)) { - if(DenialOfServiceTaf.denyIP(ip)) { - trans.audit().log(ip+" has been set to deny by "+trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); + /** + * Deny an IP + */ + authzAPI.route(POST, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Deny IP",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String ip = pathParam(req,":ip"); + if(req.isUserInRole(PERM_DENY_IP)) { + if(DenialOfServiceTaf.denyIP(ip)) { + trans.audit().log(ip+" has been set to deny by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.CREATED_201); - } else { - context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, - ip + " is already being denied")); - } - } else { - trans.audit().log(trans.user(),"has attempted to deny",ip,"without authorization"); - context.error(trans,resp,Result.err(Status.ERR_Denied, - trans.getUserPrincipal().getName() + " is not allowed to set IP Denial")); - } - } - }); - - /** - * Stop Denying an IP - */ - authzAPI.route(DELETE, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Stop Denying IP",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String ip = pathParam(req,":ip"); - if(req.isUserInRole(PERM_DENY_IP)) { - if(DenialOfServiceTaf.removeDenyIP(ip)) { - trans.audit().log(ip+" has been removed from denial by "+trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,Result.err(Status.ERR_NotFound, - ip + " is not on the denial list")); - } - } else { - trans.audit().log(trans.user(),"has attempted to remove",ip," from being denied without authorization"); - context.error(trans,resp,Result.err(Status.ERR_Denied, - trans.getUserPrincipal().getName() + " is not allowed to remove IP Denial")); - } - } - }); + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, + ip + " is already being denied")); + } + } else { + trans.audit().log(trans.user(),"has attempted to deny",ip,"without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to set IP Denial")); + } + } + }); + + /** + * Stop Denying an IP + */ + authzAPI.route(DELETE, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Stop Denying IP",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String ip = pathParam(req,":ip"); + if(req.isUserInRole(PERM_DENY_IP)) { + if(DenialOfServiceTaf.removeDenyIP(ip)) { + trans.audit().log(ip+" has been removed from denial by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,Result.err(Status.ERR_NotFound, + ip + " is not on the denial list")); + } + } else { + trans.audit().log(trans.user(),"has attempted to remove",ip," from being denied without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to remove IP Denial")); + } + } + }); - /** - * Deny an ID - */ - authzAPI.route(POST, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Deny ID",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_DENY_ID)) { - if(DenialOfServiceTaf.denyID(id)) { - trans.audit().log(id+" has been set to deny by "+trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.CREATED_201); - } else { - context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, - id + " is already being denied")); - } - } else { - trans.audit().log(trans.user(),"has attempted to deny",id,"without authorization"); - context.error(trans,resp,Result.err(Status.ERR_Denied, - trans.getUserPrincipal().getName() + " is not allowed to set ID Denial")); - } - } - }); - - /** - * Stop Denying an ID - */ - authzAPI.route(DELETE, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Stop Denying ID",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_DENY_ID)) { - if(DenialOfServiceTaf.removeDenyID(id)) { - trans.audit().log(id+" has been removed from denial by " + trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,Result.err(Status.ERR_NotFound, - id + " is not on the denial list")); - } - } else { - trans.audit().log(trans.user(),"has attempted to remove",id," from being denied without authorization"); - context.error(trans,resp,Result.err(Status.ERR_Denied, - trans.getUserPrincipal().getName() + " is not allowed to remove ID Denial")); - } - } - }); + /** + * Deny an ID + */ + authzAPI.route(POST, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Deny ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_DENY_ID)) { + if(DenialOfServiceTaf.denyID(id)) { + trans.audit().log(id+" has been set to deny by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, + id + " is already being denied")); + } + } else { + trans.audit().log(trans.user(),"has attempted to deny",id,"without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to set ID Denial")); + } + } + }); + + /** + * Stop Denying an ID + */ + authzAPI.route(DELETE, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Stop Denying ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_DENY_ID)) { + if(DenialOfServiceTaf.removeDenyID(id)) { + trans.audit().log(id+" has been removed from denial by " + trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,Result.err(Status.ERR_NotFound, + id + " is not on the denial list")); + } + } else { + trans.audit().log(trans.user(),"has attempted to remove",id," from being denied without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to remove ID Denial")); + } + } + }); - /** - * Deny an ID - */ - authzAPI.route(POST, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Special Log ID",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_LOG_ID)) { - if(Question.specialLogOn(trans,id)) { - trans.audit().log(id+" has been set to special Log by "+trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.CREATED_201); - } else { - context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, - id + " is already being special Logged")); - } - } else { - trans.audit().log(trans.user(),"has attempted to special Log",id,"without authorization"); - context.error(trans,resp,Result.err(Status.ERR_Denied, - trans.getUserPrincipal().getName() + " is not allowed to set ID special Logging")); - } - } - }); - - /** - * Stop Denying an ID - */ - authzAPI.route(DELETE, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Stop Special Log ID",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_LOG_ID)) { - if(Question.specialLogOff(trans,id)) { - trans.audit().log(id+" has been removed from special Logging by " + trans.user()); - trans.checkpoint(SUCCESS,Trans.ALWAYS); - resp.setStatus(HttpStatus.OK_200); - } else { - context.error(trans,resp,Result.err(Status.ERR_NotFound, - id + " is not on the special Logging list")); - } - } else { - trans.audit().log(trans.user(),"has attempted to remove",id," from being special Logged without authorization"); - context.error(trans,resp,Result.err(Status.ERR_Denied, - trans.getUserPrincipal().getName() + " is not allowed to remove ID special Logging")); - } - } - }); + /** + * Deny an ID + */ + authzAPI.route(POST, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Special Log ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_LOG_ID)) { + if(Question.specialLogOn(trans,id)) { + trans.audit().log(id+" has been set to special Log by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, + id + " is already being special Logged")); + } + } else { + trans.audit().log(trans.user(),"has attempted to special Log",id,"without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to set ID special Logging")); + } + } + }); + + /** + * Stop Denying an ID + */ + authzAPI.route(DELETE, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Stop Special Log ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_LOG_ID)) { + if(Question.specialLogOff(trans,id)) { + trans.audit().log(id+" has been removed from special Logging by " + trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,Result.err(Status.ERR_NotFound, + id + " is not on the special Logging list")); + } + } else { + trans.audit().log(trans.user(),"has attempted to remove",id," from being special Logged without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to remove ID special Logging")); + } + } + }); - } + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Multi.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Multi.java index d3fe4f1f..45bc9d0f 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Multi.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Multi.java @@ -38,28 +38,28 @@ import org.onap.aaf.auth.service.mapper.Mapper.API; public class API_Multi { - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - - authzAPI.route(POST,"/authz/multi",API.VOID, new Code(facade,"Multiple Request API",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.addResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - case Status.ACC_Future: - resp.setStatus(HttpStatus.ACCEPTED_202); - break; - default: - context.error(trans,resp,r); - } - } - } - ); - } + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + + authzAPI.route(POST,"/authz/multi",API.VOID, new Code(facade,"Multiple Request API",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.addResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_NS.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_NS.java index 1087cd4d..0c4a7e49 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_NS.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_NS.java @@ -41,355 +41,355 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.onap.aaf.auth.service.mapper.Mapper.API; public class API_NS { - private static final String FULL = "full"; - private static final String TRUE = "true"; + private static final String FULL = "full"; + private static final String TRUE = "true"; - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * puts a new Namespace in Authz DB - * - * TESTCASES: TC_NS1, TC_NSdelete1 - */ - authzAPI.route(POST,"/authz/ns",API.NS_REQ, new Code(facade,"Create a Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - NsType nst = NsType.fromString(req.getParameter("type")); - Result r = context.requestNS(trans, req, resp,nst); - - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - case Status.ACC_Future: - resp.setStatus(HttpStatus.ACCEPTED_202); - break; - default: - context.error(trans,resp,r); - } - } - } - ); - - /** - * removes a Namespace from Authz DB - * - * TESTCASES: TC_NS1, TC_NSdelete1 - */ - authzAPI.route(DELETE,"/authz/ns/:ns",API.VOID, new Code(facade,"Delete a Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.deleteNS(trans, req, resp, pathParam(req,":ns")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * puts a new Namespace in Authz DB + * + * TESTCASES: TC_NS1, TC_NSdelete1 + */ + authzAPI.route(POST,"/authz/ns",API.NS_REQ, new Code(facade,"Create a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + NsType nst = NsType.fromString(req.getParameter("type")); + Result r = context.requestNS(trans, req, resp,nst); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * removes a Namespace from Authz DB + * + * TESTCASES: TC_NS1, TC_NSdelete1 + */ + authzAPI.route(DELETE,"/authz/ns/:ns",API.VOID, new Code(facade,"Delete a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.deleteNS(trans, req, resp, pathParam(req,":ns")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - /** - * Add an Admin in NS in Authz DB - * - * TESTCASES: TC_NS1 - */ - authzAPI.route(POST,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Add an Admin to a Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.addAdminToNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - case Status.ACC_Future: - resp.setStatus(HttpStatus.ACCEPTED_202); - break; - default: - context.error(trans,resp,r); - } - } - } - ); - - /** - * Removes an Admin from Namespace in Authz DB - * - * TESTCASES: TC_NS1 - */ - authzAPI.route(DELETE,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Remove an Admin from a Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.delAdminFromNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + /** + * Add an Admin in NS in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(POST,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Add an Admin to a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.addAdminToNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Removes an Admin from Namespace in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(DELETE,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Remove an Admin from a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.delAdminFromNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - /** - * Add an Admin in NS in Authz DB - * - * TESTCASES: TC_NS1 - */ - authzAPI.route(POST,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Add a Responsible Identity to a Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.addResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - case Status.ACC_Future: - resp.setStatus(HttpStatus.ACCEPTED_202); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + /** + * Add an Admin in NS in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(POST,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Add a Responsible Identity to a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.addResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - /** - * - */ - authzAPI.route(GET,"/authz/nss/:id",API.NSS, new Code(facade,"Return Information about Namespaces", true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.getNSsByName(trans, resp, pathParam(req,":id")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); - - /** - * Get all Namespaces where user is an admin - */ - authzAPI.route(GET,"/authz/nss/admin/:user",API.NSS, new Code(facade,"Return Namespaces where User is an Admin", true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.getNSsByAdmin(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); - - /** - * Get all Namespaces where user is a responsible party - */ - authzAPI.route(GET,"/authz/nss/responsible/:user",API.NSS, new Code(facade,"Return Namespaces where User is Responsible", true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.getNSsByResponsible(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + /** + * + */ + authzAPI.route(GET,"/authz/nss/:id",API.NSS, new Code(facade,"Return Information about Namespaces", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.getNSsByName(trans, resp, pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all Namespaces where user is an admin + */ + authzAPI.route(GET,"/authz/nss/admin/:user",API.NSS, new Code(facade,"Return Namespaces where User is an Admin", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.getNSsByAdmin(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all Namespaces where user is a responsible party + */ + authzAPI.route(GET,"/authz/nss/responsible/:user",API.NSS, new Code(facade,"Return Namespaces where User is Responsible", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.getNSsByResponsible(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - /** - * Get all Namespaces where user is an admin or owner - */ - authzAPI.route(GET,"/authz/nss/either/:user",API.NSS, new Code(facade,"Return Namespaces where User Admin or Owner", true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.getNSsByEither(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + /** + * Get all Namespaces where user is an admin or owner + */ + authzAPI.route(GET,"/authz/nss/either/:user",API.NSS, new Code(facade,"Return Namespaces where User Admin or Owner", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.getNSsByEither(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - /** - * Get all children Namespaces - */ - authzAPI.route(GET,"/authz/nss/children/:id",API.NSS, new Code(facade,"Return Child Namespaces", true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.getNSsChildren(trans, resp, pathParam(req,":id")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + /** + * Get all children Namespaces + */ + authzAPI.route(GET,"/authz/nss/children/:id",API.NSS, new Code(facade,"Return Child Namespaces", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.getNSsChildren(trans, resp, pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - /** - * Set a description of a Namespace - */ - authzAPI.route(PUT,"/authz/ns",API.NS_REQ,new Code(facade,"Set a Description for a Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.updateNsDescription(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Removes an Owner from Namespace in Authz DB - * - * TESTCASES: TC_NS1 - */ - authzAPI.route(DELETE,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Remove a Responsible Identity from Namespace",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.delResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + /** + * Set a description of a Namespace + */ + authzAPI.route(PUT,"/authz/ns",API.NS_REQ,new Code(facade,"Set a Description for a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.updateNsDescription(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Removes an Owner from Namespace in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(DELETE,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Remove a Responsible Identity from Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.delResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - authzAPI.route(POST,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"Add an Attribute from a Namespace",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.createAttribForNS(trans, resp, - pathParam(req,":ns"), - pathParam(req,":key"), - pathParam(req,":value")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + authzAPI.route(POST,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"Add an Attribute from a Namespace",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.createAttribForNS(trans, resp, + pathParam(req,":ns"), + pathParam(req,":key"), + pathParam(req,":value")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - authzAPI.route(GET,"/authz/ns/attrib/:key",API.KEYS, new Code(facade,"get Ns Key List From Attribute",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.readNsByAttrib(trans, resp, pathParam(req,":key")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + authzAPI.route(GET,"/authz/ns/attrib/:key",API.KEYS, new Code(facade,"get Ns Key List From Attribute",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.readNsByAttrib(trans, resp, pathParam(req,":key")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - authzAPI.route(PUT,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"update an Attribute from a Namespace",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.updAttribForNS(trans, resp, - pathParam(req,":ns"), - pathParam(req,":key"), - pathParam(req,":value")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); - - authzAPI.route(DELETE,"/authz/ns/:ns/attrib/:key",API.VOID, new Code(facade,"delete an Attribute from a Namespace",true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.delAttribForNS(trans, resp, - pathParam(req,":ns"), - pathParam(req,":key")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + authzAPI.route(PUT,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"update an Attribute from a Namespace",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.updAttribForNS(trans, resp, + pathParam(req,":ns"), + pathParam(req,":key"), + pathParam(req,":value")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + authzAPI.route(DELETE,"/authz/ns/:ns/attrib/:key",API.VOID, new Code(facade,"delete an Attribute from a Namespace",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.delAttribForNS(trans, resp, + pathParam(req,":ns"), + pathParam(req,":key")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - } - - + } + + } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java index c9795a5f..5f2a823e 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java @@ -43,254 +43,254 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.misc.env.util.Split; public class API_Perms { - public static void timeSensitiveInit(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * gets all permissions by user name - */ - authzAPI.route(GET, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - String scopes = req.getParameter("scopes"); - Result r; - if(scopes==null) { - r = context.getPermsByUser(trans, resp, pathParam(req, "user")); - } else { - r = context.getPermsByUserScope(trans, resp, pathParam(req, "user"),Split.split(':', scopes)); - } - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } + public static void timeSensitiveInit(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * gets all permissions by user name + */ + authzAPI.route(GET, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + String scopes = req.getParameter("scopes"); + Result r; + if(scopes==null) { + r = context.getPermsByUser(trans, resp, pathParam(req, "user")); + } else { + r = context.getPermsByUserScope(trans, resp, pathParam(req, "user"),Split.split(':', scopes)); + } + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } - }); - - /** - * gets all permissions by user name - */ - authzAPI.route(POST, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User, Query AAF Perms",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getPermsByUserWithAAFQuery(trans, req, resp, pathParam(req, "user")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } + }); + + /** + * gets all permissions by user name + */ + authzAPI.route(POST, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User, Query AAF Perms",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getPermsByUserWithAAFQuery(trans, req, resp, pathParam(req, "user")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } - }); + }); - } // end timeSensitiveInit + } // end timeSensitiveInit - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * Create a Permission - */ - authzAPI.route(POST,"/authz/perm",API.PERM_REQ,new Code(facade,"Create a Permission",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.createPerm(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - default: - context.error(trans,resp,r); - } - } - }); + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Create a Permission + */ + authzAPI.route(POST,"/authz/perm",API.PERM_REQ,new Code(facade,"Create a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.createPerm(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * get details of Permission - */ - authzAPI.route(GET, "/authz/perms/:type/:instance/:action", API.PERMS, new Code(facade,"Get Permissions by Key",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getPermsByName(trans, resp, - pathParam(req, "type"), - URLDecoder.decode(pathParam(req, "instance"),Config.UTF_8), - pathParam(req, "action")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } + /** + * get details of Permission + */ + authzAPI.route(GET, "/authz/perms/:type/:instance/:action", API.PERMS, new Code(facade,"Get Permissions by Key",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getPermsByName(trans, resp, + pathParam(req, "type"), + URLDecoder.decode(pathParam(req, "instance"),Config.UTF_8), + pathParam(req, "action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } - }); - - /** - * get children of Permission - */ - authzAPI.route(GET, "/authz/perms/:type", API.PERMS, new Code(facade,"Get Permissions by Type",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getPermsByType(trans, resp, pathParam(req, "type")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } + }); + + /** + * get children of Permission + */ + authzAPI.route(GET, "/authz/perms/:type", API.PERMS, new Code(facade,"Get Permissions by Type",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getPermsByType(trans, resp, pathParam(req, "type")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } - }); + }); - - /** - * gets all permissions by role name - */ - authzAPI.route(GET,"/authz/perms/role/:role",API.PERMS,new Code(facade,"Get Permissions by Role",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getPermsForRole(trans, resp, pathParam(req, "role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + + /** + * gets all permissions by role name + */ + authzAPI.route(GET,"/authz/perms/role/:role",API.PERMS,new Code(facade,"Get Permissions by Role",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getPermsForRole(trans, resp, pathParam(req, "role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * gets all permissions by Namespace - */ - authzAPI.route(GET,"/authz/perms/ns/:ns",API.PERMS,new Code(facade,"Get PermsByNS",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getPermsByNS(trans, resp, pathParam(req, "ns")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Set a perm's description - */ - authzAPI.route(PUT,"/authz/perm",API.PERM_REQ,new Code(facade,"Set Description for Permission",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.updatePermDescription(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Update a permission with a rename - */ - authzAPI.route(PUT,"/authz/perm/:type/:instance/:action",API.PERM_REQ,new Code(facade,"Update a Permission",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.renamePerm(trans, req, resp, pathParam(req, "type"), - pathParam(req, "instance"), pathParam(req, "action")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Delete a Permission - */ - authzAPI.route(DELETE,"/authz/perm",API.PERM_REQ,new Code(facade,"Delete a Permission",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.deletePerm(trans,req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * gets all permissions by Namespace + */ + authzAPI.route(GET,"/authz/perms/ns/:ns",API.PERMS,new Code(facade,"Get PermsByNS",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getPermsByNS(trans, resp, pathParam(req, "ns")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Set a perm's description + */ + authzAPI.route(PUT,"/authz/perm",API.PERM_REQ,new Code(facade,"Set Description for Permission",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.updatePermDescription(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Update a permission with a rename + */ + authzAPI.route(PUT,"/authz/perm/:type/:instance/:action",API.PERM_REQ,new Code(facade,"Update a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.renamePerm(trans, req, resp, pathParam(req, "type"), + pathParam(req, "instance"), pathParam(req, "action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Delete a Permission + */ + authzAPI.route(DELETE,"/authz/perm",API.PERM_REQ,new Code(facade,"Delete a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.deletePerm(trans,req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - - + + - /** - * Delete a Permission - */ - authzAPI.route(DELETE,"/authz/perm/:name/:type/:action",API.PERM_KEY,new Code(facade,"Delete a Permission",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.deletePerm(trans, resp, - pathParam(req, ":name"), - pathParam(req, ":type"), - pathParam(req, ":action")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * Delete a Permission + */ + authzAPI.route(DELETE,"/authz/perm/:name/:type/:action",API.PERM_KEY,new Code(facade,"Delete a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.deletePerm(trans, resp, + pathParam(req, ":name"), + pathParam(req, ":type"), + pathParam(req, ":action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - } // end init + } // end init } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Roles.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Roles.java index 24259e16..2c93bc38 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Roles.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Roles.java @@ -40,298 +40,298 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.onap.aaf.auth.service.mapper.Mapper.API; public class API_Roles { - public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * puts a new role in Authz DB - */ - authzAPI.route(POST,"/authz/role",API.ROLE_REQ, new Code(facade,"Create Role",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.createRole(trans, req, resp); - - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - case Status.ACC_Future: - resp.setStatus(HttpStatus.ACCEPTED_202); - break; - default: - context.error(trans,resp,r); - } - } - } - ); + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * puts a new role in Authz DB + */ + authzAPI.route(POST,"/authz/role",API.ROLE_REQ, new Code(facade,"Create Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.createRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); - /** - * get Role by name - */ - authzAPI.route(GET, "/authz/roles/:role", API.ROLES, new Code(facade,"GetRolesByFullName",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getRolesByName(trans, resp, pathParam(req, "role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } + /** + * get Role by name + */ + authzAPI.route(GET, "/authz/roles/:role", API.ROLES, new Code(facade,"GetRolesByFullName",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getRolesByName(trans, resp, pathParam(req, "role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } - }); + }); - /** - * gets all Roles by user name - */ - authzAPI.route(GET, "/authz/roles/user/:name", API.ROLES, new Code(facade,"GetRolesByUser",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getRolesByUser(trans, resp, pathParam(req, "name")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } + /** + * gets all Roles by user name + */ + authzAPI.route(GET, "/authz/roles/user/:name", API.ROLES, new Code(facade,"GetRolesByUser",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getRolesByUser(trans, resp, pathParam(req, "name")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } - }); + }); - /** - * gets all Roles by Namespace - */ - authzAPI.route(GET, "/authz/roles/ns/:ns", API.ROLES, new Code(facade,"GetRolesByNS",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getRolesByNS(trans, resp, pathParam(req, "ns")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * gets all Roles by Namespace + */ + authzAPI.route(GET, "/authz/roles/ns/:ns", API.ROLES, new Code(facade,"GetRolesByNS",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getRolesByNS(trans, resp, pathParam(req, "ns")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * gets all Roles by Name without the Namespace - */ - authzAPI.route(GET, "/authz/roles/name/:name", API.ROLES, new Code(facade,"GetRolesByNameOnly",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.getRolesByNameOnly(trans, resp, pathParam(req, ":name")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Deletes a Role from Authz DB by Object - */ - authzAPI.route(DELETE,"/authz/role",API.ROLE_REQ, new Code(facade,"Delete Role",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.deleteRole(trans, req, resp); - - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - - } - ); - + /** + * gets all Roles by Name without the Namespace + */ + authzAPI.route(GET, "/authz/roles/name/:name", API.ROLES, new Code(facade,"GetRolesByNameOnly",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.getRolesByNameOnly(trans, resp, pathParam(req, ":name")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Deletes a Role from Authz DB by Object + */ + authzAPI.route(DELETE,"/authz/role",API.ROLE_REQ, new Code(facade,"Delete Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.deleteRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + } + ); + - - /** - * Deletes a Role from Authz DB by Key - */ - authzAPI.route(DELETE,"/authz/role/:role",API.ROLE, new Code(facade,"Delete Role",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.deleteRole(trans, resp, pathParam(req,":role")); - - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - - } - ); - + + /** + * Deletes a Role from Authz DB by Key + */ + authzAPI.route(DELETE,"/authz/role/:role",API.ROLE, new Code(facade,"Delete Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.deleteRole(trans, resp, pathParam(req,":role")); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + } + ); + - /** - * Add a Permission to a Role (Grant) - */ - authzAPI.route(POST,"/authz/role/perm",API.ROLE_PERM_REQ, new Code(facade,"Add Permission to Role",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.addPermToRole(trans, req, resp); - - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - default: - context.error(trans,resp,r); - } - } - } - ); - - /** - * Get all Roles by Permission - */ - authzAPI.route(GET,"/authz/roles/perm/:type/:instance/:action",API.ROLES,new Code(facade,"GetRolesByPerm",true) { - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.getRolesByPerm(trans, resp, - pathParam(req, "type"), - pathParam(req, "instance"), - pathParam(req, "action")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Set a role's description - */ - authzAPI.route(PUT,"/authz/role",API.ROLE_REQ,new Code(facade,"Set Description for role",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.updateRoleDescription(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Set a permission's roles to roles given - */ - authzAPI.route(PUT,"/authz/role/perm",API.ROLE_PERM_REQ,new Code(facade,"Set a Permission's Roles",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - - Result r = context.resetPermRoles(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Delete a Permission from a Role - * With multiple perms - */ - authzAPI.route(DELETE,"/authz/role/:role/perm",API.ROLE_PERM_REQ, new Code(facade,"Delete Permission from Role",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.delPermFromRole(trans, req, resp); - - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * Add a Permission to a Role (Grant) + */ + authzAPI.route(POST,"/authz/role/perm",API.ROLE_PERM_REQ, new Code(facade,"Add Permission to Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.addPermToRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all Roles by Permission + */ + authzAPI.route(GET,"/authz/roles/perm/:type/:instance/:action",API.ROLES,new Code(facade,"GetRolesByPerm",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.getRolesByPerm(trans, resp, + pathParam(req, "type"), + pathParam(req, "instance"), + pathParam(req, "action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Set a role's description + */ + authzAPI.route(PUT,"/authz/role",API.ROLE_REQ,new Code(facade,"Set Description for role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.updateRoleDescription(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Set a permission's roles to roles given + */ + authzAPI.route(PUT,"/authz/role/perm",API.ROLE_PERM_REQ,new Code(facade,"Set a Permission's Roles",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result r = context.resetPermRoles(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Delete a Permission from a Role + * With multiple perms + */ + authzAPI.route(DELETE,"/authz/role/:role/perm",API.ROLE_PERM_REQ, new Code(facade,"Delete Permission from Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.delPermFromRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /* - * Delete a Permission from a Role by key only - * / - authzAPI.route(DELETE,"/authz/role/:role/perm/:type/:instance/:action",API.ROLE_PERM_REQ, new Code(facade,"Delete Permission from Role",true) { - @Override - public void handle( - AuthzTrans trans, - HttpServletRequest req, - HttpServletResponse resp) throws Exception { - Result r = context.delPermFromRole(trans, resp, - pathParam(req,":role"), - pathParam(req,":type"), - pathParam(req,":instance"), - pathParam(req,":action")); - - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - */ - } + /* + * Delete a Permission from a Role by key only + * / + authzAPI.route(DELETE,"/authz/role/:role/perm/:type/:instance/:action",API.ROLE_PERM_REQ, new Code(facade,"Delete Permission from Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result r = context.delPermFromRole(trans, resp, + pathParam(req,":role"), + pathParam(req,":type"), + pathParam(req,":instance"), + pathParam(req,":action")); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + */ + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_User.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_User.java index 26be2a07..0ce1dfe2 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_User.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_User.java @@ -41,93 +41,93 @@ import org.onap.aaf.auth.service.mapper.Mapper.API; * */ public class API_User { - /** - * Normal Init level APIs - * - * @param authzAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * get all Users who have Permission X - */ - authzAPI.route(GET,"/authz/users/perm/:type/:instance/:action",API.USERS,new Code(facade,"Get Users By Permission", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { -// trans.checkpoint(pathParam(req,"type") + " " -// + pathParam(req,"instance") + " " -// + pathParam(req,"action")); + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * get all Users who have Permission X + */ + authzAPI.route(GET,"/authz/users/perm/:type/:instance/:action",API.USERS,new Code(facade,"Get Users By Permission", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { +// trans.checkpoint(pathParam(req,"type") + " " +// + pathParam(req,"instance") + " " +// + pathParam(req,"action")); // - Result r = context.getUsersByPermission(trans, resp, - pathParam(req, ":type"), - pathParam(req, ":instance"), - pathParam(req, ":action")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + Result r = context.getUsersByPermission(trans, resp, + pathParam(req, ":type"), + pathParam(req, ":instance"), + pathParam(req, ":action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * get all Users who have Role X - */ - authzAPI.route(GET,"/authz/users/role/:role",API.USERS,new Code(facade,"Get Users By Role", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getUsersByRole(trans, resp, pathParam(req, ":role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Get User Role if exists - * @deprecated - */ - authzAPI.route(GET,"/authz/userRole/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * get all Users who have Role X + */ + authzAPI.route(GET,"/authz/users/role/:role",API.USERS,new Code(facade,"Get Users By Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getUsersByRole(trans, resp, pathParam(req, ":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get User Role if exists + * @deprecated + */ + authzAPI.route(GET,"/authz/userRole/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - /** - * Get User Role if exists - */ - authzAPI.route(GET,"/authz/users/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - + /** + * Get User Role if exists + */ + authzAPI.route(GET,"/authz/users/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + - } - + } + } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java index 89550a71..7937a184 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java @@ -44,138 +44,138 @@ import org.onap.aaf.auth.service.mapper.Mapper.API; * */ public class API_UserRole { - /** - * Normal Init level APIs - * - * @param authzAPI - * @param facade - * @throws Exception - */ - public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { - /** - * Request User Role Access - */ - authzAPI.route(POST,"/authz/userRole",API.USER_ROLE_REQ,new Code(facade,"Request User Role Access", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.requestUserRole(trans, req, resp); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.CREATED_201); - break; - default: - context.error(trans,resp,r); - } - } - }); - - - /** - * Get UserRoles by Role - */ - authzAPI.route(GET,"/authz/userRoles/role/:role",API.USER_ROLES,new Code(facade,"Get UserRoles by Role", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getUserRolesByRole(trans, resp, pathParam(req,":role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Get UserRoles by User - */ - authzAPI.route(GET,"/authz/userRoles/user/:user",API.USER_ROLES,new Code(facade,"Get UserRoles by User", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.getUserRolesByUser(trans, resp, pathParam(req,":user")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Request User Role Access + */ + authzAPI.route(POST,"/authz/userRole",API.USER_ROLE_REQ,new Code(facade,"Request User Role Access", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.requestUserRole(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + /** + * Get UserRoles by Role + */ + authzAPI.route(GET,"/authz/userRoles/role/:role",API.USER_ROLES,new Code(facade,"Get UserRoles by Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getUserRolesByRole(trans, resp, pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get UserRoles by User + */ + authzAPI.route(GET,"/authz/userRoles/user/:user",API.USER_ROLES,new Code(facade,"Get UserRoles by User", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.getUserRolesByUser(trans, resp, pathParam(req,":user")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - - /** - * Update roles attached to user in path - */ - authzAPI.route(PUT,"/authz/userRole/user",API.USER_ROLE_REQ,new Code(facade,"Update Roles for a user", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.resetRolesForUser(trans, resp, req); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - - /** - * Update users attached to role in path - */ - authzAPI.route(PUT,"/authz/userRole/role",API.USER_ROLE_REQ,new Code(facade,"Update Users for a role", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.resetUsersForRole(trans, resp, req); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); - - /** - * Extend Expiration Date (according to Organizational rules) - */ - authzAPI.route(PUT, "/authz/userRole/extend/:user/:role", API.VOID, new Code(facade,"Extend Expiration", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.extendUserRoleExpiration(trans,resp,pathParam(req,":user"),pathParam(req,":role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - - } - - }); - - - /** - * Create a new ID/Credential - */ - authzAPI.route(DELETE,"/authz/userRole/:user/:role",API.VOID,new Code(facade,"Delete User Role", true) { - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - Result r = context.deleteUserRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); - switch(r.status) { - case OK: - resp.setStatus(HttpStatus.OK_200); - break; - default: - context.error(trans,resp,r); - } - } - }); + + /** + * Update roles attached to user in path + */ + authzAPI.route(PUT,"/authz/userRole/user",API.USER_ROLE_REQ,new Code(facade,"Update Roles for a user", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.resetRolesForUser(trans, resp, req); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + /** + * Update users attached to role in path + */ + authzAPI.route(PUT,"/authz/userRole/role",API.USER_ROLE_REQ,new Code(facade,"Update Users for a role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.resetUsersForRole(trans, resp, req); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Extend Expiration Date (according to Organizational rules) + */ + authzAPI.route(PUT, "/authz/userRole/extend/:user/:role", API.VOID, new Code(facade,"Extend Expiration", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.extendUserRoleExpiration(trans,resp,pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + + } + + }); + + + /** + * Create a new ID/Credential + */ + authzAPI.route(DELETE,"/authz/userRole/:user/:role",API.VOID,new Code(facade,"Delete User Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result r = context.deleteUserRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); - } + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java index af375199..61a491f0 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java @@ -45,221 +45,221 @@ import org.onap.aaf.auth.rserv.RServlet; * */ public interface AuthzFacade { - public static final int PERM_DEPEND_424 = -1000; - public static final int ROLE_DEPEND_424 = -1001; + public static final int PERM_DEPEND_424 = -1000; + public static final int ROLE_DEPEND_424 = -1001; - /* - * Namespaces - */ - public abstract Result requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type); - - public abstract Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns); - - public abstract Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); - - public abstract Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); - - public abstract Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + /* + * Namespaces + */ + public abstract Result requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type); + + public abstract Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns); + + public abstract Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); - public abstract Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String pathParam); + public abstract Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String pathParam); - public abstract Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + public abstract Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - public abstract Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + public abstract Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - public abstract Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + public abstract Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - public abstract Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - - public abstract Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + public abstract Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - public abstract Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns); + public abstract Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns); - // NS Attribs - public abstract Result createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); + // NS Attribs + public abstract Result createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); - public abstract Result readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key); + public abstract Result readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key); - public abstract Result updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); + public abstract Result updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); - public abstract Result delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key); + public abstract Result delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key); - /* - * Permissions - */ - public abstract Result createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action); + /* + * Permissions + */ + public abstract Result createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action); - public abstract Result getPermsByUser(AuthzTrans trans, HttpServletResponse response, String user); + public abstract Result getPermsByUser(AuthzTrans trans, HttpServletResponse response, String user); - public abstract Result getPermsByUserScope(AuthzTrans trans, HttpServletResponse resp, String user, String[] scopes); - - public abstract Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest request, HttpServletResponse response, String user); - - public abstract Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String type); + public abstract Result getPermsByUserScope(AuthzTrans trans, HttpServletResponse resp, String user, String[] scopes); + + public abstract Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest request, HttpServletResponse response, String user); + + public abstract Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String type); - public abstract Result getPermsForRole(AuthzTrans trans, HttpServletResponse response, String roleName); + public abstract Result getPermsForRole(AuthzTrans trans, HttpServletResponse response, String roleName); - public abstract Result getPermsByNS(AuthzTrans trans, HttpServletResponse response, String ns); - - public abstract Result renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, - String type, String instance, String action); - - public abstract Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + public abstract Result getPermsByNS(AuthzTrans trans, HttpServletResponse response, String ns); + + public abstract Result renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, + String type, String instance, String action); + + public abstract Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - public abstract Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + public abstract Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - public abstract Result deletePerm(AuthzTrans trans, HttpServletResponse resp, - String perm, String type, String action); + public abstract Result deletePerm(AuthzTrans trans, HttpServletResponse resp, + String perm, String type, String action); - /* - * Roles - */ - public abstract Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse response); - - public abstract Result getRolesByName(AuthzTrans trans,HttpServletResponse resp, String name); + /* + * Roles + */ + public abstract Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse response); + + public abstract Result getRolesByName(AuthzTrans trans,HttpServletResponse resp, String name); - public abstract Result getRolesByNS(AuthzTrans trans, HttpServletResponse resp, String ns); + public abstract Result getRolesByNS(AuthzTrans trans, HttpServletResponse resp, String ns); - public abstract Result getRolesByNameOnly(AuthzTrans trans, HttpServletResponse resp, String nameOnly); + public abstract Result getRolesByNameOnly(AuthzTrans trans, HttpServletResponse resp, String nameOnly); - public abstract Result getRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); + public abstract Result getRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); - public abstract Result getRolesByPerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action); + public abstract Result getRolesByPerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action); - public abstract Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result addPermToRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); - - public abstract Result delPermFromRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + public abstract Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result addPermToRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result delPermFromRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); - public abstract Result delPermFromRole(AuthzTrans trans, HttpServletResponse resp, - String role, String type, String instance, String action); + public abstract Result delPermFromRole(AuthzTrans trans, HttpServletResponse resp, + String role, String type, String instance, String action); - public abstract Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + public abstract Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - public abstract Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role); + public abstract Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role); - /* - * Users - */ - - public abstract Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role); - - public abstract Result getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action); + /* + * Users + */ + + public abstract Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role); + + public abstract Result getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action); - /* - * Delegates - */ - public abstract Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deleteDelegate(AuthzTrans trans, String user); - - public abstract Result getDelegatesByUser(AuthzTrans trans, String userName, HttpServletResponse resp); + /* + * Delegates + */ + public abstract Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deleteDelegate(AuthzTrans trans, String user); + + public abstract Result getDelegatesByUser(AuthzTrans trans, String userName, HttpServletResponse resp); - public abstract Result getDelegatesByDelegate(AuthzTrans trans, String userName, HttpServletResponse resp); + public abstract Result getDelegatesByDelegate(AuthzTrans trans, String userName, HttpServletResponse resp); - /* - * Credentials - */ - public abstract Result createUserCred(AuthzTrans trans, HttpServletRequest req); + /* + * Credentials + */ + public abstract Result createUserCred(AuthzTrans trans, HttpServletRequest req); - public abstract Result changeUserCred(AuthzTrans trans, HttpServletRequest req); + public abstract Result changeUserCred(AuthzTrans trans, HttpServletRequest req); - public abstract Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days); + public abstract Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days); - public abstract Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns); + public abstract Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns); - public abstract Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id); + public abstract Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id); - public abstract Result deleteUserCred(AuthzTrans trans, HttpServletRequest req); + public abstract Result deleteUserCred(AuthzTrans trans, HttpServletRequest req); - public abstract Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth); + public abstract Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth); - public abstract Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + public abstract Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - /* - * Miscellaneous - */ - /** - * Place Standard Messages based on HTTP Code onto Error Data Structure, and write to OutputStream - * Log message - */ - public abstract void error(AuthzTrans trans, HttpServletResponse response, Result result); + /* + * Miscellaneous + */ + /** + * Place Standard Messages based on HTTP Code onto Error Data Structure, and write to OutputStream + * Log message + */ + public abstract void error(AuthzTrans trans, HttpServletResponse response, Result result); - /* - * UserRole - */ - public abstract Result requestUserRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); - - public abstract Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); - - public abstract Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role); - - public abstract Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); + /* + * UserRole + */ + public abstract Result requestUserRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); + + public abstract Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role); + + public abstract Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); - public abstract Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); - - public abstract Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); + public abstract Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); + + public abstract Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); - public abstract Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); - - public abstract Result extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, - String role); + public abstract Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); + + public abstract Result extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, + String role); - /* - * Approval - */ - public abstract Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user); - - public abstract Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket); - - public abstract Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver); + /* + * Approval + */ + public abstract Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user); + + public abstract Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket); + + public abstract Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver); - /* - * History - */ - public abstract Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort); - - public abstract Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + /* + * History + */ + public abstract Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort); + + public abstract Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); - public abstract Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + public abstract Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); - public abstract Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + public abstract Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); - /* - * Cache - */ - public abstract Result cacheClear(AuthzTrans trans, String pathParam); + /* + * Cache + */ + public abstract Result cacheClear(AuthzTrans trans, String pathParam); - public abstract Result cacheClear(AuthzTrans trans, String string,String segments); - - public abstract void dbReset(AuthzTrans trans); + public abstract Result cacheClear(AuthzTrans trans, String string,String segments); + + public abstract void dbReset(AuthzTrans trans); - /* - * API - */ - public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet); - - public abstract Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional); + /* + * API + */ + public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet); + + public abstract Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional); - public abstract Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id); + public abstract Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeFactory.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeFactory.java index de8260f1..1d7f31e5 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeFactory.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeFactory.java @@ -31,25 +31,25 @@ import org.onap.aaf.misc.env.Data; public class AuthzFacadeFactory { - public static AuthzFacade_2_0 v2_0(AuthzEnv env, AuthzTrans trans, Data.TYPE type, Question question) throws APIException { - return new AuthzFacade_2_0(env, - new AuthzCassServiceImpl< - aaf.v2_0.Nss, - aaf.v2_0.Perms, - aaf.v2_0.Pkey, - aaf.v2_0.Roles, - aaf.v2_0.Users, - aaf.v2_0.UserRoles, - aaf.v2_0.Delgs, - aaf.v2_0.Certs, - aaf.v2_0.Keys, - aaf.v2_0.Request, - aaf.v2_0.History, - aaf.v2_0.Error, - aaf.v2_0.Approvals> - (trans,new Mapper_2_0(question),question), - type); - } - + public static AuthzFacade_2_0 v2_0(AuthzEnv env, AuthzTrans trans, Data.TYPE type, Question question) throws APIException { + return new AuthzFacade_2_0(env, + new AuthzCassServiceImpl< + aaf.v2_0.Nss, + aaf.v2_0.Perms, + aaf.v2_0.Pkey, + aaf.v2_0.Roles, + aaf.v2_0.Users, + aaf.v2_0.UserRoles, + aaf.v2_0.Delgs, + aaf.v2_0.Certs, + aaf.v2_0.Keys, + aaf.v2_0.Request, + aaf.v2_0.History, + aaf.v2_0.Error, + aaf.v2_0.Approvals> + (trans,new Mapper_2_0(question),question), + type); + } + } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java index 4895e26f..0e1479c4 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java @@ -86,7 +86,7 @@ import aaf.v2_0.Api; * 1) Interact with the Service Implementation (which might be supported by various kinds of Backend Storage) * 2) Validate incoming data (if applicable) * 3) Convert the Service response into the right Format, and mark the Content Type - * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. + * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. * 4) Log Service info, warnings and exceptions as necessary * 5) When asked by the API layer, this will create and write Error content to the OutputStream * @@ -97,2546 +97,2546 @@ import aaf.v2_0.Api; * */ public abstract class AuthzFacadeImpl extends FacadeImpl implements AuthzFacade - { - private static final String FORBIDDEN = "Forbidden"; - private static final String NOT_FOUND = "Not Found"; - private static final String NOT_ACCEPTABLE = "Not Acceptable"; - private static final String GENERAL_SERVICE_ERROR = "General Service Error"; - private static final String NO_DATA = "***No Data***"; - private AuthzService service = null; - private final RosettaDF nssDF; - private final RosettaDF permsDF; - private final RosettaDF roleDF; - private final RosettaDF usersDF; - private final RosettaDF userrolesDF; - private final RosettaDF certsDF; - private final RosettaDF delgDF; - private final RosettaDF permRequestDF; - private final RosettaDF roleRequestDF; - private final RosettaDF userRoleRequestDF; - private final RosettaDF rolePermRequestDF; - private final RosettaDF nsRequestDF; - private final RosettaDF credRequestDF; - private final RosettaDF delgRequestDF; - private final RosettaDF historyDF; - private final RosettaDF keysDF; - - private final RosettaDF errDF; - private final RosettaDF approvalDF; - // Note: Api is not different per Version - private final RosettaDF apiDF; - - - @SuppressWarnings("unchecked") - public AuthzFacadeImpl(AuthzEnv env, AuthzService service, Data.TYPE dataType) throws APIException { - this.service = service; - (nssDF = env.newDataFactory(service.mapper().getClass(API.NSS))).in(dataType).out(dataType); - (permRequestDF = env.newDataFactory(service.mapper().getClass(API.PERM_REQ))).in(dataType).out(dataType); - (permsDF = env.newDataFactory(service.mapper().getClass(API.PERMS))).in(dataType).out(dataType); -// (permKeyDF = env.newDataFactory(service.mapper().getClass(API.PERM_KEY))).in(dataType).out(dataType); - (roleDF = env.newDataFactory(service.mapper().getClass(API.ROLES))).in(dataType).out(dataType); - (roleRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_REQ))).in(dataType).out(dataType); - (usersDF = env.newDataFactory(service.mapper().getClass(API.USERS))).in(dataType).out(dataType); - (userrolesDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLES))).in(dataType).out(dataType); - (certsDF = env.newDataFactory(service.mapper().getClass(API.CERTS))).in(dataType).out(dataType) - .rootMarshal((Marshal) service.mapper().getMarshal(API.CERTS)); - ; - (userRoleRequestDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLE_REQ))).in(dataType).out(dataType); - (rolePermRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_PERM_REQ))).in(dataType).out(dataType); - (nsRequestDF = env.newDataFactory(service.mapper().getClass(API.NS_REQ))).in(dataType).out(dataType); - (credRequestDF = env.newDataFactory(service.mapper().getClass(API.CRED_REQ))).in(dataType).out(dataType); - (delgRequestDF = env.newDataFactory(service.mapper().getClass(API.DELG_REQ))).in(dataType).out(dataType); - (historyDF = env.newDataFactory(service.mapper().getClass(API.HISTORY))).in(dataType).out(dataType); - ( keysDF = env.newDataFactory(service.mapper().getClass(API.KEYS))).in(dataType).out(dataType); - (delgDF = env.newDataFactory(service.mapper().getClass(API.DELGS))).in(dataType).out(dataType); - (approvalDF = env.newDataFactory(service.mapper().getClass(API.APPROVALS))).in(dataType).out(dataType); - (errDF = env.newDataFactory(service.mapper().getClass(API.ERROR))).in(dataType).out(dataType); - (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType); - } - - public Mapper mapper() { - return service.mapper(); - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) - * - * Note: Conforms to AT&T TSS RESTful Error Structure - */ - @Override - public void error(AuthzTrans trans, HttpServletResponse response, Result result) { - String msg = result.details==null?"%s":"%s - " + result.details.trim(); - String msgId; - String[] detail; - boolean hidemsg = false; - if(result.variables==null) { - detail = new String[1]; - } else { - int l = result.variables.length; - detail=new String[l+1]; - System.arraycopy(result.variables, 0, detail, 1, l); - } - //int httpstatus; - - switch(result.status) { - case ERR_ActionNotCompleted: - msgId = "SVC1202"; - detail[0] = "Accepted, Action not complete"; - response.setStatus(/*httpstatus=*/202); - break; - - case ERR_Policy: - msgId = "SVC3403"; - detail[0] = FORBIDDEN; - response.setStatus(/*httpstatus=*/403); - break; - case ERR_Security: - msgId = "SVC2403"; - detail[0] = FORBIDDEN; - response.setStatus(/*httpstatus=*/403); - break; - case ERR_Denied: - msgId = "SVC1403"; - detail[0] = FORBIDDEN; - response.setStatus(/*httpstatus=*/403); - break; - // This is still forbidden to directly impact, but can be Requested when passed - // with "request=true" query Param - case ERR_FutureNotRequested: - msgId = "SVC2403"; - detail[0] = msg; - response.setStatus(/*httpstatus=*/403); - break; - - case ERR_NsNotFound: - msgId = "SVC2404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_RoleNotFound: - msgId = "SVC3404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_PermissionNotFound: - msgId = "SVC4404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_UserNotFound: - msgId = "SVC5404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_UserRoleNotFound: - msgId = "SVC6404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_DelegateNotFound: - msgId = "SVC7404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_NotFound: - msgId = "SVC1404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - - case ERR_InvalidDelegate: - msgId="SVC2406"; - detail[0] = NOT_ACCEPTABLE; - response.setStatus(/*httpstatus=*/406); - break; - case ERR_BadData: - msgId="SVC1406"; - detail[0] = NOT_ACCEPTABLE; - response.setStatus(/*httpstatus=*/406); - break; - - case ERR_ConflictAlreadyExists: - msgId = "SVC1409"; - detail[0] = "Conflict Already Exists"; - response.setStatus(/*httpstatus=*/409); - break; - - case ERR_DependencyExists: - msgId = "SVC1424"; - detail[0] = "Failed Dependency"; - response.setStatus(/*httpstatus=*/424); - break; - - case ERR_NotImplemented: - msgId = "SVC1501"; - detail[0] = "Not Implemented"; - response.setStatus(/*httpstatus=*/501); - break; - - case Status.ACC_Future: - msgId = "SVC1202"; - detail[0] = "Accepted for Future, pending Approvals"; - response.setStatus(/*httpstatus=*/202); - break; - case ERR_ChoiceNeeded: - msgId = "SVC1300"; - detail = result.variables; - response.setStatus(/*httpstatus=*/300); - break; - case ERR_Backend: - msgId = "SVC2500"; - detail[0] = GENERAL_SERVICE_ERROR; - response.setStatus(/*httpstatus=*/500); - hidemsg = true; - break; - - default: - msgId = "SVC1500"; - detail[0] = GENERAL_SERVICE_ERROR; - response.setStatus(/*httpstatus=*/500); - hidemsg = true; - break; - } - - try { - StringBuilder holder = new StringBuilder(); - ERR em = service.mapper().errorFromMessage(holder,msgId,msg,detail); - trans.checkpoint( - "ErrResp [" + - msgId + - "] " + - holder.toString(), - Env.ALWAYS); - if(hidemsg) { - holder.setLength(0); - em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); - } - errDF.newData(trans).load(em).to(response.getOutputStream()); - } catch (Exception e) { - trans.error().log(e,"unable to send response for",msg); - } - } - - /////////////////////////// - // Namespace - /////////////////////////// - public static final String CREATE_NS = "createNamespace"; - public static final String ADD_NS_ADMIN = "addNamespaceAdmin"; - public static final String DELETE_NS_ADMIN = "delNamespaceAdmin"; - public static final String ADD_NS_RESPONSIBLE = "addNamespaceResponsible"; - public static final String DELETE_NS_RESPONSIBLE = "delNamespaceResponsible"; - public static final String GET_NS_BY_NAME = "getNamespaceByName"; - public static final String GET_NS_BY_ADMIN = "getNamespaceByAdmin"; - public static final String GET_NS_BY_RESPONSIBLE = "getNamespaceByResponsible"; - public static final String GET_NS_BY_EITHER = "getNamespaceByEither"; - public static final String GET_NS_CHILDREN = "getNamespaceChildren"; - public static final String UPDATE_NS_DESC = "updateNamespaceDescription"; - public static final String DELETE_NS = "deleteNamespace"; - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type) { - TimeTaken tt = trans.start(CREATE_NS, Env.SUB|Env.ALWAYS); - try { - REQUEST request; - try { - Data rd = nsRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,rd.asString()); - } - request = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_NS); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.createNS(trans,request,type); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,CREATE_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(ADD_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.addAdminNS(trans,ns,id); - switch(rp.status) { - case OK: - //TODO Perms?? - setContentType(resp,nsRequestDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,ADD_NS_ADMIN); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(DELETE_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.delAdminNS(trans, ns, id); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_NS_ADMIN); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(ADD_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.addResponsibleNS(trans,ns,id); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,ADD_NS_RESPONSIBLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(DELETE_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.delResponsibleNS(trans, ns, id); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_NS_RESPONSIBLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByName(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(GET_NS_BY_NAME + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyName(trans, ns); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_NAME); - return Result.err(e); - } finally { - tt.done(); - } - } - -// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByAdmin(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ - TimeTaken tt = trans.start(GET_NS_BY_ADMIN + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyAdmin(trans, user, full); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_ADMIN); - return Result.err(e); - } finally { - tt.done(); - } - } - -// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ - TimeTaken tt = trans.start(GET_NS_BY_RESPONSIBLE + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyResponsible(trans, user, full); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_RESPONSIBLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ - TimeTaken tt = trans.start(GET_NS_BY_EITHER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyEither(trans, user, full); - - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_EITHER); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String parent){ - TimeTaken tt = trans.start(GET_NS_CHILDREN + ' ' + parent, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSsChildren(trans, parent); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_CHILDREN); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_NS_DESC, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = nsRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,UPDATE_NS_DESC); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.updateNsDescription(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_NS_DESC); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#requestNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(DELETE_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteNS(trans,ns); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - private final static String NS_CREATE_ATTRIB = "nsCreateAttrib"; - private final static String NS_UPDATE_ATTRIB = "nsUpdateAttrib"; - private final static String READ_NS_BY_ATTRIB = "readNsByAttrib"; - private final static String NS_DELETE_ATTRIB = "nsDeleteAttrib"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { - TimeTaken tt = trans.start(NS_CREATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); - try { - Result rp = service.createNsAttrib(trans,ns,key,value); - switch(rp.status) { - case OK: - setContentType(resp, keysDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,NS_CREATE_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#readAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key) { - TimeTaken tt = trans.start(READ_NS_BY_ATTRIB + ' ' + key, Env.SUB|Env.ALWAYS); - try { - Result rp = service.readNsByAttrib(trans, key); - switch(rp.status) { - case OK: - RosettaData data = keysDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,keysDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,READ_NS_BY_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#updAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { - TimeTaken tt = trans.start(NS_UPDATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); - try { - Result rp = service.updateNsAttrib(trans,ns,key,value); - switch(rp.status) { - case OK: - setContentType(resp, keysDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,NS_UPDATE_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#delAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) - */ - @Override - public Result delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key) { - TimeTaken tt = trans.start(NS_DELETE_ATTRIB + ' ' + ns + ':'+key, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteNsAttrib(trans,ns,key); - switch(rp.status) { - case OK: - setContentType(resp, keysDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,NS_DELETE_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - } + { + private static final String FORBIDDEN = "Forbidden"; + private static final String NOT_FOUND = "Not Found"; + private static final String NOT_ACCEPTABLE = "Not Acceptable"; + private static final String GENERAL_SERVICE_ERROR = "General Service Error"; + private static final String NO_DATA = "***No Data***"; + private AuthzService service = null; + private final RosettaDF nssDF; + private final RosettaDF permsDF; + private final RosettaDF roleDF; + private final RosettaDF usersDF; + private final RosettaDF userrolesDF; + private final RosettaDF certsDF; + private final RosettaDF delgDF; + private final RosettaDF permRequestDF; + private final RosettaDF roleRequestDF; + private final RosettaDF userRoleRequestDF; + private final RosettaDF rolePermRequestDF; + private final RosettaDF nsRequestDF; + private final RosettaDF credRequestDF; + private final RosettaDF delgRequestDF; + private final RosettaDF historyDF; + private final RosettaDF keysDF; + + private final RosettaDF errDF; + private final RosettaDF approvalDF; + // Note: Api is not different per Version + private final RosettaDF apiDF; + + + @SuppressWarnings("unchecked") + public AuthzFacadeImpl(AuthzEnv env, AuthzService service, Data.TYPE dataType) throws APIException { + this.service = service; + (nssDF = env.newDataFactory(service.mapper().getClass(API.NSS))).in(dataType).out(dataType); + (permRequestDF = env.newDataFactory(service.mapper().getClass(API.PERM_REQ))).in(dataType).out(dataType); + (permsDF = env.newDataFactory(service.mapper().getClass(API.PERMS))).in(dataType).out(dataType); +// (permKeyDF = env.newDataFactory(service.mapper().getClass(API.PERM_KEY))).in(dataType).out(dataType); + (roleDF = env.newDataFactory(service.mapper().getClass(API.ROLES))).in(dataType).out(dataType); + (roleRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_REQ))).in(dataType).out(dataType); + (usersDF = env.newDataFactory(service.mapper().getClass(API.USERS))).in(dataType).out(dataType); + (userrolesDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLES))).in(dataType).out(dataType); + (certsDF = env.newDataFactory(service.mapper().getClass(API.CERTS))).in(dataType).out(dataType) + .rootMarshal((Marshal) service.mapper().getMarshal(API.CERTS)); + ; + (userRoleRequestDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLE_REQ))).in(dataType).out(dataType); + (rolePermRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_PERM_REQ))).in(dataType).out(dataType); + (nsRequestDF = env.newDataFactory(service.mapper().getClass(API.NS_REQ))).in(dataType).out(dataType); + (credRequestDF = env.newDataFactory(service.mapper().getClass(API.CRED_REQ))).in(dataType).out(dataType); + (delgRequestDF = env.newDataFactory(service.mapper().getClass(API.DELG_REQ))).in(dataType).out(dataType); + (historyDF = env.newDataFactory(service.mapper().getClass(API.HISTORY))).in(dataType).out(dataType); + ( keysDF = env.newDataFactory(service.mapper().getClass(API.KEYS))).in(dataType).out(dataType); + (delgDF = env.newDataFactory(service.mapper().getClass(API.DELGS))).in(dataType).out(dataType); + (approvalDF = env.newDataFactory(service.mapper().getClass(API.APPROVALS))).in(dataType).out(dataType); + (errDF = env.newDataFactory(service.mapper().getClass(API.ERROR))).in(dataType).out(dataType); + (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType); + } + + public Mapper mapper() { + return service.mapper(); + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) + * + * Note: Conforms to AT&T TSS RESTful Error Structure + */ + @Override + public void error(AuthzTrans trans, HttpServletResponse response, Result result) { + String msg = result.details==null?"%s":"%s - " + result.details.trim(); + String msgId; + String[] detail; + boolean hidemsg = false; + if(result.variables==null) { + detail = new String[1]; + } else { + int l = result.variables.length; + detail=new String[l+1]; + System.arraycopy(result.variables, 0, detail, 1, l); + } + //int httpstatus; + + switch(result.status) { + case ERR_ActionNotCompleted: + msgId = "SVC1202"; + detail[0] = "Accepted, Action not complete"; + response.setStatus(/*httpstatus=*/202); + break; + + case ERR_Policy: + msgId = "SVC3403"; + detail[0] = FORBIDDEN; + response.setStatus(/*httpstatus=*/403); + break; + case ERR_Security: + msgId = "SVC2403"; + detail[0] = FORBIDDEN; + response.setStatus(/*httpstatus=*/403); + break; + case ERR_Denied: + msgId = "SVC1403"; + detail[0] = FORBIDDEN; + response.setStatus(/*httpstatus=*/403); + break; + // This is still forbidden to directly impact, but can be Requested when passed + // with "request=true" query Param + case ERR_FutureNotRequested: + msgId = "SVC2403"; + detail[0] = msg; + response.setStatus(/*httpstatus=*/403); + break; + + case ERR_NsNotFound: + msgId = "SVC2404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_RoleNotFound: + msgId = "SVC3404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_PermissionNotFound: + msgId = "SVC4404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_UserNotFound: + msgId = "SVC5404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_UserRoleNotFound: + msgId = "SVC6404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_DelegateNotFound: + msgId = "SVC7404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_NotFound: + msgId = "SVC1404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + + case ERR_InvalidDelegate: + msgId="SVC2406"; + detail[0] = NOT_ACCEPTABLE; + response.setStatus(/*httpstatus=*/406); + break; + case ERR_BadData: + msgId="SVC1406"; + detail[0] = NOT_ACCEPTABLE; + response.setStatus(/*httpstatus=*/406); + break; + + case ERR_ConflictAlreadyExists: + msgId = "SVC1409"; + detail[0] = "Conflict Already Exists"; + response.setStatus(/*httpstatus=*/409); + break; + + case ERR_DependencyExists: + msgId = "SVC1424"; + detail[0] = "Failed Dependency"; + response.setStatus(/*httpstatus=*/424); + break; + + case ERR_NotImplemented: + msgId = "SVC1501"; + detail[0] = "Not Implemented"; + response.setStatus(/*httpstatus=*/501); + break; + + case Status.ACC_Future: + msgId = "SVC1202"; + detail[0] = "Accepted for Future, pending Approvals"; + response.setStatus(/*httpstatus=*/202); + break; + case ERR_ChoiceNeeded: + msgId = "SVC1300"; + detail = result.variables; + response.setStatus(/*httpstatus=*/300); + break; + case ERR_Backend: + msgId = "SVC2500"; + detail[0] = GENERAL_SERVICE_ERROR; + response.setStatus(/*httpstatus=*/500); + hidemsg = true; + break; + + default: + msgId = "SVC1500"; + detail[0] = GENERAL_SERVICE_ERROR; + response.setStatus(/*httpstatus=*/500); + hidemsg = true; + break; + } + + try { + StringBuilder holder = new StringBuilder(); + ERR em = service.mapper().errorFromMessage(holder,msgId,msg,detail); + trans.checkpoint( + "ErrResp [" + + msgId + + "] " + + holder.toString(), + Env.ALWAYS); + if(hidemsg) { + holder.setLength(0); + em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); + } + errDF.newData(trans).load(em).to(response.getOutputStream()); + } catch (Exception e) { + trans.error().log(e,"unable to send response for",msg); + } + } + + /////////////////////////// + // Namespace + /////////////////////////// + public static final String CREATE_NS = "createNamespace"; + public static final String ADD_NS_ADMIN = "addNamespaceAdmin"; + public static final String DELETE_NS_ADMIN = "delNamespaceAdmin"; + public static final String ADD_NS_RESPONSIBLE = "addNamespaceResponsible"; + public static final String DELETE_NS_RESPONSIBLE = "delNamespaceResponsible"; + public static final String GET_NS_BY_NAME = "getNamespaceByName"; + public static final String GET_NS_BY_ADMIN = "getNamespaceByAdmin"; + public static final String GET_NS_BY_RESPONSIBLE = "getNamespaceByResponsible"; + public static final String GET_NS_BY_EITHER = "getNamespaceByEither"; + public static final String GET_NS_CHILDREN = "getNamespaceChildren"; + public static final String UPDATE_NS_DESC = "updateNamespaceDescription"; + public static final String DELETE_NS = "deleteNamespace"; + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type) { + TimeTaken tt = trans.start(CREATE_NS, Env.SUB|Env.ALWAYS); + try { + REQUEST request; + try { + Data rd = nsRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,rd.asString()); + } + request = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_NS); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.createNS(trans,request,type); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(ADD_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.addAdminNS(trans,ns,id); + switch(rp.status) { + case OK: + //TODO Perms?? + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_NS_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(DELETE_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.delAdminNS(trans, ns, id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(ADD_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.addResponsibleNS(trans,ns,id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_NS_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(DELETE_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.delResponsibleNS(trans, ns, id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByName(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_NS_BY_NAME + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyName(trans, ns); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_NAME); + return Result.err(e); + } finally { + tt.done(); + } + } + +// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByAdmin(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_ADMIN + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyAdmin(trans, user, full); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + +// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_RESPONSIBLE + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyResponsible(trans, user, full); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_EITHER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyEither(trans, user, full); + + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_EITHER); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String parent){ + TimeTaken tt = trans.start(GET_NS_CHILDREN + ' ' + parent, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSsChildren(trans, parent); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_CHILDREN); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_NS_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = nsRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_NS_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.updateNsDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_NS_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#requestNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(DELETE_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deleteNS(trans,ns); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + private final static String NS_CREATE_ATTRIB = "nsCreateAttrib"; + private final static String NS_UPDATE_ATTRIB = "nsUpdateAttrib"; + private final static String READ_NS_BY_ATTRIB = "readNsByAttrib"; + private final static String NS_DELETE_ATTRIB = "nsDeleteAttrib"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { + TimeTaken tt = trans.start(NS_CREATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); + try { + Result rp = service.createNsAttrib(trans,ns,key,value); + switch(rp.status) { + case OK: + setContentType(resp, keysDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,NS_CREATE_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#readAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key) { + TimeTaken tt = trans.start(READ_NS_BY_ATTRIB + ' ' + key, Env.SUB|Env.ALWAYS); + try { + Result rp = service.readNsByAttrib(trans, key); + switch(rp.status) { + case OK: + RosettaData data = keysDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,keysDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,READ_NS_BY_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#updAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { + TimeTaken tt = trans.start(NS_UPDATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); + try { + Result rp = service.updateNsAttrib(trans,ns,key,value); + switch(rp.status) { + case OK: + setContentType(resp, keysDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,NS_UPDATE_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) + */ + @Override + public Result delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key) { + TimeTaken tt = trans.start(NS_DELETE_ATTRIB + ' ' + ns + ':'+key, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deleteNsAttrib(trans,ns,key); + switch(rp.status) { + case OK: + setContentType(resp, keysDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,NS_DELETE_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + } // // PERMISSION // - public static final String CREATE_PERMISSION = "createPermission"; - public static final String GET_PERMS_BY_TYPE = "getPermsByType"; - public static final String GET_PERMS_BY_NAME = "getPermsByName"; - public static final String GET_PERMISSIONS_BY_USER = "getPermissionsByUser"; - public static final String GET_PERMISSIONS_BY_USER_SCOPE = "getPermissionsByUserScope"; - public static final String GET_PERMISSIONS_BY_USER_WITH_QUERY = "getPermissionsByUserWithQuery"; - public static final String GET_PERMISSIONS_BY_ROLE = "getPermissionsByRole"; - public static final String GET_PERMISSIONS_BY_NS = "getPermissionsByNS"; - public static final String UPDATE_PERMISSION = "updatePermission"; - public static final String UPDATE_PERM_DESC = "updatePermissionDescription"; - public static final String SET_PERMISSION_ROLES_TO = "setPermissionRolesTo"; - public static final String DELETE_PERMISSION = "deletePermission"; - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start( CREATE_PERMISSION, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_PERMISSION); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.createPerm(trans,rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,CREATE_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getChildPerms(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String perm) { - TimeTaken tt = trans.start(GET_PERMS_BY_TYPE + ' ' + perm, Env.SUB|Env.ALWAYS); - try { - - Result rp = service.getPermsByType(trans, perm); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMS_BY_TYPE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action) { - - TimeTaken tt = trans.start(GET_PERMS_BY_NAME + ' ' + type - + '|' + instance + '|' + action, Env.SUB|Env.ALWAYS); - try { - - Result rp = service.getPermsByName(trans, type, instance, action); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMS_BY_TYPE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getPermsByUser(trans, user); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_USER, user); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsByUserScope(AuthzTrans trans, HttpServletResponse resp, String user, String[] scopes) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_SCOPE + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getPermsByUserScope(trans, user, scopes); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_SCOPE, user); - return Result.err(e); - } finally { - tt.done(); - } - } - - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_WITH_QUERY + ' ' + user, Env.SUB|Env.ALWAYS); - try { - PERMS perms; - try { - RosettaData data = permsDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - perms = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,GET_PERMISSIONS_BY_USER_WITH_QUERY); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.getPermsByUser(trans, perms, user); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_WITH_QUERY , user); - return Result.err(e); - } finally { - tt.done(); - } - } - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getPermissionsForRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsForRole(AuthzTrans trans, HttpServletResponse resp, String roleName) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_ROLE + ' ' + roleName, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getPermsByRole(trans, roleName); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getPermsByNS(AuthzTrans trans,HttpServletResponse resp,String ns) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getPermsByNS(trans, ns); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, - String origType, String origInstance, String origAction) { - String cmdDescription = UPDATE_PERMISSION; - TimeTaken tt = trans.start( cmdDescription + ' ' + origType + ' ' + origInstance + ' ' + origAction, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,cmdDescription); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.renamePerm(trans,rreq, origType, origInstance, origAction); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,cmdDescription); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_PERM_DESC, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,UPDATE_PERM_DESC); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.updatePermDescription(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_PERM_DESC); - return Result.err(e); - } finally { - tt.done(); - } - } - - - @Override - public Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(SET_PERMISSION_ROLES_TO, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN, SET_PERMISSION_ROLES_TO); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.resetPermRoles(trans, rreq); - - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,SET_PERMISSION_ROLES_TO); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_PERMISSION, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,DELETE_PERMISSION); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - - Result rp = service.deletePerm(trans,rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deletePerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action) { - TimeTaken tt = trans.start(DELETE_PERMISSION + type + ' ' + instance + ' ' + action, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deletePerm(trans,type,instance,action); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - public static final String CREATE_ROLE = "createRole"; - public static final String GET_ROLES_BY_USER = "getRolesByUser"; - public static final String GET_ROLES_BY_NS = "getRolesByNS"; - public static final String GET_ROLES_BY_NAME_ONLY = "getRolesByNameOnly"; - public static final String GET_ROLES_BY_NAME = "getRolesByName"; - public static final String GET_ROLES_BY_PERM = "getRolesByPerm"; - public static final String UPDATE_ROLE_DESC = "updateRoleDescription"; - public static final String ADD_PERM_TO_ROLE = "addPermissionToRole"; - public static final String DELETE_PERM_FROM_ROLE = "deletePermissionFromRole"; - public static final String UPDATE_MGTPERM_ROLE = "updateMgtPermRole"; - public static final String DELETE_ROLE = "deleteRole"; - public static final String GET_CERT_BY_ID = "getCertByID"; - - @Override - public Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(CREATE_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.createRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,roleRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,CREATE_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByName(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(GET_ROLES_BY_NAME + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByName(trans, role); - switch(rp.status) { - case OK: - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,roleDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_NAME); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByUser(AuthzTrans trans,HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_ROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByUser(trans, user); - switch(rp.status) { - case OK: - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,roleDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_USER, user); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByNS(AuthzTrans trans,HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(GET_ROLES_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByNS(trans, ns); - switch(rp.status) { - case OK: - if(!rp.isEmpty()) { - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - } else { - Question.logEncryptTrace(trans, NO_DATA); - } - setContentType(resp,roleDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByNameOnly(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByNameOnly(AuthzTrans trans,HttpServletResponse resp, String nameOnly) { - TimeTaken tt = trans.start(GET_ROLES_BY_NAME_ONLY + ' ' + nameOnly, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByNameOnly(trans, nameOnly); - switch(rp.status) { - case OK: - if(!rp.isEmpty()) { - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - } else { - Question.logEncryptTrace(trans, NO_DATA); - } - setContentType(resp,roleDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_NAME_ONLY); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByPerm(AuthzTrans trans,HttpServletResponse resp, String type, String instance, String action) { - TimeTaken tt = trans.start(GET_ROLES_BY_PERM + type +' '+instance+' '+action, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByPerm(trans, type,instance,action); - switch(rp.status) { - case OK: - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,roleDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_PERM); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#updateDescription(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_ROLE_DESC, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,UPDATE_ROLE_DESC); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.updateRoleDescription(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,roleRequestDF.getOutType()); - return Result.ok(); - default: - return rp; - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_ROLE_DESC); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result addPermToRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(ADD_PERM_TO_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,ADD_PERM_TO_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.addPermToRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,ADD_PERM_TO_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result delPermFromRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,DELETE_PERM_FROM_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.delPermFromRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#delPermFromRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result delPermFromRole(AuthzTrans trans, HttpServletResponse resp, String role, String type, - String instance, String action) { - TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); - try { - Result rp = service.delPermFromRole(trans, role, type, instance, action); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(DELETE_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteRole(trans, role); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.deleteRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - public static final String CREATE_CRED = "createUserCred"; - private static final String GET_CREDS_BY_NS = "getCredsByNS"; - private static final String GET_CREDS_BY_ID = "getCredsByID"; - public static final String UPDATE_CRED = "updateUserCred"; - public static final String EXTEND_CRED = "extendUserCred"; - public static final String DELETE_CRED = "deleteUserCred"; - public static final String DOES_CRED_MATCH = "doesCredMatch"; - public static final String VALIDATE_BASIC_AUTH = "validateBasicAuth"; - - - - @Override - /** - * Create Credential - * - */ - public Result createUserCred(AuthzTrans trans, HttpServletRequest req) { - TimeTaken tt = trans.start(CREATE_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - return service.createUserCred(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,CREATE_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result changeUserCred(AuthzTrans trans, HttpServletRequest req) { - TimeTaken tt = trans.start(UPDATE_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.changeUserCred(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#extendUserCred(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, int) - */ - @Override - public Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days) { - TimeTaken tt = trans.start(EXTEND_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.extendUserCred(trans, data.asObject(), days); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,EXTEND_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(GET_CREDS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - - try { - Result ru = service.getCredsByNS(trans,ns); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans,trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_CREDS_BY_NS); - return Result.err(e); - } finally { - tt.done(); - } - - } - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getCredsByID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id) { - TimeTaken tt = trans.start(GET_CREDS_BY_ID + ' ' + id, Env.SUB|Env.ALWAYS); - - try { - Result ru = service.getCredsByID(trans,id); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_CREDS_BY_ID); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result deleteUserCred(AuthzTrans trans, HttpServletRequest req) { - TimeTaken tt = trans.start(DELETE_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.deleteUserCred(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,DELETE_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - - @Override - public Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DOES_CRED_MATCH, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.doesCredentialMatch(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (IOException e) { - trans.error().log(e,IN,DOES_CRED_MATCH); - return Result.err(e); - } finally { - tt.done(); - } - } - - - @Override - public Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth) { - TimeTaken tt = trans.start(VALIDATE_BASIC_AUTH, Env.SUB|Env.ALWAYS); - try { - Result result = service.validateBasicAuth(trans,basicAuth); - switch(result.status){ - case OK: - resp.getOutputStream().write(Chrono.utcStamp(result.value).getBytes()); - return Result.ok(); - } - return Result.err(result); - } catch (Exception e) { - trans.error().log(e,IN,VALIDATE_BASIC_AUTH); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getCertInfoByID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id) { - TimeTaken tt = trans.start(GET_CERT_BY_ID, Env.SUB|Env.ALWAYS); - try { - Result rci = service.getCertInfoByID(trans,req,id); - - switch(rci.status) { - case OK: - if(Question.willSpecialLog(trans, trans.user())) { - RosettaData data = certsDF.newData(trans).load(rci.value); - Question.logEncryptTrace(trans,data.asString()); - data.to(resp.getOutputStream()); - } else { - certsDF.direct(trans, rci.value, resp.getOutputStream()); - } - setContentType(resp,certsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rci); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_CERT_BY_ID); - return Result.err(e); - } finally { - tt.done(); - } - } - - public static final String CREATE_DELEGATE = "createDelegate"; - public static final String UPDATE_DELEGATE = "updateDelegate"; - public static final String DELETE_DELEGATE = "deleteDelegate"; - public static final String GET_DELEGATE_USER = "getDelegatesByUser"; - public static final String GET_DELEGATE_DELG = "getDelegatesByDelegate"; - - @Override - public Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(CREATE_DELEGATE, Env.SUB|Env.ALWAYS); - try { - Data data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.createDelegate(trans, data.asObject()); - } catch (Exception e) { - trans.error().log(e,IN,CREATE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_DELEGATE, Env.SUB|Env.ALWAYS); - try { - Data data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.updateDelegate(trans, data.asObject()); - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_DELEGATE, Env.SUB|Env.ALWAYS); - try { - Data data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.deleteDelegate(trans, data.asObject()); - } catch (Exception e) { - trans.error().log(e,IN,DELETE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteDelegate(AuthzTrans trans, String userName) { - TimeTaken tt = trans.start(DELETE_DELEGATE + ' ' + userName, Env.SUB|Env.ALWAYS); - try { - return service.deleteDelegate(trans, userName); - } catch (Exception e) { - trans.error().log(e,IN,DELETE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getDelegatesByUser(AuthzTrans trans, String user, HttpServletResponse resp) { - TimeTaken tt = trans.start(GET_DELEGATE_USER, Env.SUB|Env.ALWAYS); - try { - Result rd = service.getDelegatesByUser(trans, user); - - switch(rd.status) { - case OK: - RosettaData data = delgDF.newData(trans).load(rd.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,delgDF.getOutType()); - return Result.ok(); - default: - return Result.err(rd); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_DELEGATE_USER); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getDelegatesByDelegate(AuthzTrans trans, String delegate, HttpServletResponse resp) { - TimeTaken tt = trans.start(GET_DELEGATE_DELG, Env.SUB|Env.ALWAYS); - try { - Result rd = service.getDelegatesByDelegate(trans, delegate); - switch(rd.status) { - case OK: - RosettaData data = delgDF.newData(trans).load(rd.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,delgDF.getOutType()); - return Result.ok(); - default: - return Result.err(rd); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_DELEGATE_DELG); - return Result.err(e); - } finally { - tt.done(); - } - } - - private static final String REQUEST_USER_ROLE = "createUserRole"; - private static final String GET_USERROLES = "getUserRoles"; - private static final String GET_USERROLES_BY_ROLE = "getUserRolesByRole"; - private static final String GET_USERROLES_BY_USER = "getUserRolesByUser"; - private static final String SET_ROLES_FOR_USER = "setRolesForUser"; - private static final String SET_USERS_FOR_ROLE = "setUsersForRole"; - private static final String EXTEND_USER_ROLE = "extendUserRole"; - private static final String DELETE_USER_ROLE = "deleteUserRole"; - @Override - public Result requestUserRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(REQUEST_USER_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST request; - try { - Data data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - request = data.asObject(); - } catch(APIException e) { - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.createUserRole(trans,request); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,REQUEST_USER_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { - TimeTaken tt = trans.start(GET_USERROLES + ' ' + user + '|' + role, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUserInRole(trans,user,role); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERROLES); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_USERROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUserRolesByUser(trans,user); - switch(ru.status) { - case OK: - RosettaData data = userrolesDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERROLES_BY_USER); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(GET_USERROLES_BY_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUserRolesByRole(trans,role); - switch(ru.status) { - case OK: - RosettaData data = userrolesDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - setCacheControlOff(resp); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERROLES_BY_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - - } - - - @Override - public Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { - TimeTaken tt = trans.start(SET_USERS_FOR_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN, SET_USERS_FOR_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.resetUsersForRole(trans, rreq); - - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,SET_USERS_FOR_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { - TimeTaken tt = trans.start(SET_ROLES_FOR_USER, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN, SET_ROLES_FOR_USER); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.resetRolesForUser(trans, rreq); - - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,SET_ROLES_FOR_USER); - return Result.err(e); - } finally { - tt.done(); - } - - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#extendUserRoleExpiration(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) - */ - @Override - public Result extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, String role) { - TimeTaken tt = trans.start(EXTEND_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); - try { - return service.extendUserRole(trans,user,role); - } catch (Exception e) { - trans.error().log(e,IN,EXTEND_USER_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { - TimeTaken tt = trans.start(DELETE_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteUserRole(trans,user,role); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_USER_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - private static final String UPDATE_APPROVAL = "updateApproval"; - private static final String GET_APPROVALS_BY_USER = "getApprovalsByUser."; - private static final String GET_APPROVALS_BY_TICKET = "getApprovalsByTicket."; - private static final String GET_APPROVALS_BY_APPROVER = "getApprovalsByApprover."; - - @Override - public Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_APPROVAL, Env.SUB|Env.ALWAYS); - try { - Data data = approvalDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - Result rp = service.updateApproval(trans, data.asObject()); - - switch(rp.status) { - case OK: - setContentType(resp,approvalDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_APPROVAL); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_APPROVALS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getApprovalsByUser(trans, user); - switch(rp.status) { - case OK: - RosettaData data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_APPROVALS_BY_USER, user); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver) { - TimeTaken tt = trans.start(GET_APPROVALS_BY_APPROVER + ' ' + approver, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getApprovalsByApprover(trans, approver); - switch(rp.status) { - case OK: - RosettaData data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_APPROVALS_BY_APPROVER,approver); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket) { - TimeTaken tt = trans.start(GET_APPROVALS_BY_TICKET, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getApprovalsByTicket(trans, ticket); - switch(rp.status) { - case OK: - RosettaData data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_APPROVALS_BY_TICKET); - return Result.err(e); - } finally { - tt.done(); - } - } - - - - public static final String GET_USERS_PERMISSION = "getUsersByPermission"; - public static final String GET_USERS_ROLE = "getUsersByRole"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getUsersByRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(GET_USERS_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUsersByRole(trans,role); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERS_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getUsersByPermission(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action) { - TimeTaken tt = trans.start(GET_USERS_PERMISSION + ' ' + type + ' ' + instance + ' ' +action, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUsersByPermission(trans,type,instance,action); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERS_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - - public static final String GET_HISTORY_USER = "getHistoryByUser"; - public static final String GET_HISTORY_ROLE = "getHistoryByRole"; - public static final String GET_HISTORY_PERM = "getHistoryByPerm"; - public static final String GET_HISTORY_NS = "getHistoryByNS"; - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_USER); - sb.append(' '); - sb.append(user); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - - try { - Result rh = service.getHistoryByUser(trans,user,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_USER); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) - */ - @Override - public Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String role, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_ROLE); - sb.append(' '); - sb.append(role); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - try { - Result rh = service.getHistoryByRole(trans,role,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) - */ - @Override - public Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String ns, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_NS); - sb.append(' '); - sb.append(ns); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - try { - Result rh = service.getHistoryByNS(trans,ns,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByPerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) - */ - @Override - public Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String perm, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_PERM); - sb.append(' '); - sb.append(perm); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - try { - Result rh = service.getHistoryByPerm(trans,perm,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_PERM); - return Result.err(e); - } finally { - tt.done(); - } - } - - public final static String CACHE_CLEAR = "cacheClear "; -// public final static String CACHE_VALIDATE = "validateCache"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) - */ - @Override - public Result cacheClear(AuthzTrans trans, String cname) { - TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS); - try { - return service.cacheClear(trans,cname); - } catch (Exception e) { - trans.error().log(e,IN,CACHE_CLEAR); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) + public static final String CREATE_PERMISSION = "createPermission"; + public static final String GET_PERMS_BY_TYPE = "getPermsByType"; + public static final String GET_PERMS_BY_NAME = "getPermsByName"; + public static final String GET_PERMISSIONS_BY_USER = "getPermissionsByUser"; + public static final String GET_PERMISSIONS_BY_USER_SCOPE = "getPermissionsByUserScope"; + public static final String GET_PERMISSIONS_BY_USER_WITH_QUERY = "getPermissionsByUserWithQuery"; + public static final String GET_PERMISSIONS_BY_ROLE = "getPermissionsByRole"; + public static final String GET_PERMISSIONS_BY_NS = "getPermissionsByNS"; + public static final String UPDATE_PERMISSION = "updatePermission"; + public static final String UPDATE_PERM_DESC = "updatePermissionDescription"; + public static final String SET_PERMISSION_ROLES_TO = "setPermissionRolesTo"; + public static final String DELETE_PERMISSION = "deletePermission"; + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start( CREATE_PERMISSION, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_PERMISSION); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.createPerm(trans,rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getChildPerms(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String perm) { + TimeTaken tt = trans.start(GET_PERMS_BY_TYPE + ' ' + perm, Env.SUB|Env.ALWAYS); + try { + + Result rp = service.getPermsByType(trans, perm); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMS_BY_TYPE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action) { + + TimeTaken tt = trans.start(GET_PERMS_BY_NAME + ' ' + type + + '|' + instance + '|' + action, Env.SUB|Env.ALWAYS); + try { + + Result rp = service.getPermsByName(trans, type, instance, action); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMS_BY_TYPE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getPermsByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsByUserScope(AuthzTrans trans, HttpServletResponse resp, String user, String[] scopes) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_SCOPE + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getPermsByUserScope(trans, user, scopes); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_SCOPE, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_WITH_QUERY + ' ' + user, Env.SUB|Env.ALWAYS); + try { + PERMS perms; + try { + RosettaData data = permsDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + perms = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,GET_PERMISSIONS_BY_USER_WITH_QUERY); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.getPermsByUser(trans, perms, user); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_WITH_QUERY , user); + return Result.err(e); + } finally { + tt.done(); + } + } + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionsForRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsForRole(AuthzTrans trans, HttpServletResponse resp, String roleName) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_ROLE + ' ' + roleName, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getPermsByRole(trans, roleName); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getPermsByNS(AuthzTrans trans,HttpServletResponse resp,String ns) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getPermsByNS(trans, ns); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, + String origType, String origInstance, String origAction) { + String cmdDescription = UPDATE_PERMISSION; + TimeTaken tt = trans.start( cmdDescription + ' ' + origType + ' ' + origInstance + ' ' + origAction, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,cmdDescription); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.renamePerm(trans,rreq, origType, origInstance, origAction); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,cmdDescription); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_PERM_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_PERM_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.updatePermDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_PERM_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(SET_PERMISSION_ROLES_TO, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_PERMISSION_ROLES_TO); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.resetPermRoles(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_PERMISSION_ROLES_TO); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_PERMISSION, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_PERMISSION); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + + Result rp = service.deletePerm(trans,rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deletePerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action) { + TimeTaken tt = trans.start(DELETE_PERMISSION + type + ' ' + instance + ' ' + action, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deletePerm(trans,type,instance,action); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_ROLE = "createRole"; + public static final String GET_ROLES_BY_USER = "getRolesByUser"; + public static final String GET_ROLES_BY_NS = "getRolesByNS"; + public static final String GET_ROLES_BY_NAME_ONLY = "getRolesByNameOnly"; + public static final String GET_ROLES_BY_NAME = "getRolesByName"; + public static final String GET_ROLES_BY_PERM = "getRolesByPerm"; + public static final String UPDATE_ROLE_DESC = "updateRoleDescription"; + public static final String ADD_PERM_TO_ROLE = "addPermissionToRole"; + public static final String DELETE_PERM_FROM_ROLE = "deletePermissionFromRole"; + public static final String UPDATE_MGTPERM_ROLE = "updateMgtPermRole"; + public static final String DELETE_ROLE = "deleteRole"; + public static final String GET_CERT_BY_ID = "getCertByID"; + + @Override + public Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.createRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,roleRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByName(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_ROLES_BY_NAME + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByName(trans, role); + switch(rp.status) { + case OK: + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NAME); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByUser(AuthzTrans trans,HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_ROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByNS(AuthzTrans trans,HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_ROLES_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByNS(trans, ns); + switch(rp.status) { + case OK: + if(!rp.isEmpty()) { + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + } else { + Question.logEncryptTrace(trans, NO_DATA); + } + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByNameOnly(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByNameOnly(AuthzTrans trans,HttpServletResponse resp, String nameOnly) { + TimeTaken tt = trans.start(GET_ROLES_BY_NAME_ONLY + ' ' + nameOnly, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByNameOnly(trans, nameOnly); + switch(rp.status) { + case OK: + if(!rp.isEmpty()) { + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + } else { + Question.logEncryptTrace(trans, NO_DATA); + } + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NAME_ONLY); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByPerm(AuthzTrans trans,HttpServletResponse resp, String type, String instance, String action) { + TimeTaken tt = trans.start(GET_ROLES_BY_PERM + type +' '+instance+' '+action, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByPerm(trans, type,instance,action); + switch(rp.status) { + case OK: + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_PERM); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#updateDescription(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_ROLE_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_ROLE_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.updateRoleDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,roleRequestDF.getOutType()); + return Result.ok(); + default: + return rp; + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_ROLE_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result addPermToRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(ADD_PERM_TO_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,ADD_PERM_TO_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.addPermToRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_PERM_TO_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result delPermFromRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_PERM_FROM_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.delPermFromRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delPermFromRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result delPermFromRole(AuthzTrans trans, HttpServletResponse resp, String role, String type, + String instance, String action) { + TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); + try { + Result rp = service.delPermFromRole(trans, role, type, instance, action); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(DELETE_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deleteRole(trans, role); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.deleteRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_CRED = "createUserCred"; + private static final String GET_CREDS_BY_NS = "getCredsByNS"; + private static final String GET_CREDS_BY_ID = "getCredsByID"; + public static final String UPDATE_CRED = "updateUserCred"; + public static final String EXTEND_CRED = "extendUserCred"; + public static final String DELETE_CRED = "deleteUserCred"; + public static final String DOES_CRED_MATCH = "doesCredMatch"; + public static final String VALIDATE_BASIC_AUTH = "validateBasicAuth"; + + + + @Override + /** + * Create Credential + * + */ + public Result createUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(CREATE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + return service.createUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,CREATE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result changeUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(UPDATE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.changeUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#extendUserCred(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, int) + */ + @Override + public Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days) { + TimeTaken tt = trans.start(EXTEND_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.extendUserCred(trans, data.asObject(), days); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,EXTEND_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_CREDS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + + try { + Result ru = service.getCredsByNS(trans,ns); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans,trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CREDS_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + + } + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getCredsByID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id) { + TimeTaken tt = trans.start(GET_CREDS_BY_ID + ' ' + id, Env.SUB|Env.ALWAYS); + + try { + Result ru = service.getCredsByID(trans,id); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CREDS_BY_ID); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result deleteUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(DELETE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.deleteUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DOES_CRED_MATCH, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.doesCredentialMatch(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (IOException e) { + trans.error().log(e,IN,DOES_CRED_MATCH); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth) { + TimeTaken tt = trans.start(VALIDATE_BASIC_AUTH, Env.SUB|Env.ALWAYS); + try { + Result result = service.validateBasicAuth(trans,basicAuth); + switch(result.status){ + case OK: + resp.getOutputStream().write(Chrono.utcStamp(result.value).getBytes()); + return Result.ok(); + } + return Result.err(result); + } catch (Exception e) { + trans.error().log(e,IN,VALIDATE_BASIC_AUTH); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getCertInfoByID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id) { + TimeTaken tt = trans.start(GET_CERT_BY_ID, Env.SUB|Env.ALWAYS); + try { + Result rci = service.getCertInfoByID(trans,req,id); + + switch(rci.status) { + case OK: + if(Question.willSpecialLog(trans, trans.user())) { + RosettaData data = certsDF.newData(trans).load(rci.value); + Question.logEncryptTrace(trans,data.asString()); + data.to(resp.getOutputStream()); + } else { + certsDF.direct(trans, rci.value, resp.getOutputStream()); + } + setContentType(resp,certsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rci); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CERT_BY_ID); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_DELEGATE = "createDelegate"; + public static final String UPDATE_DELEGATE = "updateDelegate"; + public static final String DELETE_DELEGATE = "deleteDelegate"; + public static final String GET_DELEGATE_USER = "getDelegatesByUser"; + public static final String GET_DELEGATE_DELG = "getDelegatesByDelegate"; + + @Override + public Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.createDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,CREATE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.updateDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.deleteDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteDelegate(AuthzTrans trans, String userName) { + TimeTaken tt = trans.start(DELETE_DELEGATE + ' ' + userName, Env.SUB|Env.ALWAYS); + try { + return service.deleteDelegate(trans, userName); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getDelegatesByUser(AuthzTrans trans, String user, HttpServletResponse resp) { + TimeTaken tt = trans.start(GET_DELEGATE_USER, Env.SUB|Env.ALWAYS); + try { + Result rd = service.getDelegatesByUser(trans, user); + + switch(rd.status) { + case OK: + RosettaData data = delgDF.newData(trans).load(rd.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,delgDF.getOutType()); + return Result.ok(); + default: + return Result.err(rd); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_DELEGATE_USER); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getDelegatesByDelegate(AuthzTrans trans, String delegate, HttpServletResponse resp) { + TimeTaken tt = trans.start(GET_DELEGATE_DELG, Env.SUB|Env.ALWAYS); + try { + Result rd = service.getDelegatesByDelegate(trans, delegate); + switch(rd.status) { + case OK: + RosettaData data = delgDF.newData(trans).load(rd.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,delgDF.getOutType()); + return Result.ok(); + default: + return Result.err(rd); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_DELEGATE_DELG); + return Result.err(e); + } finally { + tt.done(); + } + } + + private static final String REQUEST_USER_ROLE = "createUserRole"; + private static final String GET_USERROLES = "getUserRoles"; + private static final String GET_USERROLES_BY_ROLE = "getUserRolesByRole"; + private static final String GET_USERROLES_BY_USER = "getUserRolesByUser"; + private static final String SET_ROLES_FOR_USER = "setRolesForUser"; + private static final String SET_USERS_FOR_ROLE = "setUsersForRole"; + private static final String EXTEND_USER_ROLE = "extendUserRole"; + private static final String DELETE_USER_ROLE = "deleteUserRole"; + @Override + public Result requestUserRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(REQUEST_USER_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST request; + try { + Data data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + request = data.asObject(); + } catch(APIException e) { + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.createUserRole(trans,request); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,REQUEST_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(GET_USERROLES + ' ' + user + '|' + role, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUserInRole(trans,user,role); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_USERROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUserRolesByUser(trans,user); + switch(ru.status) { + case OK: + RosettaData data = userrolesDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES_BY_USER); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_USERROLES_BY_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUserRolesByRole(trans,role); + switch(ru.status) { + case OK: + RosettaData data = userrolesDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES_BY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + + } + + + @Override + public Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { + TimeTaken tt = trans.start(SET_USERS_FOR_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_USERS_FOR_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.resetUsersForRole(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_USERS_FOR_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { + TimeTaken tt = trans.start(SET_ROLES_FOR_USER, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_ROLES_FOR_USER); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.resetRolesForUser(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_ROLES_FOR_USER); + return Result.err(e); + } finally { + tt.done(); + } + + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#extendUserRoleExpiration(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) + */ + @Override + public Result extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(EXTEND_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); + try { + return service.extendUserRole(trans,user,role); + } catch (Exception e) { + trans.error().log(e,IN,EXTEND_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(DELETE_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deleteUserRole(trans,user,role); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + private static final String UPDATE_APPROVAL = "updateApproval"; + private static final String GET_APPROVALS_BY_USER = "getApprovalsByUser."; + private static final String GET_APPROVALS_BY_TICKET = "getApprovalsByTicket."; + private static final String GET_APPROVALS_BY_APPROVER = "getApprovalsByApprover."; + + @Override + public Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_APPROVAL, Env.SUB|Env.ALWAYS); + try { + Data data = approvalDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + Result rp = service.updateApproval(trans, data.asObject()); + + switch(rp.status) { + case OK: + setContentType(resp,approvalDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_APPROVAL); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getApprovalsByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_APPROVER + ' ' + approver, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getApprovalsByApprover(trans, approver); + switch(rp.status) { + case OK: + RosettaData data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_APPROVER,approver); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_TICKET, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getApprovalsByTicket(trans, ticket); + switch(rp.status) { + case OK: + RosettaData data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_TICKET); + return Result.err(e); + } finally { + tt.done(); + } + } + + + + public static final String GET_USERS_PERMISSION = "getUsersByPermission"; + public static final String GET_USERS_ROLE = "getUsersByRole"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getUsersByRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_USERS_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUsersByRole(trans,role); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERS_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getUsersByPermission(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action) { + TimeTaken tt = trans.start(GET_USERS_PERMISSION + ' ' + type + ' ' + instance + ' ' +action, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUsersByPermission(trans,type,instance,action); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERS_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + + public static final String GET_HISTORY_USER = "getHistoryByUser"; + public static final String GET_HISTORY_ROLE = "getHistoryByRole"; + public static final String GET_HISTORY_PERM = "getHistoryByPerm"; + public static final String GET_HISTORY_NS = "getHistoryByNS"; + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_USER); + sb.append(' '); + sb.append(user); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + + try { + Result rh = service.getHistoryByUser(trans,user,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_USER); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String role, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_ROLE); + sb.append(' '); + sb.append(role); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result rh = service.getHistoryByRole(trans,role,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String ns, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_NS); + sb.append(' '); + sb.append(ns); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result rh = service.getHistoryByNS(trans,ns,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByPerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String perm, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_PERM); + sb.append(' '); + sb.append(perm); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result rh = service.getHistoryByPerm(trans,perm,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_PERM); + return Result.err(e); + } finally { + tt.done(); + } + } + + public final static String CACHE_CLEAR = "cacheClear "; +// public final static String CACHE_VALIDATE = "validateCache"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @Override + public Result cacheClear(AuthzTrans trans, String cname) { + TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS); + try { + return service.cacheClear(trans,cname); + } catch (Exception e) { + trans.error().log(e,IN,CACHE_CLEAR); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) * @see com.att.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer) */ - @Override - public Result cacheClear(AuthzTrans trans, String cname, String segments) { - TimeTaken tt = trans.start(CACHE_CLEAR + cname + ", segments[" + segments + ']', Env.SUB|Env.ALWAYS); - try { - String[] segs = segments.split("\\s*,\\s*"); - int isegs[] = new int[segs.length]; - for(int i=0;i getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet) { - TimeTaken tt = trans.start(API_REPORT, Env.SUB); - try { - Api api = new Api(); - Api.Route ar; - Method[] meths = AuthzCassServiceImpl.class.getDeclaredMethods(); - for(RouteReport rr : rservlet.routeReport()) { - api.getRoute().add(ar = new Api.Route()); - ar.setMeth(rr.meth.name()); - ar.setPath(rr.path); - ar.setDesc(rr.desc); - ar.getContentType().addAll(rr.contextTypes); - for(Method m : meths) { - ApiDoc ad; - if((ad = m.getAnnotation(ApiDoc.class))!=null && - rr.meth.equals(ad.method()) && - rr.path.equals(ad.path())) { - for(String param : ad.params()) { - ar.getParam().add(param); - } - for(String text : ad.text()) { - ar.getComments().add(text); - } - ar.setExpected(ad.expectedCode()); - for(int ec : ad.errorCodes()) { - ar.getExplicitErr().add(ec); - } - } - } - } - RosettaData data = apiDF.newData(trans).load(api); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,apiDF.getOutType()); - return Result.ok(); - - } catch (Exception e) { - trans.error().log(e,IN,API_REPORT); - return Result.err(e); - } finally { - tt.done(); - } - } - - - public final static String API_EXAMPLE = "apiExample"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getAPIExample(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) { - TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB); - try { - String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); - resp.getOutputStream().print(content); - setContentType(resp,content.contains(" cacheClear(AuthzTrans trans, String cname, String segments) { + TimeTaken tt = trans.start(CACHE_CLEAR + cname + ", segments[" + segments + ']', Env.SUB|Env.ALWAYS); + try { + String[] segs = segments.split("\\s*,\\s*"); + int isegs[] = new int[segs.length]; + for(int i=0;i getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet) { + TimeTaken tt = trans.start(API_REPORT, Env.SUB); + try { + Api api = new Api(); + Api.Route ar; + Method[] meths = AuthzCassServiceImpl.class.getDeclaredMethods(); + for(RouteReport rr : rservlet.routeReport()) { + api.getRoute().add(ar = new Api.Route()); + ar.setMeth(rr.meth.name()); + ar.setPath(rr.path); + ar.setDesc(rr.desc); + ar.getContentType().addAll(rr.contextTypes); + for(Method m : meths) { + ApiDoc ad; + if((ad = m.getAnnotation(ApiDoc.class))!=null && + rr.meth.equals(ad.method()) && + rr.path.equals(ad.path())) { + for(String param : ad.params()) { + ar.getParam().add(param); + } + for(String text : ad.text()) { + ar.getComments().add(text); + } + ar.setExpected(ad.expectedCode()); + for(int ec : ad.errorCodes()) { + ar.getExplicitErr().add(ec); + } + } + } + } + RosettaData data = apiDF.newData(trans).load(api); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,apiDF.getOutType()); + return Result.ok(); + + } catch (Exception e) { + trans.error().log(e,IN,API_REPORT); + return Result.err(e); + } finally { + tt.done(); + } + } + + + public final static String API_EXAMPLE = "apiExample"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getAPIExample(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) { + TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB); + try { + String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); + resp.getOutputStream().print(content); + setContentType(resp,content.contains(" + Nss, + Perms, + Pkey, + Roles, + Users, + UserRoles, + Delgs, + Certs, + Keys, + Request, + History, + Error, + Approvals> { - public AuthzFacade_2_0(AuthzEnv env, - AuthzService service, - Data.TYPE type) throws APIException { - super(env, service, type); - } + public AuthzFacade_2_0(AuthzEnv env, + AuthzService service, + Data.TYPE type) throws APIException { + super(env, service, type); + } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper.java index e7cedf96..c66525da 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper.java @@ -41,82 +41,82 @@ import org.onap.aaf.auth.service.MayChange; import org.onap.aaf.misc.rosetta.Marshal; public interface Mapper< - NSS, - PERMS, - PERMKEY, - ROLES, - USERS, - USERROLES, - DELGS, - CERTS, - KEYS, - REQUEST, - HISTORY, - ERROR, - APPROVALS> + NSS, + PERMS, + PERMKEY, + ROLES, + USERS, + USERROLES, + DELGS, + CERTS, + KEYS, + REQUEST, + HISTORY, + ERROR, + APPROVALS> { - enum API{NSS,NS_REQ, - PERMS,PERM_KEY,PERM_REQ, - ROLES,ROLE,ROLE_REQ,ROLE_PERM_REQ, - USERS,USER_ROLE_REQ,USER_ROLES, - CRED_REQ,CERTS, - APPROVALS, - DELGS,DELG_REQ, - KEYS, - HISTORY, - ERROR, - API, - VOID}; - public Class getClass(API api); - public
    Marshal getMarshal(API api); - public A newInstance(API api); + enum API{NSS,NS_REQ, + PERMS,PERM_KEY,PERM_REQ, + ROLES,ROLE,ROLE_REQ,ROLE_PERM_REQ, + USERS,USER_ROLE_REQ,USER_ROLES, + CRED_REQ,CERTS, + APPROVALS, + DELGS,DELG_REQ, + KEYS, + HISTORY, + ERROR, + API, + VOID}; + public Class getClass(API api); + public Marshal getMarshal(API api); + public A newInstance(API api); - public Result permkey(AuthzTrans trans, PERMKEY from); - public Result perm(AuthzTrans trans, REQUEST from); - public Result role(AuthzTrans trans, REQUEST from); - public Result ns(AuthzTrans trans, REQUEST from); - public Result cred(AuthzTrans trans, REQUEST from, boolean requiresPass); - public Result cred(List lcred, USERS to); - public Result cert(List lcert, CERTS to); - public Result delegate(AuthzTrans trans, REQUEST from); - public Result delegate(List lDelg); - public Result approvals(List lAppr); - public Result> approvals(APPROVALS apprs); - public Result> perms(AuthzTrans trans, PERMS perms); - - public Result userRole(AuthzTrans trans, REQUEST from); - public Result permFromRPRequest(AuthzTrans trans, REQUEST from); - public REQUEST ungrantRequest(AuthzTrans trans, String role, String type, String instance, String action); - public Result roleFromRPRequest(AuthzTrans trans, REQUEST from); - - /* - * Check Requests of varying sorts for Future fields set - */ - public Result future(AuthzTrans trans, String table, REQUEST from, Bytification content, boolean enableApproval, Memo memo, MayChange mc); + public Result permkey(AuthzTrans trans, PERMKEY from); + public Result perm(AuthzTrans trans, REQUEST from); + public Result role(AuthzTrans trans, REQUEST from); + public Result ns(AuthzTrans trans, REQUEST from); + public Result cred(AuthzTrans trans, REQUEST from, boolean requiresPass); + public Result cred(List lcred, USERS to); + public Result cert(List lcert, CERTS to); + public Result delegate(AuthzTrans trans, REQUEST from); + public Result delegate(List lDelg); + public Result approvals(List lAppr); + public Result> approvals(APPROVALS apprs); + public Result> perms(AuthzTrans trans, PERMS perms); + + public Result userRole(AuthzTrans trans, REQUEST from); + public Result permFromRPRequest(AuthzTrans trans, REQUEST from); + public REQUEST ungrantRequest(AuthzTrans trans, String role, String type, String instance, String action); + public Result roleFromRPRequest(AuthzTrans trans, REQUEST from); + + /* + * Check Requests of varying sorts for Future fields set + */ + public Result future(AuthzTrans trans, String table, REQUEST from, Bytification content, boolean enableApproval, Memo memo, MayChange mc); - public Result nss(AuthzTrans trans, Namespace from, NSS to); + public Result nss(AuthzTrans trans, Namespace from, NSS to); - // Note: Prevalidate if NS given is allowed to be seen before calling - public Result nss(AuthzTrans trans, Collection from, NSS to); -// public Result ns_attrib(AuthzTrans trans, Set from, NSS to); - public Result perms(AuthzTrans trans, List from, PERMS to, boolean filter); - public Result perms(AuthzTrans trans, List from, PERMS to, String[] scopes, boolean filter); - public Result roles(AuthzTrans trans, List from, ROLES roles, boolean filter); - // Note: Prevalidate if NS given is allowed to be seen before calling - public Result users(AuthzTrans trans, Collection from, USERS to); - public Result userRoles(AuthzTrans trans, Collection from, USERROLES to); - public Result keys(Collection from); + // Note: Prevalidate if NS given is allowed to be seen before calling + public Result nss(AuthzTrans trans, Collection from, NSS to); +// public Result ns_attrib(AuthzTrans trans, Set from, NSS to); + public Result perms(AuthzTrans trans, List from, PERMS to, boolean filter); + public Result perms(AuthzTrans trans, List from, PERMS to, String[] scopes, boolean filter); + public Result roles(AuthzTrans trans, List from, ROLES roles, boolean filter); + // Note: Prevalidate if NS given is allowed to be seen before calling + public Result users(AuthzTrans trans, Collection from, USERS to); + public Result userRoles(AuthzTrans trans, Collection from, USERROLES to); + public Result keys(Collection from); - public Result history(AuthzTrans trans, List history, final int sort); - - public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); - - /* - * A Memo Creator... Use to avoid creating superfluous Strings until needed. - */ - public static interface Memo { - public String get(); - } + public Result history(AuthzTrans trans, List history, final int sort); + + public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); + + /* + * A Memo Creator... Use to avoid creating superfluous Strings until needed. + */ + public static interface Memo { + public String get(); + } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java index f414a9fd..5f6f30e4 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java @@ -97,771 +97,771 @@ import aaf.v2_0.Users; import aaf.v2_0.Users.User; public class Mapper_2_0 implements Mapper { - private Question q; - - public Mapper_2_0(Question q) { - this.q = q; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.mapper.Mapper#ns(java.lang.Object, org.onap.aaf.auth.service.mapper.Mapper.Holder) - */ - @Override - public Result ns(AuthzTrans trans, Request base) { - NsRequest from = (NsRequest)base; - Namespace namespace = new Namespace(); - namespace.name = from.getName(); - namespace.admin = from.getAdmin(); - namespace.owner = from.getResponsible(); - namespace.description = from.getDescription(); - trans.checkpoint(namespace.name, Env.ALWAYS); - - NsType nt = NsType.fromString(from.getType()); - if(nt.equals(NsType.UNKNOWN)) { - String ns = namespace.name; - int count = 0; - for(int i=ns.indexOf('.'); - i>=0; - i=ns.indexOf('.',i+1)) { - ++count; - } - switch(count) { - case 0: nt = NsType.ROOT;break; - case 1: nt = NsType.COMPANY;break; - default: nt = NsType.APP; - } - } - namespace.type = nt.type; - - return Result.ok(namespace); - } - - @Override - public Result nss(AuthzTrans trans, Namespace from, Nss to) { - List nss = to.getNs(); - Ns ns = new Ns(); - ns.setName(from.name); - if(from.admin!=null)ns.getAdmin().addAll(from.admin); - if(from.owner!=null)ns.getResponsible().addAll(from.owner); - if(from.attrib!=null) { - for(Pair attrib : from.attrib) { - Ns.Attrib toAttrib = new Ns.Attrib(); - toAttrib.setKey(attrib.x); - toAttrib.setValue(attrib.y); - ns.getAttrib().add(toAttrib); - } - } - - ns.setDescription(from.description); - nss.add(ns); - return Result.ok(to); - } - - /** - * Note: Prevalidate if NS given is allowed to be seen before calling - */ - @Override - public Result nss(AuthzTrans trans, Collection from, Nss to) { - List nss = to.getNs(); - for(Namespace nd : from) { - Ns ns = new Ns(); - ns.setName(nd.name); - if(nd.admin!=null) { - ns.getAdmin().addAll(nd.admin); - } - if(nd.owner!=null) { - ns.getResponsible().addAll(nd.owner); - } - ns.setDescription(nd.description); - if(nd.attrib!=null) { - for(Pair attrib : nd.attrib) { - Ns.Attrib toAttrib = new Ns.Attrib(); - toAttrib.setKey(attrib.x); - toAttrib.setValue(attrib.y); - ns.getAttrib().add(toAttrib); - } - } - - nss.add(ns); - } - return Result.ok(to); - } - - @Override - public Result perms(AuthzTrans trans, List from, Perms to, boolean filter) { - List perms = to.getPerm(); - final boolean addNS = trans.requested(REQD_TYPE.ns); - TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); - try { - if(from!=null) { - for (PermDAO.Data data : from) { - if(!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK()) { - Perm perm = new Perm(); - perm.setType(data.fullType()); - perm.setInstance(data.instance); - perm.setAction(data.action); - perm.setDescription(data.description); - if(addNS) { - perm.setNs(data.ns); - } - for(String role : data.roles(false)) { - perm.getRoles().add(role); - } - perms.add(perm); - } - } - } - } finally { - tt.done(); - } - - tt = trans.start("Sort Perms", Env.SUB); - try { - Collections.sort(perms, new Comparator() { - @Override - public int compare(Perm perm1, Perm perm2) { - int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType()); - if (typeCompare == 0) { - int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance()); - if (instanceCompare == 0) { - return perm1.getAction().compareToIgnoreCase(perm2.getAction()); - } - return instanceCompare; - } - return typeCompare; - } - }); - } finally { - tt.done(); - } - return Result.ok(to); - } - - @Override - public Result perms(AuthzTrans trans, List from, Perms to, String[] nss, boolean filter) { - List perms = to.getPerm(); - TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); - try { - if(from!=null) { - boolean inNSS; - for (PermDAO.Data data : from) { - inNSS=false; - for(int i=0;!inNSS && i() { - @Override - public int compare(Perm perm1, Perm perm2) { - int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType()); - if (typeCompare == 0) { - int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance()); - if (instanceCompare == 0) { - return perm1.getAction().compareToIgnoreCase(perm2.getAction()); - } - return instanceCompare; - } - return typeCompare; - } - }); - } finally { - tt.done(); - } - return Result.ok(to); - } - - @Override - public Result> perms(AuthzTrans trans, Perms perms) { - List lpd = new ArrayList<>(); - for (Perm p : perms.getPerm()) { - Result nss = q.deriveNsSplit(trans, p.getType()); - PermDAO.Data pd = new PermDAO.Data(); - if(nss.isOK()) { - pd.ns=nss.value.ns; - pd.type = nss.value.name; - pd.instance = p.getInstance(); - pd.action = p.getAction(); - for (String role : p.getRoles()) { - pd.roles(true).add(role); - } - lpd.add(pd); - } else { - return Result.err(nss); - } - } - return Result.ok(lpd); - } - - - @Override - public Result permkey(AuthzTrans trans, Pkey from) { - return q.permFrom(trans, from.getType(),from.getInstance(),from.getAction()); - } - - @Override - public Result permFromRPRequest(AuthzTrans trans, Request req) { - RolePermRequest from = (RolePermRequest)req; - Pkey perm = from.getPerm(); - if(perm==null)return Result.err(Status.ERR_NotFound, "Permission not found"); - Result nss = q.deriveNsSplit(trans, perm.getType()); - PermDAO.Data pd = new PermDAO.Data(); - if(nss.isOK()) { - pd.ns=nss.value.ns; - pd.type = nss.value.name; - pd.instance = from.getPerm().getInstance(); - pd.action = from.getPerm().getAction(); - trans.checkpoint(pd.fullPerm(), Env.ALWAYS); - - String[] roles = {}; - - if (from.getRole() != null) { - roles = from.getRole().split(","); - } - for (String role : roles) { - pd.roles(true).add(role); - } - return Result.ok(pd); - } else { - return Result.err(nss); - } - } - - @Override - public Result roleFromRPRequest(AuthzTrans trans, Request req) { - RolePermRequest from = (RolePermRequest)req; - Result nss = q.deriveNsSplit(trans, from.getRole()); - RoleDAO.Data rd = new RoleDAO.Data(); - if(nss.isOK()) { - rd.ns = nss.value.ns; - rd.name = nss.value.name; - trans.checkpoint(rd.fullName(), Env.ALWAYS); - return Result.ok(rd); - } else { - return Result.err(nss); - } - } - - @Override - public Result perm(AuthzTrans trans, Request req) { - PermRequest from = (PermRequest)req; - Result nss = q.deriveNsSplit(trans, from.getType()); - PermDAO.Data pd = new PermDAO.Data(); - if(nss.isOK()) { - pd.ns=nss.value.ns; - pd.type = nss.value.name; - pd.instance = from.getInstance(); - pd.action = from.getAction(); - pd.description = from.getDescription(); - trans.checkpoint(pd.fullPerm(), Env.ALWAYS); - return Result.ok(pd); - } else { - return Result.err(nss); - } - } - - @Override - public Request ungrantRequest(AuthzTrans trans, String role, String type, String instance, String action) { - RolePermRequest rpr = new RolePermRequest(); - Pkey pkey = new Pkey(); - pkey.setType(type); - pkey.setInstance(instance); - pkey.setAction(action); - rpr.setPerm(pkey); - - rpr.setRole(role); - return rpr; - } - - @Override - public Result role(AuthzTrans trans, Request base) { - RoleRequest from = (RoleRequest)base; - Result nss = q.deriveNsSplit(trans, from.getName()); - if(nss.isOK()) { - RoleDAO.Data to = new RoleDAO.Data(); - to.ns = nss.value.ns; - to.name = nss.value.name; - to.description = from.getDescription(); - trans.checkpoint(to.fullName(), Env.ALWAYS); - - return Result.ok(to); - } else { - return Result.err(nss); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.mapper.Mapper#roles(java.util.List) - */ - @Override - public Result roles(AuthzTrans trans, List from, Roles to, boolean filter) { - final boolean needNS = trans.requested(REQD_TYPE.ns); - for(RoleDAO.Data frole : from) { - // Only Add Data to view if User is allowed to see this Role - if(!filter || q.mayUser(trans, trans.user(), frole,Access.read).isOK()) { - Role role = new Role(); - role.setName(frole.ns + '.' + frole.name); - role.setDescription(frole.description); - if(needNS) { - role.setNs(frole.ns); - } - for(String p : frole.perms(false)) { // can see any Perms in the Role he has permission for - Result rpa = PermDAO.Data.decodeToArray(trans,q,p); - if(rpa.notOK()) - return Result.err(rpa); - - String[] pa = rpa.value; - Pkey pKey = new Pkey(); - pKey.setType(pa[0]+'.'+pa[1]); - pKey.setInstance(pa[2]); - pKey.setAction(pa[3]); - role.getPerms().add(pKey); - } - to.getRole().add(role); - } - } - return Result.ok(to); - } - - /* - * (non-Javadoc) - * @see org.onap.aaf.auth.service.mapper.Mapper#users(java.util.Collection, java.lang.Object) - * - * Note: Prevalidate all data for permission to view - */ - @Override - public Result users(AuthzTrans trans, Collection from, Users to) { - List cu = to.getUser(); - for(UserRoleDAO.Data urd : from) { - User user = new User(); - user.setId(urd.user); - if(urd.expires!=null) { - user.setExpires(Chrono.timeStamp(urd.expires)); - } - cu.add(user); - } - return Result.ok(to); - } - - /* - * (non-Javadoc) - * @see org.onap.aaf.auth.service.mapper.Mapper#users(java.util.Collection, java.lang.Object) - * - * Note: Prevalidate all data for permission to view - */ - @Override - public Result userRoles(AuthzTrans trans, Collection from, UserRoles to) { - List cu = to.getUserRole(); - for(UserRoleDAO.Data urd : from) { - UserRole ur = new UserRole(); - ur.setUser(urd.user); - ur.setRole(urd.role); - ur.setExpires(Chrono.timeStamp(urd.expires)); - cu.add(ur); - } - return Result.ok(to); - } - - @Override - public Result userRole(AuthzTrans trans, Request base) { - try { - UserRoleRequest from = (UserRoleRequest)base; - - // Setup UserRoleData, either for immediate placement, or for futureIt i - UserRoleDAO.Data to = new UserRoleDAO.Data(); - if (from.getUser() != null) { - to.user = from.getUser(); - } - if (from.getRole() != null) { - to.role(trans,q,from.getRole()); - } - to.expires = getExpires(trans.org(),Expiration.UserInRole,base,from.getUser()); - trans.checkpoint(to.toString(), Env.ALWAYS); - - return Result.ok(to); - } catch (Exception t) { - return Result.err(Status.ERR_BadData,t.getMessage()); - } - } - - @Override - public Result cred(AuthzTrans trans, Request base, boolean requiresPass) { - CredRequest from = (CredRequest)base; - CredDAO.Data to = new CredDAO.Data(); - to.id=from.getId(); - to.ns = Question.domain2ns(to.id); - String passwd = from.getPassword(); - if(requiresPass) { - String ok = trans.org().isValidPassword(trans, to.id,passwd); - if(ok.length()>0) { - return Result.err(Status.ERR_BadData,ok); - } - } else { - to.type=0; - } - if(passwd != null) { - to.cred = ByteBuffer.wrap(passwd.getBytes()); - to.type = CredDAO.RAW; - } else { - to.type = 0; - } - - // Note: Ensure requested EndDate created will match Organization Password Rules - // P.S. Do not apply TempPassword rule here. Do that when you know you are doing a Create/Reset (see Service) - to.expires = getExpires(trans.org(),Expiration.Password,base,from.getId()); - trans.checkpoint(to.id, Env.ALWAYS); - - return Result.ok(to); - } - - @Override - public Result cred(List from, Users to) { - List cu = to.getUser(); - for(CredDAO.Data cred : from) { - User user = new User(); - user.setId(cred.id); - user.setExpires(Chrono.timeStamp(cred.expires)); - user.setType(cred.type); - cu.add(user); - } - return Result.ok(to); - } - - @Override - public Result cert(List from, Certs to) { - List lc = to.getCert(); - for(CertDAO.Data fcred : from) { - Cert cert = new Cert(); - cert.setId(fcred.id); - cert.setX500(fcred.x500); - /**TODO - change Interface - * @deprecated */ - cert.setFingerprint(fcred.serial.toByteArray()); - lc.add(cert); - } - return Result.ok(to); - } - - /** - * Analyze whether Requests should be acted on now, or in the future, based on Start Date, and whether the requester - * is allowed to change this value directly - * - * Returning Result.OK means it should be done in the future. - * Returning Result.ACC_Now means to act on table change now. - */ - @Override - public Result future(AuthzTrans trans, String table, Request from, - Bytification content, boolean enableApproval, Memo memo, MayChange mc) { - Result rMayChange; - boolean needsAppr = enableApproval?trans.requested(REQD_TYPE.future):false; - if(!needsAppr && (needsAppr = (rMayChange=mc.mayChange()).notOK())) { - if(enableApproval) { - if(!trans.requested(AuthzTrans.REQD_TYPE.future)) { - return Result.err(rMayChange); - } - } else { - return Result.err(rMayChange); - } - } - GregorianCalendar now = new GregorianCalendar(); - GregorianCalendar start = from.getStart()==null?now:from.getStart().toGregorianCalendar(); - - GregorianCalendar expires = trans.org().expiration(start, Expiration.Future); - XMLGregorianCalendar xgc; - if((xgc=from.getEnd())!=null) { - GregorianCalendar fgc = xgc.toGregorianCalendar(); - expires = expires.before(fgc)?expires:fgc; // Min of desired expiration, and Org expiration - } - - //TODO needs two answers from this. What's the NSS, and may Change. - FutureDAO.Data fto; - if(start.after(now) || needsAppr ) { - //String user = trans.user(); - fto = new FutureDAO.Data(); - fto.target=table; - fto.memo = memo.get(); - fto.start = start.getTime(); - fto.expires = expires.getTime(); - if(needsAppr) { // Need to add Approvers... - /* - Result rslt = mc.getNsd(); - if(rslt.notOKorIsEmpty())return Result.err(rslt); - appr.addAll(mc.getNsd().value.responsible); - try { - //Note from 2013 Is this getting Approvers for user only? What about Delegates? - // 3/25/2014. Approvers are set by Corporate policy. We don't have to worry here about what that means. - // It is important to get Delegates, if necessary, at notification time - // If we add delegates now, it will get all confused as to who is actually responsible. - for(Organization.User ou : org.getApprovers(trans, user)) { - appr.add(ou.email); - } - } catch (Exception e) { - return Result.err(Status.ERR_Policy,org.getName() + " did not respond with Approvers: " + e.getLocalizedMessage()); - } - */ - } - try { - fto.construct = content.bytify(); - } catch (Exception e) { - return Result.err(Status.ERR_BadData,"Data cannot be saved for Future."); - } - } else { - return Result.err(Status.ACC_Now, "Make Data changes now."); - } - return Result.ok(fto); - } - - - /* (non-Javadoc) - * @see org.onap.aaf.auth.service.mapper.Mapper#history(java.util.List) - */ - @Override - public Result history(AuthzTrans trans, List history, final int sort) { - History hist = new History(); - List items = hist.getItem(); - for(HistoryDAO.Data data : history) { - History.Item item = new History.Item(); - item.setYYYYMM(Integer.toString(data.yr_mon)); - Date date = Chrono.uuidToDate(data.id); - item.setTimestamp(Chrono.timeStamp(date)); - item.setAction(data.action); - item.setMemo(data.memo); - item.setSubject(data.subject); - item.setTarget(data.target); - item.setUser(data.user); - items.add(item); - } - - if(sort != 0) { - TimeTaken tt = trans.start("Sort ", Env.SUB); - try { - java.util.Collections.sort(items, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return sort*(o1.getTimestamp().compare(o2.getTimestamp())); - } - }); - } finally { - tt.done(); - } - } - return Result.ok(hist); - } - - @Override - public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { - Error err = new Error(); - err.setMessageId(msgID); - // AT&T Restful Error Format requires numbers "%" placements - err.setText(Vars.convert(holder, text, var)); - for(String s : var) { - err.getVariables().add(s); - } - return err; - } - - @Override - public Class getClass(API api) { - switch(api) { - case NSS: return Nss.class; - case NS_REQ: return NsRequest.class; - case PERMS: return Perms.class; - case PERM_KEY: return PermKey.class; - case ROLES: return Roles.class; - case ROLE: return Role.class; - case USERS: return Users.class; - case DELGS: return Delgs.class; - case CERTS: return Certs.class; - case DELG_REQ: return DelgRequest.class; - case PERM_REQ: return PermRequest.class; - case ROLE_REQ: return RoleRequest.class; - case CRED_REQ: return CredRequest.class; - case USER_ROLE_REQ: return UserRoleRequest.class; - case USER_ROLES: return UserRoles.class; - case ROLE_PERM_REQ: return RolePermRequest.class; - case APPROVALS: return Approvals.class; - case KEYS: return Keys.class; - case HISTORY: return History.class; -// case MODEL: return Model.class; - case ERROR: return Error.class; - case API: return Api.class; - case VOID: return Void.class; - } - return null; - } - - @SuppressWarnings("unchecked") - @Override - public A newInstance(API api) { - switch(api) { - case NS_REQ: return (A) new NsRequest(); - case NSS: return (A) new Nss(); - case PERMS: return (A)new Perms(); - case PERM_KEY: return (A)new PermKey(); - case ROLES: return (A)new Roles(); - case ROLE: return (A)new Role(); - case USERS: return (A)new Users(); - case DELGS: return (A)new Delgs(); - case CERTS: return (A)new Certs(); - case PERM_REQ: return (A)new PermRequest(); - case CRED_REQ: return (A)new CredRequest(); - case ROLE_REQ: return (A)new RoleRequest(); - case USER_ROLE_REQ: return (A)new UserRoleRequest(); - case USER_ROLES: return (A)new UserRoles(); - case ROLE_PERM_REQ: return (A)new RolePermRequest(); - case HISTORY: return (A)new History(); - case KEYS: return (A)new Keys(); - //case MODEL: return (A)new Model(); - case ERROR: return (A)new Error(); - case API: return (A)new Api(); - case VOID: return null; - - case APPROVALS: return (A) new Approvals(); - case DELG_REQ: return (A) new DelgRequest(); - } - return null; - } - - @SuppressWarnings("unchecked") - /** - * Get Typed Marshaler as they are defined - * - * @param api - * @return - */ - public Marshal getMarshal(API api) { - switch(api) { - case CERTS: return (Marshal) new CertsMarshal(); - default: - return null; - } - } - - @Override - public Result approvals(List lAppr) { - Approvals apprs = new Approvals(); - List lappr = apprs.getApprovals(); - Approval a; - for(ApprovalDAO.Data appr : lAppr) { - a = new Approval(); - a.setId(appr.id.toString()); - if(appr.ticket==null) { - a.setTicket(null); - } else { - a.setTicket(appr.ticket.toString()); - } - a.setUser(appr.user); - a.setApprover(appr.approver); - a.setType(appr.type); - a.setStatus(appr.status); - a.setMemo(appr.memo); - a.setOperation(appr.operation); - a.setUpdated(Chrono.timeStamp(appr.updated)); - lappr.add(a); - } - return Result.ok(apprs); - } - - @Override - public Result> approvals(Approvals apprs) { - List lappr = new ArrayList<>(); - for(Approval a : apprs.getApprovals()) { - ApprovalDAO.Data ad = new ApprovalDAO.Data(); - String str = a.getId(); - if(str!=null)ad.id=UUID.fromString(str); - str = a.getTicket(); - if(str!=null)ad.ticket=UUID.fromString(str); - ad.user=a.getUser(); - ad.approver=a.getApprover(); - ad.type=a.getType(); - ad.status=a.getStatus(); - ad.operation=a.getOperation(); - ad.memo=a.getMemo(); - - XMLGregorianCalendar xgc = a.getUpdated(); - if(xgc!=null)ad.updated=xgc.toGregorianCalendar().getTime(); - lappr.add(ad); - } - return Result.ok(lappr); - } - - @Override - public Result delegate(List lDelg) { - Delgs delgs = new Delgs(); - List ldelg = delgs.getDelgs(); - Delg d; - for(DelegateDAO.Data del: lDelg) { - d = new Delg(); - d.setUser(del.user); - d.setDelegate(del.delegate); - if(del.expires!=null)d.setExpires(Chrono.timeStamp(del.expires)); - ldelg.add(d); - } - return Result.ok(delgs); - } - - @Override - public Result delegate(AuthzTrans trans, Request base) { - try { - DelgRequest from = (DelgRequest)base; - DelegateDAO.Data to = new DelegateDAO.Data(); - String user = from.getUser(); - to.user = user; - String delegate = from.getDelegate(); - to.delegate = delegate; - to.expires = getExpires(trans.org(),Expiration.UserDelegate,base,from.getUser()); - trans.checkpoint(to.user+"=>"+to.delegate, Env.ALWAYS); - - return Result.ok(to); - } catch (Exception t) { - return Result.err(Status.ERR_BadData,t.getMessage()); - } - } - - /* - * We want "Expired" dates to start at a specified time set by the Organization, and consistent wherever - * the date is created from. - */ - private Date getExpires(Organization org, Expiration exp, Request base, String id) { - XMLGregorianCalendar end = base.getEnd(); - GregorianCalendar gc = end==null?new GregorianCalendar():end.toGregorianCalendar(); - GregorianCalendar orggc; - orggc = org.expiration(gc,exp,id); - - // We'll choose the lesser of dates to ensure Policy Compliance... - - GregorianCalendar endgc = end==null||gc.after(orggc)?orggc:gc; - // Allow the Organization to determine when official "day Start" begins, Specifically when to consider something Expired. - endgc = Chrono.firstMomentOfDay(endgc); - endgc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay()); - return endgc.getTime(); - } - - - @Override - public Result keys(Collection from) { - Keys keys = new Keys(); - keys.getKey().addAll(from); - return Result.ok(keys).emptyList(from.isEmpty()); - } + private Question q; + + public Mapper_2_0(Question q) { + this.q = q; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#ns(java.lang.Object, org.onap.aaf.auth.service.mapper.Mapper.Holder) + */ + @Override + public Result ns(AuthzTrans trans, Request base) { + NsRequest from = (NsRequest)base; + Namespace namespace = new Namespace(); + namespace.name = from.getName(); + namespace.admin = from.getAdmin(); + namespace.owner = from.getResponsible(); + namespace.description = from.getDescription(); + trans.checkpoint(namespace.name, Env.ALWAYS); + + NsType nt = NsType.fromString(from.getType()); + if(nt.equals(NsType.UNKNOWN)) { + String ns = namespace.name; + int count = 0; + for(int i=ns.indexOf('.'); + i>=0; + i=ns.indexOf('.',i+1)) { + ++count; + } + switch(count) { + case 0: nt = NsType.ROOT;break; + case 1: nt = NsType.COMPANY;break; + default: nt = NsType.APP; + } + } + namespace.type = nt.type; + + return Result.ok(namespace); + } + + @Override + public Result nss(AuthzTrans trans, Namespace from, Nss to) { + List nss = to.getNs(); + Ns ns = new Ns(); + ns.setName(from.name); + if(from.admin!=null)ns.getAdmin().addAll(from.admin); + if(from.owner!=null)ns.getResponsible().addAll(from.owner); + if(from.attrib!=null) { + for(Pair attrib : from.attrib) { + Ns.Attrib toAttrib = new Ns.Attrib(); + toAttrib.setKey(attrib.x); + toAttrib.setValue(attrib.y); + ns.getAttrib().add(toAttrib); + } + } + + ns.setDescription(from.description); + nss.add(ns); + return Result.ok(to); + } + + /** + * Note: Prevalidate if NS given is allowed to be seen before calling + */ + @Override + public Result nss(AuthzTrans trans, Collection from, Nss to) { + List nss = to.getNs(); + for(Namespace nd : from) { + Ns ns = new Ns(); + ns.setName(nd.name); + if(nd.admin!=null) { + ns.getAdmin().addAll(nd.admin); + } + if(nd.owner!=null) { + ns.getResponsible().addAll(nd.owner); + } + ns.setDescription(nd.description); + if(nd.attrib!=null) { + for(Pair attrib : nd.attrib) { + Ns.Attrib toAttrib = new Ns.Attrib(); + toAttrib.setKey(attrib.x); + toAttrib.setValue(attrib.y); + ns.getAttrib().add(toAttrib); + } + } + + nss.add(ns); + } + return Result.ok(to); + } + + @Override + public Result perms(AuthzTrans trans, List from, Perms to, boolean filter) { + List perms = to.getPerm(); + final boolean addNS = trans.requested(REQD_TYPE.ns); + TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); + try { + if(from!=null) { + for (PermDAO.Data data : from) { + if(!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK()) { + Perm perm = new Perm(); + perm.setType(data.fullType()); + perm.setInstance(data.instance); + perm.setAction(data.action); + perm.setDescription(data.description); + if(addNS) { + perm.setNs(data.ns); + } + for(String role : data.roles(false)) { + perm.getRoles().add(role); + } + perms.add(perm); + } + } + } + } finally { + tt.done(); + } + + tt = trans.start("Sort Perms", Env.SUB); + try { + Collections.sort(perms, new Comparator() { + @Override + public int compare(Perm perm1, Perm perm2) { + int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType()); + if (typeCompare == 0) { + int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance()); + if (instanceCompare == 0) { + return perm1.getAction().compareToIgnoreCase(perm2.getAction()); + } + return instanceCompare; + } + return typeCompare; + } + }); + } finally { + tt.done(); + } + return Result.ok(to); + } + + @Override + public Result perms(AuthzTrans trans, List from, Perms to, String[] nss, boolean filter) { + List perms = to.getPerm(); + TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); + try { + if(from!=null) { + boolean inNSS; + for (PermDAO.Data data : from) { + inNSS=false; + for(int i=0;!inNSS && i() { + @Override + public int compare(Perm perm1, Perm perm2) { + int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType()); + if (typeCompare == 0) { + int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance()); + if (instanceCompare == 0) { + return perm1.getAction().compareToIgnoreCase(perm2.getAction()); + } + return instanceCompare; + } + return typeCompare; + } + }); + } finally { + tt.done(); + } + return Result.ok(to); + } + + @Override + public Result> perms(AuthzTrans trans, Perms perms) { + List lpd = new ArrayList<>(); + for (Perm p : perms.getPerm()) { + Result nss = q.deriveNsSplit(trans, p.getType()); + PermDAO.Data pd = new PermDAO.Data(); + if(nss.isOK()) { + pd.ns=nss.value.ns; + pd.type = nss.value.name; + pd.instance = p.getInstance(); + pd.action = p.getAction(); + for (String role : p.getRoles()) { + pd.roles(true).add(role); + } + lpd.add(pd); + } else { + return Result.err(nss); + } + } + return Result.ok(lpd); + } + + + @Override + public Result permkey(AuthzTrans trans, Pkey from) { + return q.permFrom(trans, from.getType(),from.getInstance(),from.getAction()); + } + + @Override + public Result permFromRPRequest(AuthzTrans trans, Request req) { + RolePermRequest from = (RolePermRequest)req; + Pkey perm = from.getPerm(); + if(perm==null)return Result.err(Status.ERR_NotFound, "Permission not found"); + Result nss = q.deriveNsSplit(trans, perm.getType()); + PermDAO.Data pd = new PermDAO.Data(); + if(nss.isOK()) { + pd.ns=nss.value.ns; + pd.type = nss.value.name; + pd.instance = from.getPerm().getInstance(); + pd.action = from.getPerm().getAction(); + trans.checkpoint(pd.fullPerm(), Env.ALWAYS); + + String[] roles = {}; + + if (from.getRole() != null) { + roles = from.getRole().split(","); + } + for (String role : roles) { + pd.roles(true).add(role); + } + return Result.ok(pd); + } else { + return Result.err(nss); + } + } + + @Override + public Result roleFromRPRequest(AuthzTrans trans, Request req) { + RolePermRequest from = (RolePermRequest)req; + Result nss = q.deriveNsSplit(trans, from.getRole()); + RoleDAO.Data rd = new RoleDAO.Data(); + if(nss.isOK()) { + rd.ns = nss.value.ns; + rd.name = nss.value.name; + trans.checkpoint(rd.fullName(), Env.ALWAYS); + return Result.ok(rd); + } else { + return Result.err(nss); + } + } + + @Override + public Result perm(AuthzTrans trans, Request req) { + PermRequest from = (PermRequest)req; + Result nss = q.deriveNsSplit(trans, from.getType()); + PermDAO.Data pd = new PermDAO.Data(); + if(nss.isOK()) { + pd.ns=nss.value.ns; + pd.type = nss.value.name; + pd.instance = from.getInstance(); + pd.action = from.getAction(); + pd.description = from.getDescription(); + trans.checkpoint(pd.fullPerm(), Env.ALWAYS); + return Result.ok(pd); + } else { + return Result.err(nss); + } + } + + @Override + public Request ungrantRequest(AuthzTrans trans, String role, String type, String instance, String action) { + RolePermRequest rpr = new RolePermRequest(); + Pkey pkey = new Pkey(); + pkey.setType(type); + pkey.setInstance(instance); + pkey.setAction(action); + rpr.setPerm(pkey); + + rpr.setRole(role); + return rpr; + } + + @Override + public Result role(AuthzTrans trans, Request base) { + RoleRequest from = (RoleRequest)base; + Result nss = q.deriveNsSplit(trans, from.getName()); + if(nss.isOK()) { + RoleDAO.Data to = new RoleDAO.Data(); + to.ns = nss.value.ns; + to.name = nss.value.name; + to.description = from.getDescription(); + trans.checkpoint(to.fullName(), Env.ALWAYS); + + return Result.ok(to); + } else { + return Result.err(nss); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#roles(java.util.List) + */ + @Override + public Result roles(AuthzTrans trans, List from, Roles to, boolean filter) { + final boolean needNS = trans.requested(REQD_TYPE.ns); + for(RoleDAO.Data frole : from) { + // Only Add Data to view if User is allowed to see this Role + if(!filter || q.mayUser(trans, trans.user(), frole,Access.read).isOK()) { + Role role = new Role(); + role.setName(frole.ns + '.' + frole.name); + role.setDescription(frole.description); + if(needNS) { + role.setNs(frole.ns); + } + for(String p : frole.perms(false)) { // can see any Perms in the Role he has permission for + Result rpa = PermDAO.Data.decodeToArray(trans,q,p); + if(rpa.notOK()) + return Result.err(rpa); + + String[] pa = rpa.value; + Pkey pKey = new Pkey(); + pKey.setType(pa[0]+'.'+pa[1]); + pKey.setInstance(pa[2]); + pKey.setAction(pa[3]); + role.getPerms().add(pKey); + } + to.getRole().add(role); + } + } + return Result.ok(to); + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#users(java.util.Collection, java.lang.Object) + * + * Note: Prevalidate all data for permission to view + */ + @Override + public Result users(AuthzTrans trans, Collection from, Users to) { + List cu = to.getUser(); + for(UserRoleDAO.Data urd : from) { + User user = new User(); + user.setId(urd.user); + if(urd.expires!=null) { + user.setExpires(Chrono.timeStamp(urd.expires)); + } + cu.add(user); + } + return Result.ok(to); + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#users(java.util.Collection, java.lang.Object) + * + * Note: Prevalidate all data for permission to view + */ + @Override + public Result userRoles(AuthzTrans trans, Collection from, UserRoles to) { + List cu = to.getUserRole(); + for(UserRoleDAO.Data urd : from) { + UserRole ur = new UserRole(); + ur.setUser(urd.user); + ur.setRole(urd.role); + ur.setExpires(Chrono.timeStamp(urd.expires)); + cu.add(ur); + } + return Result.ok(to); + } + + @Override + public Result userRole(AuthzTrans trans, Request base) { + try { + UserRoleRequest from = (UserRoleRequest)base; + + // Setup UserRoleData, either for immediate placement, or for futureIt i + UserRoleDAO.Data to = new UserRoleDAO.Data(); + if (from.getUser() != null) { + to.user = from.getUser(); + } + if (from.getRole() != null) { + to.role(trans,q,from.getRole()); + } + to.expires = getExpires(trans.org(),Expiration.UserInRole,base,from.getUser()); + trans.checkpoint(to.toString(), Env.ALWAYS); + + return Result.ok(to); + } catch (Exception t) { + return Result.err(Status.ERR_BadData,t.getMessage()); + } + } + + @Override + public Result cred(AuthzTrans trans, Request base, boolean requiresPass) { + CredRequest from = (CredRequest)base; + CredDAO.Data to = new CredDAO.Data(); + to.id=from.getId(); + to.ns = Question.domain2ns(to.id); + String passwd = from.getPassword(); + if(requiresPass) { + String ok = trans.org().isValidPassword(trans, to.id,passwd); + if(ok.length()>0) { + return Result.err(Status.ERR_BadData,ok); + } + } else { + to.type=0; + } + if(passwd != null) { + to.cred = ByteBuffer.wrap(passwd.getBytes()); + to.type = CredDAO.RAW; + } else { + to.type = 0; + } + + // Note: Ensure requested EndDate created will match Organization Password Rules + // P.S. Do not apply TempPassword rule here. Do that when you know you are doing a Create/Reset (see Service) + to.expires = getExpires(trans.org(),Expiration.Password,base,from.getId()); + trans.checkpoint(to.id, Env.ALWAYS); + + return Result.ok(to); + } + + @Override + public Result cred(List from, Users to) { + List cu = to.getUser(); + for(CredDAO.Data cred : from) { + User user = new User(); + user.setId(cred.id); + user.setExpires(Chrono.timeStamp(cred.expires)); + user.setType(cred.type); + cu.add(user); + } + return Result.ok(to); + } + + @Override + public Result cert(List from, Certs to) { + List lc = to.getCert(); + for(CertDAO.Data fcred : from) { + Cert cert = new Cert(); + cert.setId(fcred.id); + cert.setX500(fcred.x500); + /**TODO - change Interface + * @deprecated */ + cert.setFingerprint(fcred.serial.toByteArray()); + lc.add(cert); + } + return Result.ok(to); + } + + /** + * Analyze whether Requests should be acted on now, or in the future, based on Start Date, and whether the requester + * is allowed to change this value directly + * + * Returning Result.OK means it should be done in the future. + * Returning Result.ACC_Now means to act on table change now. + */ + @Override + public Result future(AuthzTrans trans, String table, Request from, + Bytification content, boolean enableApproval, Memo memo, MayChange mc) { + Result rMayChange; + boolean needsAppr = enableApproval?trans.requested(REQD_TYPE.future):false; + if(!needsAppr && (needsAppr = (rMayChange=mc.mayChange()).notOK())) { + if(enableApproval) { + if(!trans.requested(AuthzTrans.REQD_TYPE.future)) { + return Result.err(rMayChange); + } + } else { + return Result.err(rMayChange); + } + } + GregorianCalendar now = new GregorianCalendar(); + GregorianCalendar start = from.getStart()==null?now:from.getStart().toGregorianCalendar(); + + GregorianCalendar expires = trans.org().expiration(start, Expiration.Future); + XMLGregorianCalendar xgc; + if((xgc=from.getEnd())!=null) { + GregorianCalendar fgc = xgc.toGregorianCalendar(); + expires = expires.before(fgc)?expires:fgc; // Min of desired expiration, and Org expiration + } + + //TODO needs two answers from this. What's the NSS, and may Change. + FutureDAO.Data fto; + if(start.after(now) || needsAppr ) { + //String user = trans.user(); + fto = new FutureDAO.Data(); + fto.target=table; + fto.memo = memo.get(); + fto.start = start.getTime(); + fto.expires = expires.getTime(); + if(needsAppr) { // Need to add Approvers... + /* + Result rslt = mc.getNsd(); + if(rslt.notOKorIsEmpty())return Result.err(rslt); + appr.addAll(mc.getNsd().value.responsible); + try { + //Note from 2013 Is this getting Approvers for user only? What about Delegates? + // 3/25/2014. Approvers are set by Corporate policy. We don't have to worry here about what that means. + // It is important to get Delegates, if necessary, at notification time + // If we add delegates now, it will get all confused as to who is actually responsible. + for(Organization.User ou : org.getApprovers(trans, user)) { + appr.add(ou.email); + } + } catch (Exception e) { + return Result.err(Status.ERR_Policy,org.getName() + " did not respond with Approvers: " + e.getLocalizedMessage()); + } + */ + } + try { + fto.construct = content.bytify(); + } catch (Exception e) { + return Result.err(Status.ERR_BadData,"Data cannot be saved for Future."); + } + } else { + return Result.err(Status.ACC_Now, "Make Data changes now."); + } + return Result.ok(fto); + } + + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#history(java.util.List) + */ + @Override + public Result history(AuthzTrans trans, List history, final int sort) { + History hist = new History(); + List items = hist.getItem(); + for(HistoryDAO.Data data : history) { + History.Item item = new History.Item(); + item.setYYYYMM(Integer.toString(data.yr_mon)); + Date date = Chrono.uuidToDate(data.id); + item.setTimestamp(Chrono.timeStamp(date)); + item.setAction(data.action); + item.setMemo(data.memo); + item.setSubject(data.subject); + item.setTarget(data.target); + item.setUser(data.user); + items.add(item); + } + + if(sort != 0) { + TimeTaken tt = trans.start("Sort ", Env.SUB); + try { + java.util.Collections.sort(items, new Comparator() { + @Override + public int compare(Item o1, Item o2) { + return sort*(o1.getTimestamp().compare(o2.getTimestamp())); + } + }); + } finally { + tt.done(); + } + } + return Result.ok(hist); + } + + @Override + public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { + Error err = new Error(); + err.setMessageId(msgID); + // AT&T Restful Error Format requires numbers "%" placements + err.setText(Vars.convert(holder, text, var)); + for(String s : var) { + err.getVariables().add(s); + } + return err; + } + + @Override + public Class getClass(API api) { + switch(api) { + case NSS: return Nss.class; + case NS_REQ: return NsRequest.class; + case PERMS: return Perms.class; + case PERM_KEY: return PermKey.class; + case ROLES: return Roles.class; + case ROLE: return Role.class; + case USERS: return Users.class; + case DELGS: return Delgs.class; + case CERTS: return Certs.class; + case DELG_REQ: return DelgRequest.class; + case PERM_REQ: return PermRequest.class; + case ROLE_REQ: return RoleRequest.class; + case CRED_REQ: return CredRequest.class; + case USER_ROLE_REQ: return UserRoleRequest.class; + case USER_ROLES: return UserRoles.class; + case ROLE_PERM_REQ: return RolePermRequest.class; + case APPROVALS: return Approvals.class; + case KEYS: return Keys.class; + case HISTORY: return History.class; +// case MODEL: return Model.class; + case ERROR: return Error.class; + case API: return Api.class; + case VOID: return Void.class; + } + return null; + } + + @SuppressWarnings("unchecked") + @Override + public A newInstance(API api) { + switch(api) { + case NS_REQ: return (A) new NsRequest(); + case NSS: return (A) new Nss(); + case PERMS: return (A)new Perms(); + case PERM_KEY: return (A)new PermKey(); + case ROLES: return (A)new Roles(); + case ROLE: return (A)new Role(); + case USERS: return (A)new Users(); + case DELGS: return (A)new Delgs(); + case CERTS: return (A)new Certs(); + case PERM_REQ: return (A)new PermRequest(); + case CRED_REQ: return (A)new CredRequest(); + case ROLE_REQ: return (A)new RoleRequest(); + case USER_ROLE_REQ: return (A)new UserRoleRequest(); + case USER_ROLES: return (A)new UserRoles(); + case ROLE_PERM_REQ: return (A)new RolePermRequest(); + case HISTORY: return (A)new History(); + case KEYS: return (A)new Keys(); + //case MODEL: return (A)new Model(); + case ERROR: return (A)new Error(); + case API: return (A)new Api(); + case VOID: return null; + + case APPROVALS: return (A) new Approvals(); + case DELG_REQ: return (A) new DelgRequest(); + } + return null; + } + + @SuppressWarnings("unchecked") + /** + * Get Typed Marshaler as they are defined + * + * @param api + * @return + */ + public Marshal getMarshal(API api) { + switch(api) { + case CERTS: return (Marshal) new CertsMarshal(); + default: + return null; + } + } + + @Override + public Result approvals(List lAppr) { + Approvals apprs = new Approvals(); + List lappr = apprs.getApprovals(); + Approval a; + for(ApprovalDAO.Data appr : lAppr) { + a = new Approval(); + a.setId(appr.id.toString()); + if(appr.ticket==null) { + a.setTicket(null); + } else { + a.setTicket(appr.ticket.toString()); + } + a.setUser(appr.user); + a.setApprover(appr.approver); + a.setType(appr.type); + a.setStatus(appr.status); + a.setMemo(appr.memo); + a.setOperation(appr.operation); + a.setUpdated(Chrono.timeStamp(appr.updated)); + lappr.add(a); + } + return Result.ok(apprs); + } + + @Override + public Result> approvals(Approvals apprs) { + List lappr = new ArrayList<>(); + for(Approval a : apprs.getApprovals()) { + ApprovalDAO.Data ad = new ApprovalDAO.Data(); + String str = a.getId(); + if(str!=null)ad.id=UUID.fromString(str); + str = a.getTicket(); + if(str!=null)ad.ticket=UUID.fromString(str); + ad.user=a.getUser(); + ad.approver=a.getApprover(); + ad.type=a.getType(); + ad.status=a.getStatus(); + ad.operation=a.getOperation(); + ad.memo=a.getMemo(); + + XMLGregorianCalendar xgc = a.getUpdated(); + if(xgc!=null)ad.updated=xgc.toGregorianCalendar().getTime(); + lappr.add(ad); + } + return Result.ok(lappr); + } + + @Override + public Result delegate(List lDelg) { + Delgs delgs = new Delgs(); + List ldelg = delgs.getDelgs(); + Delg d; + for(DelegateDAO.Data del: lDelg) { + d = new Delg(); + d.setUser(del.user); + d.setDelegate(del.delegate); + if(del.expires!=null)d.setExpires(Chrono.timeStamp(del.expires)); + ldelg.add(d); + } + return Result.ok(delgs); + } + + @Override + public Result delegate(AuthzTrans trans, Request base) { + try { + DelgRequest from = (DelgRequest)base; + DelegateDAO.Data to = new DelegateDAO.Data(); + String user = from.getUser(); + to.user = user; + String delegate = from.getDelegate(); + to.delegate = delegate; + to.expires = getExpires(trans.org(),Expiration.UserDelegate,base,from.getUser()); + trans.checkpoint(to.user+"=>"+to.delegate, Env.ALWAYS); + + return Result.ok(to); + } catch (Exception t) { + return Result.err(Status.ERR_BadData,t.getMessage()); + } + } + + /* + * We want "Expired" dates to start at a specified time set by the Organization, and consistent wherever + * the date is created from. + */ + private Date getExpires(Organization org, Expiration exp, Request base, String id) { + XMLGregorianCalendar end = base.getEnd(); + GregorianCalendar gc = end==null?new GregorianCalendar():end.toGregorianCalendar(); + GregorianCalendar orggc; + orggc = org.expiration(gc,exp,id); + + // We'll choose the lesser of dates to ensure Policy Compliance... + + GregorianCalendar endgc = end==null||gc.after(orggc)?orggc:gc; + // Allow the Organization to determine when official "day Start" begins, Specifically when to consider something Expired. + endgc = Chrono.firstMomentOfDay(endgc); + endgc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay()); + return endgc.getTime(); + } + + + @Override + public Result keys(Collection from) { + Keys keys = new Keys(); + keys.getKey().addAll(from); + return Result.ok(keys).emptyList(from.isEmpty()); + } } \ No newline at end of file diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java index 80b06a51..4a088abc 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java @@ -43,209 +43,209 @@ import org.onap.aaf.auth.validation.Validator; * */ public class ServiceValidator extends Validator { - public ServiceValidator perm(Result rpd) { - if(rpd.notOK()) { - msg(rpd.details); - } else { - perm(rpd.value); - } - return this; - } - - - public ServiceValidator perm(PermDAO.Data pd) { - if(pd==null) { - msg("Perm Data is null."); - } else { - ns(pd.ns); - permType(pd.type,pd.ns); - permInstance(pd.instance); - permAction(pd.action); - if(pd.roles!=null) { - for(String role : pd.roles) { - role(role); - } - } - if(pd.roles!=null) { - for(String r : pd.roles) { - role(r); - } - } - description("Perm",pd.description); - } - return this; - } - - public ServiceValidator role(Result rrd) { - if(rrd.notOK()) { - msg(rrd.details); - } else { - role(rrd.value); - } - return this; - } - - public ServiceValidator role(RoleDAO.Data pd) { - if(pd==null) { - msg("Role Data is null."); - } else { - ns(pd.ns); - role(pd.name); - if(pd.perms!=null) { - for(String perm : pd.perms) { - String[] ps = perm.split("\\|"); - if(ps.length!=3) { - msg("Perm [" + perm + "] in Role [" + pd.fullName() + "] is not correctly separated with '|'"); - } else { - permType(ps[0],null); - permInstance(ps[1]); - permAction(ps[2]); - } - } - } - description("Role",pd.description); - } - return this; - } - - public ServiceValidator delegate(Organization org, Result rdd) { - if(rdd.notOK()) { - msg(rdd.details); - } else { - delegate(org, rdd.value); - } - return this; - } - - public ServiceValidator delegate(Organization org, DelegateDAO.Data dd) { - if(dd==null) { - msg("Delegate Data is null."); - } else { - user(org,dd.user); - user(org,dd.delegate); - } - return this; - } - - - public ServiceValidator cred(AuthzTrans trans, Organization org, Result rcd, boolean isNew) { - if(rcd.notOK()) { - msg(rcd.details); - } else { - cred(trans, org,rcd.value,isNew); - } - return this; - } - - public ServiceValidator cred(AuthzTrans trans, Organization org, CredDAO.Data cd, boolean isNew) { - if(cd==null) { - msg("Cred Data is null."); - } else { - if(!org.isValidCred(trans, cd.id)) { - msg("ID [" + cd.id + "] is invalid in " + org.getName()); - } - String str = cd.id; - int idx = str.indexOf('@'); - if(idx>0) { - str = str.substring(0,idx); - } - - if(org.supportsRealm(cd.id)) { - String resp = org.isValidID(trans, str); - if(isNew && (resp!=null && resp.length()>0)) { - msg(cd.id,str); - } - } - - if(cd.type==null) { - msg("Credential Type must be set"); - } else { - switch(cd.type) { - case CredDAO.BASIC_AUTH_SHA256: - // ok - break; - default: - msg("Credential Type [",Integer.toString(cd.type),"] is invalid"); - } - } - } - return this; - } - - - public ServiceValidator user(Organization org, String user) { - if(nob(user,ID_CHARS)) { - msg("User [",user,"] is invalid."); - } - return this; - } - - public ServiceValidator ns(Result nsd) { - notOK(nsd); - ns(nsd.value); - return this; - } - - public ServiceValidator ns(Namespace ns) { - ns(ns.name); - for(String s : ns.admin) { - if(nob(s,ID_CHARS)) { - msg("Admin [" + s + "] is invalid."); - } - - } - for(String s : ns.owner) { - if(nob(s,ID_CHARS)) { - msg("Responsible [" + s + "] is invalid."); - } - - } - - if(ns.attrib!=null) { - for(Pair at : ns.attrib) { - if(nob(at.x,NAME_CHARS)) { - msg("Attribute tag [" + at.x + "] is invalid."); - } - if(nob(at.x,NAME_CHARS)) { - msg("Attribute value [" + at.y + "] is invalid."); - } - } - } - - description("Namespace",ns.description); - return this; - } - - public ServiceValidator user_role(UserRoleDAO.Data urdd) { - if(urdd==null) { - msg("UserRole is null"); - } else { - role(urdd.role); - nullOrBlank("UserRole.ns",urdd.ns); - nullOrBlank("UserRole.rname",urdd.rname); - } - return this; - } - - public ServiceValidator nullOrBlank(PermDAO.Data pd) { - if(pd==null) { - msg("Permission is null"); - } else { - nullOrBlank("NS",pd.ns). - nullOrBlank("Type",pd.type). - nullOrBlank("Instance",pd.instance). - nullOrBlank("Action",pd.action); - } - return this; - } - - public ServiceValidator nullOrBlank(RoleDAO.Data rd) { - if(rd==null) { - msg("Role is null"); - } else { - nullOrBlank("NS",rd.ns). - nullOrBlank("Name",rd.name); - } - return this; - } + public ServiceValidator perm(Result rpd) { + if(rpd.notOK()) { + msg(rpd.details); + } else { + perm(rpd.value); + } + return this; + } + + + public ServiceValidator perm(PermDAO.Data pd) { + if(pd==null) { + msg("Perm Data is null."); + } else { + ns(pd.ns); + permType(pd.type,pd.ns); + permInstance(pd.instance); + permAction(pd.action); + if(pd.roles!=null) { + for(String role : pd.roles) { + role(role); + } + } + if(pd.roles!=null) { + for(String r : pd.roles) { + role(r); + } + } + description("Perm",pd.description); + } + return this; + } + + public ServiceValidator role(Result rrd) { + if(rrd.notOK()) { + msg(rrd.details); + } else { + role(rrd.value); + } + return this; + } + + public ServiceValidator role(RoleDAO.Data pd) { + if(pd==null) { + msg("Role Data is null."); + } else { + ns(pd.ns); + role(pd.name); + if(pd.perms!=null) { + for(String perm : pd.perms) { + String[] ps = perm.split("\\|"); + if(ps.length!=3) { + msg("Perm [" + perm + "] in Role [" + pd.fullName() + "] is not correctly separated with '|'"); + } else { + permType(ps[0],null); + permInstance(ps[1]); + permAction(ps[2]); + } + } + } + description("Role",pd.description); + } + return this; + } + + public ServiceValidator delegate(Organization org, Result rdd) { + if(rdd.notOK()) { + msg(rdd.details); + } else { + delegate(org, rdd.value); + } + return this; + } + + public ServiceValidator delegate(Organization org, DelegateDAO.Data dd) { + if(dd==null) { + msg("Delegate Data is null."); + } else { + user(org,dd.user); + user(org,dd.delegate); + } + return this; + } + + + public ServiceValidator cred(AuthzTrans trans, Organization org, Result rcd, boolean isNew) { + if(rcd.notOK()) { + msg(rcd.details); + } else { + cred(trans, org,rcd.value,isNew); + } + return this; + } + + public ServiceValidator cred(AuthzTrans trans, Organization org, CredDAO.Data cd, boolean isNew) { + if(cd==null) { + msg("Cred Data is null."); + } else { + if(!org.isValidCred(trans, cd.id)) { + msg("ID [" + cd.id + "] is invalid in " + org.getName()); + } + String str = cd.id; + int idx = str.indexOf('@'); + if(idx>0) { + str = str.substring(0,idx); + } + + if(org.supportsRealm(cd.id)) { + String resp = org.isValidID(trans, str); + if(isNew && (resp!=null && resp.length()>0)) { + msg(cd.id,str); + } + } + + if(cd.type==null) { + msg("Credential Type must be set"); + } else { + switch(cd.type) { + case CredDAO.BASIC_AUTH_SHA256: + // ok + break; + default: + msg("Credential Type [",Integer.toString(cd.type),"] is invalid"); + } + } + } + return this; + } + + + public ServiceValidator user(Organization org, String user) { + if(nob(user,ID_CHARS)) { + msg("User [",user,"] is invalid."); + } + return this; + } + + public ServiceValidator ns(Result nsd) { + notOK(nsd); + ns(nsd.value); + return this; + } + + public ServiceValidator ns(Namespace ns) { + ns(ns.name); + for(String s : ns.admin) { + if(nob(s,ID_CHARS)) { + msg("Admin [" + s + "] is invalid."); + } + + } + for(String s : ns.owner) { + if(nob(s,ID_CHARS)) { + msg("Responsible [" + s + "] is invalid."); + } + + } + + if(ns.attrib!=null) { + for(Pair at : ns.attrib) { + if(nob(at.x,NAME_CHARS)) { + msg("Attribute tag [" + at.x + "] is invalid."); + } + if(nob(at.x,NAME_CHARS)) { + msg("Attribute value [" + at.y + "] is invalid."); + } + } + } + + description("Namespace",ns.description); + return this; + } + + public ServiceValidator user_role(UserRoleDAO.Data urdd) { + if(urdd==null) { + msg("UserRole is null"); + } else { + role(urdd.role); + nullOrBlank("UserRole.ns",urdd.ns); + nullOrBlank("UserRole.rname",urdd.rname); + } + return this; + } + + public ServiceValidator nullOrBlank(PermDAO.Data pd) { + if(pd==null) { + msg("Permission is null"); + } else { + nullOrBlank("NS",pd.ns). + nullOrBlank("Type",pd.type). + nullOrBlank("Instance",pd.instance). + nullOrBlank("Action",pd.action); + } + return this; + } + + public ServiceValidator nullOrBlank(RoleDAO.Data rd) { + if(rd==null) { + msg("Role is null"); + } else { + nullOrBlank("NS",rd.ns). + nullOrBlank("Name",rd.name); + } + return this; + } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Approval.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Approval.java index f302742f..19c79037 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Approval.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Approval.java @@ -35,34 +35,34 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_Approval { - API_Approval api_Approval; + API_Approval api_Approval; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; - @Before - public void setUp() - { + @Before + public void setUp() + { - } + } - @SuppressWarnings("static-access") - @Test - public void testInit() { + @SuppressWarnings("static-access") + @Test + public void testInit() { - try { - api_Approval.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //assertTrue(true); - } + try { + api_Approval.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //assertTrue(true); + } -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Creds.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Creds.java index 41d4daf0..32319e2e 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Creds.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Creds.java @@ -38,43 +38,43 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_Creds { - API_Creds api_Creds; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; - Env env; - DirectAAFUserPass directAAFUserPass; - @Before - public void setUp(){ + API_Creds api_Creds; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; + Env env; + DirectAAFUserPass directAAFUserPass; + @Before + public void setUp(){ - } + } - @SuppressWarnings("static-access") - @Test - public void testInit(){ - try { - api_Creds.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @SuppressWarnings("static-access") + @Test + public void testInit(){ + try { + api_Creds.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - @SuppressWarnings("static-access") - @Test - public void testTimeSensitiveInit(){ + @SuppressWarnings("static-access") + @Test + public void testTimeSensitiveInit(){ - try { - api_Creds.timeSensitiveInit(env, authzAPI, facade, directAAFUserPass); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + try { + api_Creds.timeSensitiveInit(env, authzAPI, facade, directAAFUserPass); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } // -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Delegate.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Delegate.java index 9ca81525..b97ef6e6 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Delegate.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Delegate.java @@ -35,30 +35,30 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_Delegate { - API_Delegate api_Delegate; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; - @Before - public void setUp() { + API_Delegate api_Delegate; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; + @Before + public void setUp() { - } + } - @SuppressWarnings("static-access") - @Test - public void testInit(){ + @SuppressWarnings("static-access") + @Test + public void testInit(){ - try { - api_Delegate.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + try { + api_Delegate.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } // -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_History.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_History.java index dc0a8260..6ea5c560 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_History.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_History.java @@ -35,33 +35,33 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_History { - API_History api_History; + API_History api_History; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; - @Before - public void setUp(){ + @Before + public void setUp(){ - } + } - @SuppressWarnings("static-access") - @Test - public void testInit(){ + @SuppressWarnings("static-access") + @Test + public void testInit(){ - try { - api_History.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - } + try { + api_History.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + } -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_NS.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_NS.java index ce123404..1279e40e 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_NS.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_NS.java @@ -34,26 +34,26 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_NS { - API_NS api_Ns; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; - - - @SuppressWarnings("static-access") - @Test - public void testInit(){ - try { - api_Ns.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } + API_NS api_Ns; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; + + + @SuppressWarnings("static-access") + @Test + public void testInit(){ + try { + api_Ns.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Perms.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Perms.java index f778fd9e..fa9aa77c 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Perms.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Perms.java @@ -35,41 +35,41 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_Perms { - API_Perms api_Perms; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; + API_Perms api_Perms; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; - @Before - public void setUp(){ + @Before + public void setUp(){ - } + } - @SuppressWarnings("static-access") - @Test - public void testInit(){ - try { - api_Perms.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @SuppressWarnings("static-access") + @Test + public void testInit(){ + try { + api_Perms.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - @SuppressWarnings("static-access") - @Test - public void testTimeSensitiveInit(){ - try { - api_Perms.timeSensitiveInit(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @SuppressWarnings("static-access") + @Test + public void testTimeSensitiveInit(){ + try { + api_Perms.timeSensitiveInit(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Roles.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Roles.java index 67506d32..95414677 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Roles.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_Roles.java @@ -35,31 +35,31 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_Roles { - API_Roles api_Roles; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; + API_Roles api_Roles; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; - @Before - public void setUp() { - assertTrue(true); - } + @Before + public void setUp() { + assertTrue(true); + } - @SuppressWarnings("static-access") - @Test - public void testInit(){ - try { - api_Roles.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @SuppressWarnings("static-access") + @Test + public void testInit(){ + try { + api_Roles.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_User.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_User.java index 89e5875f..45e63aa0 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_User.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_User.java @@ -35,30 +35,30 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_User { - API_User api_User; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; + API_User api_User; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; - @Before - public void setUp() { - //assertTrue(true); - } + @Before + public void setUp() { + //assertTrue(true); + } - @SuppressWarnings("static-access") - @Test - public void testInit(){ - try { - api_User.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @SuppressWarnings("static-access") + @Test + public void testInit(){ + try { + api_User.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_UserRole.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_UserRole.java index dce67063..7dfc914d 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_UserRole.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/api/test/JU_API_UserRole.java @@ -35,26 +35,26 @@ import org.onap.aaf.auth.service.facade.AuthzFacade; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_API_UserRole { - API_UserRole api_UserRole; - @Mock - AAF_Service authzAPI; - AuthzFacade facade; - - - @SuppressWarnings("static-access") - @Test - public void testInit(){ - try { - api_UserRole.init(authzAPI, facade); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -// @Test -// public void notYetImplemented() { -// fail("Tests in this file should not be trusted"); -// } + API_UserRole api_UserRole; + @Mock + AAF_Service authzAPI; + AuthzFacade facade; + + + @SuppressWarnings("static-access") + @Test + public void testInit(){ + try { + api_UserRole.init(authzAPI, facade); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +// @Test +// public void notYetImplemented() { +// fail("Tests in this file should not be trusted"); +// } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/validation/test/JU_ServiceValidator.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/validation/test/JU_ServiceValidator.java index 872161a0..1a3b0265 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/validation/test/JU_ServiceValidator.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/validation/test/JU_ServiceValidator.java @@ -37,78 +37,78 @@ import org.onap.aaf.auth.validation.Validator; public class JU_ServiceValidator { - ServiceValidator validator; + ServiceValidator validator; - @Before - public void setUp() { - validator = new ServiceValidator(); - } + @Before + public void setUp() { + validator = new ServiceValidator(); + } - @Test - public void permNotOk() { + @Test + public void permNotOk() { - Result rpd = Result.err(1, "ERR_Security"); + Result rpd = Result.err(1, "ERR_Security"); - validator.perm(rpd); - assertTrue(validator.errs().equals("ERR_Security\n")); + validator.perm(rpd); + assertTrue(validator.errs().equals("ERR_Security\n")); - } - - @Test - public void permInstance() { - assertFalse(validator.permInstance("hello").err()); - assertFalse(validator.permInstance("hello32").err()); - assertFalse(validator.permInstance("hello-32").err()); - assertFalse(validator.permInstance(":asdf:*:sdf*:sdk").err()); - assertFalse(validator.permInstance(":asdf:*:sdf*:sdk*").err()); - // Perms may not end in ":" - assertTrue(validator.permInstance(":").err()); - assertTrue(validator.permInstance(":hello:").err()); - } + } + + @Test + public void permInstance() { + assertFalse(validator.permInstance("hello").err()); + assertFalse(validator.permInstance("hello32").err()); + assertFalse(validator.permInstance("hello-32").err()); + assertFalse(validator.permInstance(":asdf:*:sdf*:sdk").err()); + assertFalse(validator.permInstance(":asdf:*:sdf*:sdk*").err()); + // Perms may not end in ":" + assertTrue(validator.permInstance(":").err()); + assertTrue(validator.permInstance(":hello:").err()); + } - @Test - public void permOkNull() { + @Test + public void permOkNull() { - Result rpd = Result.ok(); + Result rpd = Result.ok(); - validator.perm(rpd); - assertTrue(validator.errs().equals("Perm Data is null.\n")); + validator.perm(rpd); + assertTrue(validator.errs().equals("Perm Data is null.\n")); - } + } - @Test - public void roleOkNull() { + @Test + public void roleOkNull() { - Result rrd = Result.ok(); + Result rrd = Result.ok(); - validator.role(rrd); - assertTrue(validator.errs().equals("Role Data is null.\n")); - } + validator.role(rrd); + assertTrue(validator.errs().equals("Role Data is null.\n")); + } - @Test - public void roleOk() { - RoleDAO.Data to = new RoleDAO.Data(); - to.ns = "namespace"; - to.name = "name"; - to.description = "description"; - Set permissions = new HashSet<>(); - permissions.add("perm1"); - to.perms = permissions; + @Test + public void roleOk() { + RoleDAO.Data to = new RoleDAO.Data(); + to.ns = "namespace"; + to.name = "name"; + to.description = "description"; + Set permissions = new HashSet<>(); + permissions.add("perm1"); + to.perms = permissions; - Result rrd = Result.ok(to); + Result rrd = Result.ok(to); - validator.role(rrd); - assertTrue( - validator.errs().equals("Perm [perm1] in Role [namespace.name] is not correctly separated with '|'\n")); - } + validator.role(rrd); + assertTrue( + validator.errs().equals("Perm [perm1] in Role [namespace.name] is not correctly separated with '|'\n")); + } - @Test - public void roleNotOk() { + @Test + public void roleNotOk() { - Result rrd = Result.err(1, "ERR_Security"); + Result rrd = Result.err(1, "ERR_Security"); - validator.role(rrd); - assertTrue(validator.errs().equals("ERR_Security\n")); - } + validator.role(rrd); + assertTrue(validator.errs().equals("ERR_Security\n")); + } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java b/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java index a7df421b..12b343d5 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java @@ -102,195 +102,195 @@ public class JU_Mapper_2_0 { private static final String USER = "John"; - private Mapper_2_0 mapper; - @Mock - private Question question; - @Mock - private AuthzTrans transaction; - @Mock + private Mapper_2_0 mapper; + @Mock + private Question question; + @Mock + private AuthzTrans transaction; + @Mock private TimeTaken tt; - @Before - public void setUp() throws APIException, IOException, CadiException { - given(transaction.start(anyString(), eq(Env.SUB))).willReturn(tt); - given(transaction.user()).willReturn(USER); - this.mapper = new Mapper_2_0(question); - } - - @Test(expected = ClassCastException.class) - public void ns_willThrowException_whenInvalidRequestType() { - //given - Request rq = new Request(); - - //when - mapper.ns(transaction, rq); - - //then - fail("Expected ClassCastException"); - } - - @Test - public void ns_shouldConvertNamespaceRequest_whenValidTypeIsExplicitlyProvided() { - //given - String namespaceName = "org.companyA.app1"; - String namespaceType = "APP"; - NsType expectedNsType = NsType.APP; - NsRequest nsRequest = createNsRequestForType(namespaceName, namespaceType); - - //when - Result result = mapper.ns(transaction,nsRequest); - - //then - assertTrue(result.isOK()); - assertNamespaceValues(result.value, expectedNsType, namespaceName); - verify(transaction).checkpoint(namespaceName,Env.ALWAYS); - } - - @Test - public void ns_shouldConvertNamespaceRequest_whenInValidTypeIsExplicitlyProvided() { - //given - String namespaceName = "org.companyA.app1.service0"; - String invalidNsType = "BLUE"; - NsType expectedNsType = NsType.APP; - NsRequest nsRequest = createNsRequestForType(namespaceName, invalidNsType); - - //when - Result result = mapper.ns(transaction,nsRequest); - - //then - assertTrue(result.isOK()); - assertNamespaceValues(result.value, expectedNsType, namespaceName); - verify(transaction).checkpoint(namespaceName,Env.ALWAYS); - } - - @Test - public void ns_shouldConvertRootNamespaceRequest_whenTypeNotProvided() { - //given - String rootNsName = "org"; - NsType expectedNsType = NsType.ROOT; - NsRequest nsRequest = createNsRequestForType(rootNsName, null); - - //when - Result result = mapper.ns(transaction,nsRequest); - - //then - assertTrue(result.isOK()); - assertNamespaceValues(result.value, expectedNsType, rootNsName); - verify(transaction).checkpoint(rootNsName,Env.ALWAYS); - } - - @Test - public void ns_shouldConvertCompanyNamespaceRequest_whenTypeNotProvided() { - //given - String companyNsName = "org.companyA"; - NsType expectedNsType = NsType.COMPANY; - NsRequest nsRequest = createNsRequestForType(companyNsName, null); - - //when - Result result = mapper.ns(transaction,nsRequest); - - //then - assertTrue(result.isOK()); - assertNamespaceValues(result.value, expectedNsType, companyNsName); - verify(transaction).checkpoint(companyNsName,Env.ALWAYS); - } - - private void assertNamespaceValues(Namespace value, NsType nsType, String namespaceName) { - List people = Lists.newArrayList("tk007@people.osaaf.org"); - assertEquals(Integer.valueOf(nsType.type), value.type); - assertEquals(namespaceName, value.name); - assertEquals("some namespace description", value.description); - assertEquals(people, value.admin); - assertEquals(people, value.owner); - } - - private NsRequest createNsRequestForType(String nsName, String nsType) { - NsRequest req = mapper.newInstance(API.NS_REQ); - req.setType(nsType); - req.setName(nsName); - req.setDescription("some namespace description"); - req.getAdmin().add("tk007@people.osaaf.org"); - req.getResponsible().add("tk007@people.osaaf.org"); - return req; - } - - @Test - public void nss_shouldConvertNamespaceToNss_withoutAttributes() { - //given - Nss nss = mapper.newInstance(API.NSS); - Namespace ns = mapper.ns(transaction, createNsRequestForType("org.onap", null)).value; - - //when - Result result = mapper.nss(transaction, ns, nss); - - //then - assertTrue(result.isOK()); - assertEquals("Only one Ns should be added",1, result.value.getNs().size()); - Ns addedNs = Iterables.getOnlyElement(result.value.getNs()); - assertEquals(ns.admin, addedNs.getAdmin()); - assertEquals(ns.name, addedNs.getName()); - assertEquals(ns.owner, addedNs.getResponsible()); - assertEquals(ns.description, addedNs.getDescription()); - assertTrue(addedNs.getAttrib().isEmpty()); - } - - @Test - public void nss_shouldConvertNamespaceToNss_withAttributes() { - //given - Nss nss = mapper.newInstance(API.NSS); - Namespace ns = mapper.ns(transaction, createNsRequestForType("org.onap", null)).value; - ns.attrib = Lists.newArrayList(); - int attribNum = 5; - Map attribs = ImmutableMap.of("key1", "value1", "key2", "value2", "key3", "value3", "key4", "value4", "key5", "value5"); - attribs.forEach((key,val) -> ns.attrib.add(new Pair<>(key,val))); - - //when - Result result = mapper.nss(transaction, ns, nss); - - //then - assertTrue(result.isOK()); - assertEquals("Only one Ns should be added",1, result.value.getNs().size()); - Ns addedNs = Iterables.getOnlyElement(result.value.getNs()); - assertEquals(attribNum, addedNs.getAttrib().size()); - addedNs.getAttrib().forEach( attr -> { - assertEquals(attr.getValue(), attribs.get(attr.getKey())); - }); - } - - @Test - public void nss_shouldAddSeveralNamespacesToNss() { - //given - Nss nss = mapper.newInstance(API.NSS); - Namespace ns1 = mapper.ns(transaction, createNsRequestForType("org.onap", "COMPANY")).value; - Namespace ns2 = mapper.ns(transaction, createNsRequestForType("org.onap.prh", "APP")).value; - - //when - Result result = mapper.nss(transaction, Lists.newArrayList(ns1,ns2), nss); - - //then - assertTrue(result.isOK()); - assertEquals("Two namespaces should be added",2, result.value.getNs().size()); - } - - @Test - public void perm_shouldNotAddPerms_whenFilterIsSet_andUserIsNotAuthorized() { - //given + @Before + public void setUp() throws APIException, IOException, CadiException { + given(transaction.start(anyString(), eq(Env.SUB))).willReturn(tt); + given(transaction.user()).willReturn(USER); + this.mapper = new Mapper_2_0(question); + } + + @Test(expected = ClassCastException.class) + public void ns_willThrowException_whenInvalidRequestType() { + //given + Request rq = new Request(); + + //when + mapper.ns(transaction, rq); + + //then + fail("Expected ClassCastException"); + } + + @Test + public void ns_shouldConvertNamespaceRequest_whenValidTypeIsExplicitlyProvided() { + //given + String namespaceName = "org.companyA.app1"; + String namespaceType = "APP"; + NsType expectedNsType = NsType.APP; + NsRequest nsRequest = createNsRequestForType(namespaceName, namespaceType); + + //when + Result result = mapper.ns(transaction,nsRequest); + + //then + assertTrue(result.isOK()); + assertNamespaceValues(result.value, expectedNsType, namespaceName); + verify(transaction).checkpoint(namespaceName,Env.ALWAYS); + } + + @Test + public void ns_shouldConvertNamespaceRequest_whenInValidTypeIsExplicitlyProvided() { + //given + String namespaceName = "org.companyA.app1.service0"; + String invalidNsType = "BLUE"; + NsType expectedNsType = NsType.APP; + NsRequest nsRequest = createNsRequestForType(namespaceName, invalidNsType); + + //when + Result result = mapper.ns(transaction,nsRequest); + + //then + assertTrue(result.isOK()); + assertNamespaceValues(result.value, expectedNsType, namespaceName); + verify(transaction).checkpoint(namespaceName,Env.ALWAYS); + } + + @Test + public void ns_shouldConvertRootNamespaceRequest_whenTypeNotProvided() { + //given + String rootNsName = "org"; + NsType expectedNsType = NsType.ROOT; + NsRequest nsRequest = createNsRequestForType(rootNsName, null); + + //when + Result result = mapper.ns(transaction,nsRequest); + + //then + assertTrue(result.isOK()); + assertNamespaceValues(result.value, expectedNsType, rootNsName); + verify(transaction).checkpoint(rootNsName,Env.ALWAYS); + } + + @Test + public void ns_shouldConvertCompanyNamespaceRequest_whenTypeNotProvided() { + //given + String companyNsName = "org.companyA"; + NsType expectedNsType = NsType.COMPANY; + NsRequest nsRequest = createNsRequestForType(companyNsName, null); + + //when + Result result = mapper.ns(transaction,nsRequest); + + //then + assertTrue(result.isOK()); + assertNamespaceValues(result.value, expectedNsType, companyNsName); + verify(transaction).checkpoint(companyNsName,Env.ALWAYS); + } + + private void assertNamespaceValues(Namespace value, NsType nsType, String namespaceName) { + List people = Lists.newArrayList("tk007@people.osaaf.org"); + assertEquals(Integer.valueOf(nsType.type), value.type); + assertEquals(namespaceName, value.name); + assertEquals("some namespace description", value.description); + assertEquals(people, value.admin); + assertEquals(people, value.owner); + } + + private NsRequest createNsRequestForType(String nsName, String nsType) { + NsRequest req = mapper.newInstance(API.NS_REQ); + req.setType(nsType); + req.setName(nsName); + req.setDescription("some namespace description"); + req.getAdmin().add("tk007@people.osaaf.org"); + req.getResponsible().add("tk007@people.osaaf.org"); + return req; + } + + @Test + public void nss_shouldConvertNamespaceToNss_withoutAttributes() { + //given + Nss nss = mapper.newInstance(API.NSS); + Namespace ns = mapper.ns(transaction, createNsRequestForType("org.onap", null)).value; + + //when + Result result = mapper.nss(transaction, ns, nss); + + //then + assertTrue(result.isOK()); + assertEquals("Only one Ns should be added",1, result.value.getNs().size()); + Ns addedNs = Iterables.getOnlyElement(result.value.getNs()); + assertEquals(ns.admin, addedNs.getAdmin()); + assertEquals(ns.name, addedNs.getName()); + assertEquals(ns.owner, addedNs.getResponsible()); + assertEquals(ns.description, addedNs.getDescription()); + assertTrue(addedNs.getAttrib().isEmpty()); + } + + @Test + public void nss_shouldConvertNamespaceToNss_withAttributes() { + //given + Nss nss = mapper.newInstance(API.NSS); + Namespace ns = mapper.ns(transaction, createNsRequestForType("org.onap", null)).value; + ns.attrib = Lists.newArrayList(); + int attribNum = 5; + Map attribs = ImmutableMap.of("key1", "value1", "key2", "value2", "key3", "value3", "key4", "value4", "key5", "value5"); + attribs.forEach((key,val) -> ns.attrib.add(new Pair<>(key,val))); + + //when + Result result = mapper.nss(transaction, ns, nss); + + //then + assertTrue(result.isOK()); + assertEquals("Only one Ns should be added",1, result.value.getNs().size()); + Ns addedNs = Iterables.getOnlyElement(result.value.getNs()); + assertEquals(attribNum, addedNs.getAttrib().size()); + addedNs.getAttrib().forEach( attr -> { + assertEquals(attr.getValue(), attribs.get(attr.getKey())); + }); + } + + @Test + public void nss_shouldAddSeveralNamespacesToNss() { + //given + Nss nss = mapper.newInstance(API.NSS); + Namespace ns1 = mapper.ns(transaction, createNsRequestForType("org.onap", "COMPANY")).value; + Namespace ns2 = mapper.ns(transaction, createNsRequestForType("org.onap.prh", "APP")).value; + + //when + Result result = mapper.nss(transaction, Lists.newArrayList(ns1,ns2), nss); + + //then + assertTrue(result.isOK()); + assertEquals("Two namespaces should be added",2, result.value.getNs().size()); + } + + @Test + public void perm_shouldNotAddPerms_whenFilterIsSet_andUserIsNotAuthorized() { + //given given(question.mayUser(eq(transaction), eq(USER), any(PermDAO.Data.class), eq(Access.read))) .willReturn(Result.err(9, "error")); Perms permsContainer = mapper.newInstance(API.PERMS); List permsData = Lists.newArrayList(new PermDAO.Data()); boolean filter = true; - //when + //when Result result = mapper.perms(transaction, permsData, permsContainer, filter); - //then + //then assertTrue(result.isOK()); assertEquals("No perms added",0,result.value.getPerm().size()); - } + } - @Test + @Test public void perm_shouldAddPerm_withNamespaceSet_whenUserIsAuthorized_AndNamespaceIsRequestedType() { //given given(question.mayUser(eq(transaction), eq(USER), any(PermDAO.Data.class), eq(Access.read))) @@ -298,13 +298,13 @@ public class JU_Mapper_2_0 { given(transaction.requested(REQD_TYPE.ns)).willReturn(true); Perms permsContainer = mapper.newInstance(API.PERMS); Set roles = Sets.newHashSet("org.onap.portal.owner","org.onap.portal.designer" - ,"org.onap.portal.tester"); + ,"org.onap.portal.tester"); String namespace = "org.onap.portal"; String type = "access"; String fullType = namespace + "." +type; String action = "read"; String description = "Portal Read Access"; - List permsData = Lists.newArrayList(createPermDAOobj(namespace, type, "*",action, roles, description)); + List permsData = Lists.newArrayList(createPermDAOobj(namespace, type, "*",action, roles, description)); boolean filter = true; //when @@ -322,66 +322,66 @@ public class JU_Mapper_2_0 { assertEquals(Lists.newArrayList(roles), perm.getRoles()); } - @Test - public void perm_shouldAddPerm_withoutNamespaceSet_whenUserIsAuthorized_AndNamespaceIsNotRequestedType() { - //given - given(question.mayUser(eq(transaction), eq(USER), any(PermDAO.Data.class), eq(Access.read))) - .willReturn(Result.ok(new NsDAO.Data())); - given(transaction.requested(REQD_TYPE.ns)).willReturn(false); - Perms permsContainer = mapper.newInstance(API.PERMS); - String namespace = "org.onap.portal"; - String type = "access"; - String fullType = namespace + "." + type; - String action = "read"; - List permsData = Lists.newArrayList(createPermDAOobj(namespace, type, "*",action, null, null)); - boolean filter = true; - - //when - Result result = mapper.perms(transaction, permsData, permsContainer, filter); - - //then - assertTrue(result.isOK()); - assertEquals("Perm is added",1,result.value.getPerm().size()); - Perm perm = Iterables.getOnlyElement(result.value.getPerm()); - assertNull(perm.getNs()); - assertEquals(fullType, perm.getType()); - assertEquals(action, perm.getAction()); - } - - @Test - public void perm_shouldAddPermsWithCorrectSortedOrder() { - //given - given(question.mayUser(eq(transaction), eq(USER), any(PermDAO.Data.class), eq(Access.read))) - .willReturn(Result.ok(new NsDAO.Data())); - Perms permsContainer = mapper.newInstance(API.PERMS); - PermDAO.Data perm1 = createPermDAOobj("org.onap.portal", "access", "*", "read", null, null); - PermDAO.Data perm2 = createPermDAOobj("org.onap.portal", "access", "*", "write", null, null); - PermDAO.Data perm3 = createPermDAOobj("org.onap.portal", "design", "*", "new", null, null); - PermDAO.Data perm4 = createPermDAOobj("org.onap.portal", "workflow", "1", "edit", null, null); - PermDAO.Data perm5 = createPermDAOobj("org.onap.portal", "workflow", "2", "edit", null, null); - List permsData = Lists.newArrayList(perm4, perm1, perm5, perm3, perm2); - List correctOrderPerms = Lists.newArrayList(perm1, perm2, perm3, perm4, perm5); - - //when - Result result = mapper.perms(transaction, permsData, permsContainer, true); - - //then - assertTrue(result.isOK()); - assertEquals("Alls Perms added",5,result.value.getPerm().size()); - List mappedPerms = result.value.getPerm(); - for(int i=0; i<5; i++) { - comparePerm(correctOrderPerms.get(i), mappedPerms.get(i)); - } - } - - private void comparePerm(Data data, Perm perm) { - assertEquals(data.ns + "." + data.type, perm.getType()); - assertEquals(data.instance, perm.getInstance()); - assertEquals(data.action, perm.getAction()); - } - - private PermDAO.Data createPermDAOobj(String ns, String name, String instance, String action, Set roles, String description) { - NsSplit nss = new NsSplit(ns, name); + @Test + public void perm_shouldAddPerm_withoutNamespaceSet_whenUserIsAuthorized_AndNamespaceIsNotRequestedType() { + //given + given(question.mayUser(eq(transaction), eq(USER), any(PermDAO.Data.class), eq(Access.read))) + .willReturn(Result.ok(new NsDAO.Data())); + given(transaction.requested(REQD_TYPE.ns)).willReturn(false); + Perms permsContainer = mapper.newInstance(API.PERMS); + String namespace = "org.onap.portal"; + String type = "access"; + String fullType = namespace + "." + type; + String action = "read"; + List permsData = Lists.newArrayList(createPermDAOobj(namespace, type, "*",action, null, null)); + boolean filter = true; + + //when + Result result = mapper.perms(transaction, permsData, permsContainer, filter); + + //then + assertTrue(result.isOK()); + assertEquals("Perm is added",1,result.value.getPerm().size()); + Perm perm = Iterables.getOnlyElement(result.value.getPerm()); + assertNull(perm.getNs()); + assertEquals(fullType, perm.getType()); + assertEquals(action, perm.getAction()); + } + + @Test + public void perm_shouldAddPermsWithCorrectSortedOrder() { + //given + given(question.mayUser(eq(transaction), eq(USER), any(PermDAO.Data.class), eq(Access.read))) + .willReturn(Result.ok(new NsDAO.Data())); + Perms permsContainer = mapper.newInstance(API.PERMS); + PermDAO.Data perm1 = createPermDAOobj("org.onap.portal", "access", "*", "read", null, null); + PermDAO.Data perm2 = createPermDAOobj("org.onap.portal", "access", "*", "write", null, null); + PermDAO.Data perm3 = createPermDAOobj("org.onap.portal", "design", "*", "new", null, null); + PermDAO.Data perm4 = createPermDAOobj("org.onap.portal", "workflow", "1", "edit", null, null); + PermDAO.Data perm5 = createPermDAOobj("org.onap.portal", "workflow", "2", "edit", null, null); + List permsData = Lists.newArrayList(perm4, perm1, perm5, perm3, perm2); + List correctOrderPerms = Lists.newArrayList(perm1, perm2, perm3, perm4, perm5); + + //when + Result result = mapper.perms(transaction, permsData, permsContainer, true); + + //then + assertTrue(result.isOK()); + assertEquals("Alls Perms added",5,result.value.getPerm().size()); + List mappedPerms = result.value.getPerm(); + for(int i=0; i<5; i++) { + comparePerm(correctOrderPerms.get(i), mappedPerms.get(i)); + } + } + + private void comparePerm(Data data, Perm perm) { + assertEquals(data.ns + "." + data.type, perm.getType()); + assertEquals(data.instance, perm.getInstance()); + assertEquals(data.action, perm.getAction()); + } + + private PermDAO.Data createPermDAOobj(String ns, String name, String instance, String action, Set roles, String description) { + NsSplit nss = new NsSplit(ns, name); PermDAO.Data perm = new PermDAO.Data(nss, instance, action); perm.roles = roles; perm.description = description; @@ -389,263 +389,263 @@ public class JU_Mapper_2_0 { } @Test - public void role_shouldReturnErrorResult_whenNssIsNok() throws Exception { - //given - String roleName = "admin"; - RoleRequest request = createRoleRequest(roleName, "role description"); - given(question.deriveNsSplit(transaction, roleName)).willReturn(Result.err(new IllegalArgumentException())); - - //when - Result result = mapper.role(transaction, request); - - //then - assertFalse(result.isOK()); - assertNull(result.value); - assertEquals(ERR_General, result.status); - } - - @Test - public void role_shouldReturnMappedRoleObject_whenNssIsOk() throws Exception { - //given - String roleName = "admin"; - String roleNs = "org.onap.roles"; - String roleFullName = roleNs + "." + roleName; - String description =" role description"; - RoleRequest request = createRoleRequest(roleFullName, description); - given(question.deriveNsSplit(transaction, roleFullName)).willReturn(Result.ok(new NsSplit(roleNs, roleName))); - - //when - Result result = mapper.role(transaction, request); - - //then - assertTrue(result.isOK()); - assertEquals(roleName, result.value.name); - assertEquals(roleNs, result.value.ns); - assertEquals(description, result.value.description); - verify(transaction).checkpoint(roleFullName, Env.ALWAYS); - } - - private RoleRequest createRoleRequest(String name, String description) { - RoleRequest req = mapper.newInstance(API.ROLE_REQ); - req.setName(name); - req.setDescription(description); - return req; - } - - @Test - public void roles_shouldNotAddAnyRoles_whenFilterFlagIsNotSet() { - //given - Roles initialRoles = new Roles(); - RoleDAO.Data role = createRoleDAOobj("org.onap.app1", "org.onap.app1.admin", "description"); - - //when - Result result = mapper.roles(transaction, Lists.newArrayList(role), initialRoles, false); - - //then - assertTrue(result.isOK()); - assertEquals(initialRoles.getRole(), result.value.getRole()); - } - - @Test - public void roles_shouldNotAddAnyRoles_whenFilterFlagIsSet_andUserIsNotAuthorizedToReadRole() { - //given - Roles initialRoles = new Roles(); - RoleDAO.Data role = createRoleDAOobj("org.onap.app1", "org.onap.app1.admin", "description"); - given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) - .willReturn(Result.err(9, "error")); - - //when - Result result = mapper.roles(transaction, Lists.newArrayList(role), initialRoles, true); - - //then - assertTrue(result.isOK()); - assertEquals(initialRoles.getRole(), result.value.getRole()); - } - - @Test - public void roles_shouldAddRolesWithoutNamespace_whenNsNotRequested_andFilterFlagSet_andUserIsAuthorized() { - test_roles_shouldAddRoles(false); - } - - @Test - public void roles_shouldAddRolesWithNamespace_whenNsRequested_andFilterFlagSet_andUserIsAuthorized() { - test_roles_shouldAddRoles(true); - } - - private void test_roles_shouldAddRoles(boolean namespaceRequested) { - //given - String namespace = "org.onap.app1"; - String description = "role description"; - Set roleNames = Sets.newHashSet(namespace+".admin", namespace+".deployer"); - List daoRoles = roleNames.stream().map( name -> createRoleDAOobj(namespace, name, description)) - .collect(Collectors.toList()); - given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) - .willReturn(Result.ok(new NsDAO.Data())); - given(transaction.requested(REQD_TYPE.ns)).willReturn(namespaceRequested); - - //when - Result result = mapper.roles(transaction, daoRoles, new Roles(), true); - - //then - assertTrue(result.isOK()); - assertEquals(2, result.value.getRole().size()); - result.value.getRole().stream().forEach( role -> { - assertTrue(role.getPerms().isEmpty()); - if(namespaceRequested) { - assertEquals(namespace, role.getNs()); - } else { - assertNull(role.getNs()); - } - assertTrue(roleNames.contains(role.getName())); - assertEquals(description, role.getDescription()); - }); - } - - @Test - public void roles_shouldReturnErrorResult_whenAnyPermHasInvalidFormat() { - //given - given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) - .willReturn(Result.ok(new NsDAO.Data())); - RoleDAO.Data role = createRoleDAOobj("org.onap.app", "org.onap.app.admin", "description"); - role.perms = Sets.newHashSet("invalidPermFormat"); - - //when - Result result = mapper.roles(transaction, Lists.newArrayList(role), new Roles(), true); - - //then - assertFalse(result.isOK()); - assertEquals(ERR_BadData, result.status); - } - - @Test - public void roles_shouldAddPerms_whenAllPermsProperlyDefined_andUserCanViewIt() { - //given - given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) - .willReturn(Result.ok(new NsDAO.Data())); - given(question.deriveNsSplit(transaction, "org.onap.app")).willReturn(Result.ok(mock(NsSplit.class))); - RoleDAO.Data role = createRoleDAOobj("org.onap.app", "org.onap.app.admin", "description"); - role.perms = Sets.newHashSet("org.onap.app|access|*|read,approve"); - - //when - Result result = mapper.roles(transaction, Lists.newArrayList(role), new Roles(), true); - - //then - assertTrue(result.isOK()); - Role mappedRole = Iterables.getOnlyElement(result.value.getRole()); - Pkey pKey = Iterables.getOnlyElement(mappedRole.getPerms()); - assertEquals("org.onap.app.access", pKey.getType()); - assertEquals("*", pKey.getInstance()); - assertEquals("read,approve", pKey.getAction()); - } - - private RoleDAO.Data createRoleDAOobj(String namespace, String rolename, String desc) { - NsDAO.Data ns = new NsDAO.Data(); - ns.name = namespace; - RoleDAO.Data role = RoleDAO.Data.create(ns, rolename); - role.description = desc; - return role; - } - - @Test - public void userRoles_shouldMapUserRolesFromDAO() { - //given - String user = "john@people.osaaf.org"; - String role = "admin"; - String namespace = "org.osaaf.aaf"; - int year = 2020; - int month = 10; - int day = 31; - Date expiration = new Calendar.Builder().setDate(year,month-1, day).build().getTime(); //month is 0-based - UserRoles targetRoles = new UserRoles(); - - //when - Result result = mapper.userRoles(transaction, Lists.newArrayList( - createUserRoleDAOobj(user, expiration, namespace, role)), targetRoles); - - //then - assertTrue(result.isOK()); - UserRole targetRole = Iterables.getOnlyElement(result.value.getUserRole()); - assertEquals(user, targetRole.getUser()); - assertEquals(role, targetRole.getRole()); - assertEquals(year, targetRole.getExpires().getYear()); - assertEquals(month, targetRole.getExpires().getMonth()); - assertEquals(day, targetRole.getExpires().getDay()); - } - - @Test - public void userRole_shouldReturnErrorResult_whenAnyExceptionOccurs() { - //given - PermRequest wrongRequestType = new PermRequest(); - - //when - Result result = mapper.userRole(transaction, wrongRequestType); - - //then - assertFalse(result.isOK()); - assertEquals(ERR_BadData, result.status); - verifyZeroInteractions(transaction); - } - - @Test - public void userRole_shouldReturnEmptyRoleDAOobj_whenRequestIsEmpty() { - //given - UserRoleRequest request = new UserRoleRequest(); - given(question.deriveNsSplit(any(), any())).willReturn(Result.err(new IllegalArgumentException())); - Organization org = mock(Organization.class); - given(org.expiration(any(), eq(Expiration.UserInRole), any())).willReturn(new GregorianCalendar()); - given(transaction.org()).willReturn(org); - - //when - Result result = mapper.userRole(transaction, request); - - //then - assertTrue(result.isOK()); - assertNull(result.value.ns); - assertNull(result.value.rname); - assertNull(result.value.role); - assertNull(result.value.user); - assertNotNull(result.value.expires); - } - - @Test - public void userRole_shouldReturnMappedRoleDAOobj_whenRequestIsFilled() { - //given - String user = "johny@people.osaaf.org"; - String role = "org.onap.app1.deployer"; - String rName = "deployer"; - String namespace = "org.onap.app1"; - - given(question.deriveNsSplit(transaction, role)).willReturn(Result.ok(new NsSplit(namespace, rName))); - Organization org = mock(Organization.class); - given(org.expiration(any(), eq(Expiration.UserInRole), any())).willReturn(new GregorianCalendar()); - given(transaction.org()).willReturn(org); - - //when - Result result = mapper.userRole(transaction, createUserRoleRequest(role, user)); - - //then - assertTrue(result.isOK()); - assertEquals(user, result.value.user); - assertEquals(role, result.value.role); - assertEquals(rName, result.value.rname); - assertEquals(namespace, result.value.ns); - assertNotNull(result.value.expires); - } - - private UserRoleRequest createUserRoleRequest(String role, String user) { - UserRoleRequest request = new UserRoleRequest(); - request.setRole(role); - request.setUser(user); - return request; - } - - private UserRoleDAO.Data createUserRoleDAOobj(String userName, Date expires, String namespace, String roleName) { - UserRoleDAO.Data userRole = new UserRoleDAO.Data(); - userRole.user = userName; - userRole.expires = expires; - userRole.ns = namespace; - userRole.role = roleName; - return userRole; - } + public void role_shouldReturnErrorResult_whenNssIsNok() throws Exception { + //given + String roleName = "admin"; + RoleRequest request = createRoleRequest(roleName, "role description"); + given(question.deriveNsSplit(transaction, roleName)).willReturn(Result.err(new IllegalArgumentException())); + + //when + Result result = mapper.role(transaction, request); + + //then + assertFalse(result.isOK()); + assertNull(result.value); + assertEquals(ERR_General, result.status); + } + + @Test + public void role_shouldReturnMappedRoleObject_whenNssIsOk() throws Exception { + //given + String roleName = "admin"; + String roleNs = "org.onap.roles"; + String roleFullName = roleNs + "." + roleName; + String description =" role description"; + RoleRequest request = createRoleRequest(roleFullName, description); + given(question.deriveNsSplit(transaction, roleFullName)).willReturn(Result.ok(new NsSplit(roleNs, roleName))); + + //when + Result result = mapper.role(transaction, request); + + //then + assertTrue(result.isOK()); + assertEquals(roleName, result.value.name); + assertEquals(roleNs, result.value.ns); + assertEquals(description, result.value.description); + verify(transaction).checkpoint(roleFullName, Env.ALWAYS); + } + + private RoleRequest createRoleRequest(String name, String description) { + RoleRequest req = mapper.newInstance(API.ROLE_REQ); + req.setName(name); + req.setDescription(description); + return req; + } + + @Test + public void roles_shouldNotAddAnyRoles_whenFilterFlagIsNotSet() { + //given + Roles initialRoles = new Roles(); + RoleDAO.Data role = createRoleDAOobj("org.onap.app1", "org.onap.app1.admin", "description"); + + //when + Result result = mapper.roles(transaction, Lists.newArrayList(role), initialRoles, false); + + //then + assertTrue(result.isOK()); + assertEquals(initialRoles.getRole(), result.value.getRole()); + } + + @Test + public void roles_shouldNotAddAnyRoles_whenFilterFlagIsSet_andUserIsNotAuthorizedToReadRole() { + //given + Roles initialRoles = new Roles(); + RoleDAO.Data role = createRoleDAOobj("org.onap.app1", "org.onap.app1.admin", "description"); + given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) + .willReturn(Result.err(9, "error")); + + //when + Result result = mapper.roles(transaction, Lists.newArrayList(role), initialRoles, true); + + //then + assertTrue(result.isOK()); + assertEquals(initialRoles.getRole(), result.value.getRole()); + } + + @Test + public void roles_shouldAddRolesWithoutNamespace_whenNsNotRequested_andFilterFlagSet_andUserIsAuthorized() { + test_roles_shouldAddRoles(false); + } + + @Test + public void roles_shouldAddRolesWithNamespace_whenNsRequested_andFilterFlagSet_andUserIsAuthorized() { + test_roles_shouldAddRoles(true); + } + + private void test_roles_shouldAddRoles(boolean namespaceRequested) { + //given + String namespace = "org.onap.app1"; + String description = "role description"; + Set roleNames = Sets.newHashSet(namespace+".admin", namespace+".deployer"); + List daoRoles = roleNames.stream().map( name -> createRoleDAOobj(namespace, name, description)) + .collect(Collectors.toList()); + given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) + .willReturn(Result.ok(new NsDAO.Data())); + given(transaction.requested(REQD_TYPE.ns)).willReturn(namespaceRequested); + + //when + Result result = mapper.roles(transaction, daoRoles, new Roles(), true); + + //then + assertTrue(result.isOK()); + assertEquals(2, result.value.getRole().size()); + result.value.getRole().stream().forEach( role -> { + assertTrue(role.getPerms().isEmpty()); + if(namespaceRequested) { + assertEquals(namespace, role.getNs()); + } else { + assertNull(role.getNs()); + } + assertTrue(roleNames.contains(role.getName())); + assertEquals(description, role.getDescription()); + }); + } + + @Test + public void roles_shouldReturnErrorResult_whenAnyPermHasInvalidFormat() { + //given + given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) + .willReturn(Result.ok(new NsDAO.Data())); + RoleDAO.Data role = createRoleDAOobj("org.onap.app", "org.onap.app.admin", "description"); + role.perms = Sets.newHashSet("invalidPermFormat"); + + //when + Result result = mapper.roles(transaction, Lists.newArrayList(role), new Roles(), true); + + //then + assertFalse(result.isOK()); + assertEquals(ERR_BadData, result.status); + } + + @Test + public void roles_shouldAddPerms_whenAllPermsProperlyDefined_andUserCanViewIt() { + //given + given(question.mayUser(eq(transaction), eq(USER), any(RoleDAO.Data.class), eq(Access.read))) + .willReturn(Result.ok(new NsDAO.Data())); + given(question.deriveNsSplit(transaction, "org.onap.app")).willReturn(Result.ok(mock(NsSplit.class))); + RoleDAO.Data role = createRoleDAOobj("org.onap.app", "org.onap.app.admin", "description"); + role.perms = Sets.newHashSet("org.onap.app|access|*|read,approve"); + + //when + Result result = mapper.roles(transaction, Lists.newArrayList(role), new Roles(), true); + + //then + assertTrue(result.isOK()); + Role mappedRole = Iterables.getOnlyElement(result.value.getRole()); + Pkey pKey = Iterables.getOnlyElement(mappedRole.getPerms()); + assertEquals("org.onap.app.access", pKey.getType()); + assertEquals("*", pKey.getInstance()); + assertEquals("read,approve", pKey.getAction()); + } + + private RoleDAO.Data createRoleDAOobj(String namespace, String rolename, String desc) { + NsDAO.Data ns = new NsDAO.Data(); + ns.name = namespace; + RoleDAO.Data role = RoleDAO.Data.create(ns, rolename); + role.description = desc; + return role; + } + + @Test + public void userRoles_shouldMapUserRolesFromDAO() { + //given + String user = "john@people.osaaf.org"; + String role = "admin"; + String namespace = "org.osaaf.aaf"; + int year = 2020; + int month = 10; + int day = 31; + Date expiration = new Calendar.Builder().setDate(year,month-1, day).build().getTime(); //month is 0-based + UserRoles targetRoles = new UserRoles(); + + //when + Result result = mapper.userRoles(transaction, Lists.newArrayList( + createUserRoleDAOobj(user, expiration, namespace, role)), targetRoles); + + //then + assertTrue(result.isOK()); + UserRole targetRole = Iterables.getOnlyElement(result.value.getUserRole()); + assertEquals(user, targetRole.getUser()); + assertEquals(role, targetRole.getRole()); + assertEquals(year, targetRole.getExpires().getYear()); + assertEquals(month, targetRole.getExpires().getMonth()); + assertEquals(day, targetRole.getExpires().getDay()); + } + + @Test + public void userRole_shouldReturnErrorResult_whenAnyExceptionOccurs() { + //given + PermRequest wrongRequestType = new PermRequest(); + + //when + Result result = mapper.userRole(transaction, wrongRequestType); + + //then + assertFalse(result.isOK()); + assertEquals(ERR_BadData, result.status); + verifyZeroInteractions(transaction); + } + + @Test + public void userRole_shouldReturnEmptyRoleDAOobj_whenRequestIsEmpty() { + //given + UserRoleRequest request = new UserRoleRequest(); + given(question.deriveNsSplit(any(), any())).willReturn(Result.err(new IllegalArgumentException())); + Organization org = mock(Organization.class); + given(org.expiration(any(), eq(Expiration.UserInRole), any())).willReturn(new GregorianCalendar()); + given(transaction.org()).willReturn(org); + + //when + Result result = mapper.userRole(transaction, request); + + //then + assertTrue(result.isOK()); + assertNull(result.value.ns); + assertNull(result.value.rname); + assertNull(result.value.role); + assertNull(result.value.user); + assertNotNull(result.value.expires); + } + + @Test + public void userRole_shouldReturnMappedRoleDAOobj_whenRequestIsFilled() { + //given + String user = "johny@people.osaaf.org"; + String role = "org.onap.app1.deployer"; + String rName = "deployer"; + String namespace = "org.onap.app1"; + + given(question.deriveNsSplit(transaction, role)).willReturn(Result.ok(new NsSplit(namespace, rName))); + Organization org = mock(Organization.class); + given(org.expiration(any(), eq(Expiration.UserInRole), any())).willReturn(new GregorianCalendar()); + given(transaction.org()).willReturn(org); + + //when + Result result = mapper.userRole(transaction, createUserRoleRequest(role, user)); + + //then + assertTrue(result.isOK()); + assertEquals(user, result.value.user); + assertEquals(role, result.value.role); + assertEquals(rName, result.value.rname); + assertEquals(namespace, result.value.ns); + assertNotNull(result.value.expires); + } + + private UserRoleRequest createUserRoleRequest(String role, String user) { + UserRoleRequest request = new UserRoleRequest(); + request.setRole(role); + request.setUser(user); + return request; + } + + private UserRoleDAO.Data createUserRoleDAOobj(String userName, Date expires, String namespace, String roleName) { + UserRoleDAO.Data userRole = new UserRoleDAO.Data(); + userRole.user = userName; + userRole.expires = expires; + userRole.ns = namespace; + userRole.role = roleName; + return userRole; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java index c4ca8082..c4876f29 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java @@ -35,154 +35,154 @@ import org.onap.aaf.misc.env.util.Split; * */ public class AAFPermission implements Permission { - private static final List NO_ROLES; - protected String ns,type,instance,action,key; - private List roles; - - static { - NO_ROLES = new ArrayList<>(); - } + private static final List NO_ROLES; + protected String ns,type,instance,action,key; + private List roles; + + static { + NO_ROLES = new ArrayList<>(); + } - protected AAFPermission() {roles=NO_ROLES;} + protected AAFPermission() {roles=NO_ROLES;} - public AAFPermission(String ns, String name, String instance, String action) { - this.ns = ns; - type = name; - this.instance = instance; - this.action = action; - if(ns==null) { - key = type + '|' + instance + '|' + action; - } else { - key = ns + '|' + type + '|' + instance + '|' + action; - } - this.roles = NO_ROLES; + public AAFPermission(String ns, String name, String instance, String action) { + this.ns = ns; + type = name; + this.instance = instance; + this.action = action; + if(ns==null) { + key = type + '|' + instance + '|' + action; + } else { + key = ns + '|' + type + '|' + instance + '|' + action; + } + this.roles = NO_ROLES; - } + } - public AAFPermission(String ns, String name, String instance, String action, List roles) { - this.ns = ns; - type = name; - this.instance = instance; - this.action = action; - if(ns==null) { - key = type + '|' + instance + '|' + action; - } else { - key = ns + '|' + type + '|' + instance + '|' + action; - } - this.roles = roles==null?NO_ROLES:roles; - } - - /** - * Match a Permission - * if Permission is Fielded type "Permission", we use the fields - * otherwise, we split the Permission with '|' - * - * when the type or action starts with REGEX indicator character ( ! ), - * then it is evaluated as a regular expression. - * - * If you want a simple field comparison, it is faster without REGEX - */ - public boolean match(Permission p) { - String aafNS; - String aafType; - String aafInstance; - String aafAction; - if(p instanceof AAFPermission) { - AAFPermission ap = (AAFPermission)p; - // Note: In AAF > 1.0, Accepting "*" from name would violate multi-tenancy - // Current solution is only allow direct match on Type. - // 8/28/2014 Jonathan - added REGEX ability - aafNS = ap.getNS(); - aafType = ap.getType(); - aafInstance = ap.getInstance(); - aafAction = ap.getAction(); - } else { - // Permission is concatenated together: separated by - String[] aaf = Split.splitTrim('|', p.getKey()); - switch(aaf.length) { - case 1: - aafNS = aaf[0]; - aafType=""; - aafInstance = aafAction = "*"; - break; - case 2: - aafNS = aaf[0]; - aafType = aaf[1]; - aafInstance = aafAction = "*"; - break; - case 3: - aafNS = aaf[0]; - aafType = aaf[1]; - aafInstance = aaf[2]; - aafAction = "*"; - break; - default: - aafNS = aaf[0]; - aafType = aaf[1]; - aafInstance = aaf[2]; - aafAction = aaf[3]; - break; - } - } - boolean typeMatches; - if(aafNS==null) { - if(ns==null) { - typeMatches = aafType.equals(type); - } else { - typeMatches = aafType.equals(ns+'.'+type); - } - } else if(ns==null) { - typeMatches = type.equals(aafNS+'.'+aafType); - } else if(aafNS.length() == ns.length()) { - typeMatches = aafNS.equals(ns) && aafType.equals(type); - } else { // Allow for restructuring of NS/Perm structure - typeMatches = (aafNS+'.'+aafType).equals(ns+'.'+type); - } - return (typeMatches && - PermEval.evalInstance(instance, aafInstance) && - PermEval.evalAction(action, aafAction)); - } + public AAFPermission(String ns, String name, String instance, String action, List roles) { + this.ns = ns; + type = name; + this.instance = instance; + this.action = action; + if(ns==null) { + key = type + '|' + instance + '|' + action; + } else { + key = ns + '|' + type + '|' + instance + '|' + action; + } + this.roles = roles==null?NO_ROLES:roles; + } + + /** + * Match a Permission + * if Permission is Fielded type "Permission", we use the fields + * otherwise, we split the Permission with '|' + * + * when the type or action starts with REGEX indicator character ( ! ), + * then it is evaluated as a regular expression. + * + * If you want a simple field comparison, it is faster without REGEX + */ + public boolean match(Permission p) { + String aafNS; + String aafType; + String aafInstance; + String aafAction; + if(p instanceof AAFPermission) { + AAFPermission ap = (AAFPermission)p; + // Note: In AAF > 1.0, Accepting "*" from name would violate multi-tenancy + // Current solution is only allow direct match on Type. + // 8/28/2014 Jonathan - added REGEX ability + aafNS = ap.getNS(); + aafType = ap.getType(); + aafInstance = ap.getInstance(); + aafAction = ap.getAction(); + } else { + // Permission is concatenated together: separated by + String[] aaf = Split.splitTrim('|', p.getKey()); + switch(aaf.length) { + case 1: + aafNS = aaf[0]; + aafType=""; + aafInstance = aafAction = "*"; + break; + case 2: + aafNS = aaf[0]; + aafType = aaf[1]; + aafInstance = aafAction = "*"; + break; + case 3: + aafNS = aaf[0]; + aafType = aaf[1]; + aafInstance = aaf[2]; + aafAction = "*"; + break; + default: + aafNS = aaf[0]; + aafType = aaf[1]; + aafInstance = aaf[2]; + aafAction = aaf[3]; + break; + } + } + boolean typeMatches; + if(aafNS==null) { + if(ns==null) { + typeMatches = aafType.equals(type); + } else { + typeMatches = aafType.equals(ns+'.'+type); + } + } else if(ns==null) { + typeMatches = type.equals(aafNS+'.'+aafType); + } else if(aafNS.length() == ns.length()) { + typeMatches = aafNS.equals(ns) && aafType.equals(type); + } else { // Allow for restructuring of NS/Perm structure + typeMatches = (aafNS+'.'+aafType).equals(ns+'.'+type); + } + return (typeMatches && + PermEval.evalInstance(instance, aafInstance) && + PermEval.evalAction(action, aafAction)); + } - public String getNS() { - return ns; - } + public String getNS() { + return ns; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public String getFullType() { - return ns + '.' + type; - } - - public String getInstance() { - return instance; - } - - public String getAction() { - return action; - } - - public String getKey() { - return key; - } + public String getFullType() { + return ns + '.' + type; + } + + public String getInstance() { + return instance; + } + + public String getAction() { + return action; + } + + public String getKey() { + return key; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Permission#permType() - */ - public String permType() { - return "AAF"; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Permission#permType() + */ + public String permType() { + return "AAF"; + } - public List roles() { - return roles; - } - public String toString() { - return "AAFPermission:" + - "\n\tNS: " + ns + - "\n\tType: " + type + - "\n\tInstance: " + instance + - "\n\tAction: " + action + - "\n\tKey: " + key; - } + public List roles() { + return roles; + } + public String toString() { + return "AAFPermission:" + + "\n\tNS: " + ns + + "\n\tType: " + type + + "\n\tInstance: " + instance + + "\n\tAction: " + action + + "\n\tKey: " + key; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/Defaults.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/Defaults.java index 5aa4dbc5..a38904d4 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/Defaults.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/Defaults.java @@ -21,13 +21,13 @@ package org.onap.aaf.cadi.aaf; public interface Defaults { - public static String AAF_VERSION = "2.1"; - public static String AAF_NS = "AAF_NS"; - public static String AAF_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".service:" + AAF_VERSION; - public static String GUI_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".gui:" + AAF_VERSION; - public static String CM_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".cm:" + AAF_VERSION; - public static String FS_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".fs:" + AAF_VERSION; - public static String HELLO_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".hello:" + AAF_VERSION; - public static String OAUTH2_TOKEN_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".token:" + AAF_VERSION; - public static String OAUTH2_INTROSPECT_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".introspect:" + AAF_VERSION; + public static String AAF_VERSION = "2.1"; + public static String AAF_NS = "AAF_NS"; + public static String AAF_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".service:" + AAF_VERSION; + public static String GUI_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".gui:" + AAF_VERSION; + public static String CM_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".cm:" + AAF_VERSION; + public static String FS_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".fs:" + AAF_VERSION; + public static String HELLO_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".hello:" + AAF_VERSION; + public static String OAUTH2_TOKEN_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".token:" + AAF_VERSION; + public static String OAUTH2_INTROSPECT_URL = "https://AAF_LOCATE_URL/" + AAF_NS + ".introspect:" + AAF_VERSION; } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java index 75df4eab..f64eb276 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java @@ -25,116 +25,116 @@ import org.onap.aaf.misc.env.util.Split; public class PermEval { - public static final char START_REGEX_CHAR = '!'; - public static final char START_INST_KEY_CHAR=':'; - public static final char ALT_START_INST_KEY_CHAR='/'; + public static final char START_REGEX_CHAR = '!'; + public static final char START_INST_KEY_CHAR=':'; + public static final char ALT_START_INST_KEY_CHAR='/'; - public static final char LIST_SEP = ','; - public static final String INST_KEY_REGEX = new StringBuilder().append(START_INST_KEY_CHAR).toString(); - public static final String ASTERIX = "*"; + public static final char LIST_SEP = ','; + public static final String INST_KEY_REGEX = new StringBuilder().append(START_INST_KEY_CHAR).toString(); + public static final String ASTERIX = "*"; - /** - * Evaluate Instance - * - * Instance can be more complex. It can be a string, a Regular Expression, or a ":" separated Key - * who's parts can also be a String, Regular Expression. - * - * sInst = Server's Instance - * In order to prevent false matches, keys must be the same length to count as equal - * Changing this will break existing users, like Cassandra. Jonathan 9-4-2015 - */ - public static boolean evalInstance(String sInst, String pInst) { - if(sInst == null || pInst == null) { - return false; - } - if (sInst == "" || pInst == "") { - return false; - } - if(ASTERIX.equals(sInst)) { - return true; // If Server's String is "*", then it accepts every Instance - } - char firstChar = pInst.charAt(0); - char startChar = firstChar==ALT_START_INST_KEY_CHAR?ALT_START_INST_KEY_CHAR:START_INST_KEY_CHAR; - switch(pInst.charAt(0)) { // First char - case START_REGEX_CHAR: // Evaluate as Regular Expression - String pItem = pInst.substring(1); - String first = Split.split(LIST_SEP,sInst)[0]; // allow for "," definition in Action - return first.matches(pItem); + /** + * Evaluate Instance + * + * Instance can be more complex. It can be a string, a Regular Expression, or a ":" separated Key + * who's parts can also be a String, Regular Expression. + * + * sInst = Server's Instance + * In order to prevent false matches, keys must be the same length to count as equal + * Changing this will break existing users, like Cassandra. Jonathan 9-4-2015 + */ + public static boolean evalInstance(String sInst, String pInst) { + if(sInst == null || pInst == null) { + return false; + } + if (sInst == "" || pInst == "") { + return false; + } + if(ASTERIX.equals(sInst)) { + return true; // If Server's String is "*", then it accepts every Instance + } + char firstChar = pInst.charAt(0); + char startChar = firstChar==ALT_START_INST_KEY_CHAR?ALT_START_INST_KEY_CHAR:START_INST_KEY_CHAR; + switch(pInst.charAt(0)) { // First char + case START_REGEX_CHAR: // Evaluate as Regular Expression + String pItem = pInst.substring(1); + String first = Split.split(LIST_SEP,sInst)[0]; // allow for "," definition in Action + return first.matches(pItem); - case START_INST_KEY_CHAR: // Evaluate a special Key field, i.e.:xyz:*:!df.* - case ALT_START_INST_KEY_CHAR: // Also allow '/' as special Key Field, i.e. /xyz/*/!.* - if(sInst.charAt(0)==startChar) { // To compare key-to-key, both strings must be keys - String[] skeys=Split.split(startChar,sInst); - String[] pkeys=Split.split(startChar,pInst); - if(skeys.length!=pkeys.length) return false; + case START_INST_KEY_CHAR: // Evaluate a special Key field, i.e.:xyz:*:!df.* + case ALT_START_INST_KEY_CHAR: // Also allow '/' as special Key Field, i.e. /xyz/*/!.* + if(sInst.charAt(0)==startChar) { // To compare key-to-key, both strings must be keys + String[] skeys=Split.split(startChar,sInst); + String[] pkeys=Split.split(startChar,pInst); + if(skeys.length!=pkeys.length) return false; - boolean pass = true; - for(int i=1;pass && i []"); - } else { - print(true,"START OF CONNECTIVITY TESTS",new Date().toString(),System.getProperty("user.name"), - "Note: All API Calls are /authz/perms/user/"); + + public static void main(String[] args) { + if(args.length<1) { + System.out.println("Usage: ConnectivityTester []"); + } else { + print(true,"START OF CONNECTIVITY TESTS",new Date().toString(),System.getProperty("user.name"), + "Note: All API Calls are /authz/perms/user/"); - if(!args[0].contains(Config.CADI_PROP_FILES+'=')) { - args[0]=Config.CADI_PROP_FILES+'='+args[0]; - } + if(!args[0].contains(Config.CADI_PROP_FILES+'=')) { + args[0]=Config.CADI_PROP_FILES+'='+args[0]; + } - PropAccess access = new PropAccess(args); - String aaflocate; - if(args.length>1) { - aaflocate = "https://" + args[1]; - access.setProperty(Config.AAF_LOCATE_URL, "https://" + args[1]); - } else { - aaflocate = access.getProperty(Config.AAF_LOCATE_URL); - if(aaflocate==null) { - print(true,"Properties must contain ",Config.AAF_LOCATE_URL); - } - } - - try { - SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); - - List> lss = loadSetters(access,si); - ///////// - print(true,"Test Connections driven by AAFLocator"); - URI serviceURI = new URI(Defaults.AAF_URL); + PropAccess access = new PropAccess(args); + String aaflocate; + if(args.length>1) { + aaflocate = "https://" + args[1]; + access.setProperty(Config.AAF_LOCATE_URL, "https://" + args[1]); + } else { + aaflocate = access.getProperty(Config.AAF_LOCATE_URL); + if(aaflocate==null) { + print(true,"Properties must contain ",Config.AAF_LOCATE_URL); + } + } + + try { + SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); + + List> lss = loadSetters(access,si); + ///////// + print(true,"Test Connections driven by AAFLocator"); + URI serviceURI = new URI(Defaults.AAF_URL); - for(URI uri : new URI[] { - serviceURI, - new URI(Defaults.OAUTH2_TOKEN_URL), - new URI(Defaults.OAUTH2_INTROSPECT_URL), - new URI(Defaults.CM_URL), - new URI(Defaults.GUI_URL), - new URI(Defaults.FS_URL), - new URI(Defaults.HELLO_URL) - }) { - Locator locator = new AAFLocator(si, uri); - try { - connectTest(locator, uri); - } catch (Exception e) { - e.printStackTrace(); - System.err.flush(); - } - } + for(URI uri : new URI[] { + serviceURI, + new URI(Defaults.OAUTH2_TOKEN_URL), + new URI(Defaults.OAUTH2_INTROSPECT_URL), + new URI(Defaults.CM_URL), + new URI(Defaults.GUI_URL), + new URI(Defaults.FS_URL), + new URI(Defaults.HELLO_URL) + }) { + Locator locator = new AAFLocator(si, uri); + try { + connectTest(locator, uri); + } catch (Exception e) { + e.printStackTrace(); + System.err.flush(); + } + } - ///////// - print(true,"Test Service for Perms driven by AAFLocator"); - Locator locator = new AAFLocator(si,serviceURI); - for(SecuritySetter ss : lss) { - permTest(locator,ss); - } + ///////// + print(true,"Test Service for Perms driven by AAFLocator"); + Locator locator = new AAFLocator(si,serviceURI); + for(SecuritySetter ss : lss) { + permTest(locator,ss); + } - ////////// - print(true,"Test essential BasicAuth Service call, driven by AAFLocator"); - for(SecuritySetter ss : lss) { - if(ss instanceof HBasicAuthSS) { - basicAuthTest(new AAFLocator(si, serviceURI),ss); - } - } - - } catch(Exception e) { - e.printStackTrace(System.err); - } finally { - print(true,"END OF TESTS"); - } - } - } - - private static List> loadSetters(PropAccess access, SecurityInfoC si) { - print(true,"Load Security Setters from Configuration Information"); - String user = access.getProperty(Config.AAF_APPID); + ////////// + print(true,"Test essential BasicAuth Service call, driven by AAFLocator"); + for(SecuritySetter ss : lss) { + if(ss instanceof HBasicAuthSS) { + basicAuthTest(new AAFLocator(si, serviceURI),ss); + } + } + + } catch(Exception e) { + e.printStackTrace(System.err); + } finally { + print(true,"END OF TESTS"); + } + } + } + + private static List> loadSetters(PropAccess access, SecurityInfoC si) { + print(true,"Load Security Setters from Configuration Information"); + String user = access.getProperty(Config.AAF_APPID); - ArrayList> lss = new ArrayList<>(); - + ArrayList> lss = new ArrayList<>(); + - try { - HBasicAuthSS hbass = new HBasicAuthSS(si,true); - if(hbass==null || hbass.getID()==null) { - access.log(Level.INFO, "BasicAuth Information is not available in configuration, BasicAuth tests will not be conducted... Continuing"); - } else { - access.log(Level.INFO, "BasicAuth Information found with ID",hbass.getID(),". BasicAuth tests will be performed."); - lss.add(hbass); - } - } catch (Exception e) { - access.log(Level.INFO, "BasicAuth Security Setter constructor threw exception: \"",e.getMessage(),"\". BasicAuth tests will not be performed"); - } + try { + HBasicAuthSS hbass = new HBasicAuthSS(si,true); + if(hbass==null || hbass.getID()==null) { + access.log(Level.INFO, "BasicAuth Information is not available in configuration, BasicAuth tests will not be conducted... Continuing"); + } else { + access.log(Level.INFO, "BasicAuth Information found with ID",hbass.getID(),". BasicAuth tests will be performed."); + lss.add(hbass); + } + } catch (Exception e) { + access.log(Level.INFO, "BasicAuth Security Setter constructor threw exception: \"",e.getMessage(),"\". BasicAuth tests will not be performed"); + } - try { - HX509SS hxss = new HX509SS(user,si); - if(hxss==null || hxss.getID()==null) { - access.log(Level.INFO, "X509 (Client certificate) Information is not available in configuration, X509 tests will not be conducted... Continuing"); - } else { - access.log(Level.INFO, "X509 (Client certificate) Information found with ID",hxss.getID(),". X509 tests will be performed."); - lss.add(hxss); - } - } catch (Exception e) { - access.log(Level.INFO, "X509 (Client certificate) Security Setter constructor threw exception: \"",e.getMessage(),"\". X509 tests will not be performed"); - } + try { + HX509SS hxss = new HX509SS(user,si); + if(hxss==null || hxss.getID()==null) { + access.log(Level.INFO, "X509 (Client certificate) Information is not available in configuration, X509 tests will not be conducted... Continuing"); + } else { + access.log(Level.INFO, "X509 (Client certificate) Information found with ID",hxss.getID(),". X509 tests will be performed."); + lss.add(hxss); + } + } catch (Exception e) { + access.log(Level.INFO, "X509 (Client certificate) Security Setter constructor threw exception: \"",e.getMessage(),"\". X509 tests will not be performed"); + } - String tokenURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL); - String locateURL=access.getProperty(Config.AAF_LOCATE_URL); - if(tokenURL==null || (tokenURL.contains("/locate/") && locateURL!=null)) { - tokenURL=Defaults.OAUTH2_TOKEN_URL+"/token"; - } + String tokenURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL); + String locateURL=access.getProperty(Config.AAF_LOCATE_URL); + if(tokenURL==null || (tokenURL.contains("/locate/") && locateURL!=null)) { + tokenURL=Defaults.OAUTH2_TOKEN_URL+"/token"; + } - try { - HRenewingTokenSS hrtss = new HRenewingTokenSS(access, tokenURL); - access.log(Level.INFO, "AAF OAUTH2 Information found with ID",hrtss.getID(),". AAF OAUTH2 tests will be performed."); - lss.add(hrtss); - } catch (Exception e) { - access.log(Level.INFO, "AAF OAUTH2 Security Setter constructor threw exception: \"",e.getMessage(),"\". AAF OAUTH2 tests will not be conducted... Continuing"); - } - - tokenURL = access.getProperty(Config.AAF_ALT_OAUTH2_TOKEN_URL); - if(tokenURL==null) { - access.log(Level.INFO, "AAF Alternative OAUTH2 requires",Config.AAF_ALT_OAUTH2_TOKEN_URL, "OAuth2 tests to", tokenURL, "will not be conducted... Continuing"); - } else { - try { - HRenewingTokenSS hrtss = new HRenewingTokenSS(access, tokenURL); - access.log(Level.INFO, "ALT OAUTH2 Information found with ID",hrtss.getID(),". ALT OAUTH2 tests will be performed."); - lss.add(hrtss); - } catch (Exception e) { - access.log(Level.INFO, "ALT OAUTH2 Security Setter constructor threw exception: \"",e.getMessage(),"\". ALT OAuth2 tests to", tokenURL, " will not be conducted... Continuing"); - } - } - - return lss; - } + try { + HRenewingTokenSS hrtss = new HRenewingTokenSS(access, tokenURL); + access.log(Level.INFO, "AAF OAUTH2 Information found with ID",hrtss.getID(),". AAF OAUTH2 tests will be performed."); + lss.add(hrtss); + } catch (Exception e) { + access.log(Level.INFO, "AAF OAUTH2 Security Setter constructor threw exception: \"",e.getMessage(),"\". AAF OAUTH2 tests will not be conducted... Continuing"); + } + + tokenURL = access.getProperty(Config.AAF_ALT_OAUTH2_TOKEN_URL); + if(tokenURL==null) { + access.log(Level.INFO, "AAF Alternative OAUTH2 requires",Config.AAF_ALT_OAUTH2_TOKEN_URL, "OAuth2 tests to", tokenURL, "will not be conducted... Continuing"); + } else { + try { + HRenewingTokenSS hrtss = new HRenewingTokenSS(access, tokenURL); + access.log(Level.INFO, "ALT OAUTH2 Information found with ID",hrtss.getID(),". ALT OAUTH2 tests will be performed."); + lss.add(hrtss); + } catch (Exception e) { + access.log(Level.INFO, "ALT OAUTH2 Security Setter constructor threw exception: \"",e.getMessage(),"\". ALT OAuth2 tests to", tokenURL, " will not be conducted... Continuing"); + } + } + + return lss; + } - private static void print(Boolean strong, String ... args) { - PrintStream out = System.out; - out.println(); - if(strong) { - for(int i=0;i<70;++i) { - out.print('='); - } - out.println(); - } - for(String s : args) { - out.print(strong?"== ":"------ "); - out.print(s); - if(!strong) { - out.print(" ------"); - } - out.println(); - } - if(strong) { - for(int i=0;i<70;++i) { - out.print('='); - } - } - out.println(); - } + private static void print(Boolean strong, String ... args) { + PrintStream out = System.out; + out.println(); + if(strong) { + for(int i=0;i<70;++i) { + out.print('='); + } + out.println(); + } + for(String s : args) { + out.print(strong?"== ":"------ "); + out.print(s); + if(!strong) { + out.print(" ------"); + } + out.println(); + } + if(strong) { + for(int i=0;i<70;++i) { + out.print('='); + } + } + out.println(); + } - private static void connectTest(Locator dl, URI locatorURI) throws LocatorException { - URI uri; - Socket socket; - print(false,"TCP/IP Connect test to all Located Services for " + locatorURI.toString() ); - for(Item li = dl.first();li!=null;li=dl.next(li)) { - if((uri = dl.get(li)) == null) { - System.out.println("Locator Item empty"); - } else { - socket = new Socket(); - try { - try { - socket.connect(new InetSocketAddress(uri.getHost(), uri.getPort()),3000); - System.out.printf("Can Connect a Socket to %s %d\n",uri.getHost(),uri.getPort()); - } catch (IOException e) { - System.out.printf("Cannot Connect a Socket to %s %d: %s\n",uri.getHost(),uri.getPort(),e.getMessage()); - } - } finally { - try { - socket.close(); - } catch (IOException e1) { - System.out.printf("Could not close Socket Connection: %s\n",e1.getMessage()); - } - } - } - } - } + private static void connectTest(Locator dl, URI locatorURI) throws LocatorException { + URI uri; + Socket socket; + print(false,"TCP/IP Connect test to all Located Services for " + locatorURI.toString() ); + for(Item li = dl.first();li!=null;li=dl.next(li)) { + if((uri = dl.get(li)) == null) { + System.out.println("Locator Item empty"); + } else { + socket = new Socket(); + try { + try { + socket.connect(new InetSocketAddress(uri.getHost(), uri.getPort()),3000); + System.out.printf("Can Connect a Socket to %s %d\n",uri.getHost(),uri.getPort()); + } catch (IOException e) { + System.out.printf("Cannot Connect a Socket to %s %d: %s\n",uri.getHost(),uri.getPort(),e.getMessage()); + } + } finally { + try { + socket.close(); + } catch (IOException e1) { + System.out.printf("Could not close Socket Connection: %s\n",e1.getMessage()); + } + } + } + } + } - private static void permTest(Locator dl, SecuritySetter ss) { - try { - URI uri = dl.get(dl.best()); - if(uri==null) { - System.out.print("No URI available using " + ss.getClass().getSimpleName()); - System.out.println(); - return; - } else { - System.out.print("Resolved to: " + uri + " using " + ss.getClass().getSimpleName()); - } - if(ss instanceof HRenewingTokenSS) { - System.out.println(" " + ((HRenewingTokenSS)ss).tokenURL()); - } else { - System.out.println(); - } - HClient client = new HClient(ss, uri, 3000); - client.setMethod("GET"); - String user = ss.getID(); - if(user.indexOf('@')<0) { - user+="@isam.att.com"; - } - client.setPathInfo("/authz/perms/user/"+user); - client.send(); - Future future = client.futureReadString(); - if(future.get(7000)) { - System.out.println(future.body()); - } else { - if(future.code()==401 && ss instanceof HX509SS) { - System.out.println(" Authentication denied with 401 for Certificate.\n\t" - + "This means Certificate isn't valid for this environment, and has attempted another method of Authentication"); - } else { - System.out.println(future.code() + ":" + future.body()); - } - } - } catch (CadiException | LocatorException | APIException e) { - e.printStackTrace(); - } - } + private static void permTest(Locator dl, SecuritySetter ss) { + try { + URI uri = dl.get(dl.best()); + if(uri==null) { + System.out.print("No URI available using " + ss.getClass().getSimpleName()); + System.out.println(); + return; + } else { + System.out.print("Resolved to: " + uri + " using " + ss.getClass().getSimpleName()); + } + if(ss instanceof HRenewingTokenSS) { + System.out.println(" " + ((HRenewingTokenSS)ss).tokenURL()); + } else { + System.out.println(); + } + HClient client = new HClient(ss, uri, 3000); + client.setMethod("GET"); + String user = ss.getID(); + if(user.indexOf('@')<0) { + user+="@isam.att.com"; + } + client.setPathInfo("/authz/perms/user/"+user); + client.send(); + Future future = client.futureReadString(); + if(future.get(7000)) { + System.out.println(future.body()); + } else { + if(future.code()==401 && ss instanceof HX509SS) { + System.out.println(" Authentication denied with 401 for Certificate.\n\t" + + "This means Certificate isn't valid for this environment, and has attempted another method of Authentication"); + } else { + System.out.println(future.code() + ":" + future.body()); + } + } + } catch (CadiException | LocatorException | APIException e) { + e.printStackTrace(); + } + } - private static void basicAuthTest(Locator dl, SecuritySetter ss) { - try { - URI uri = dl.get(dl.best()); - System.out.println("Resolved to: " + uri); - HClient client = new HClient(ss, uri, 3000); - client.setMethod("GET"); - client.setPathInfo("/authn/basicAuth"); - client.addHeader("Accept", "text/plain"); - client.send(); - - - Future future = client.futureReadString(); - if(future.get(7000)) { - System.out.println("BasicAuth Validated"); - } else { - System.out.println("Failure " + future.code() + ":" + future.body()); - } - } catch (CadiException | LocatorException | APIException e) { - e.printStackTrace(); - } - } + private static void basicAuthTest(Locator dl, SecuritySetter ss) { + try { + URI uri = dl.get(dl.best()); + System.out.println("Resolved to: " + uri); + HClient client = new HClient(ss, uri, 3000); + client.setMethod("GET"); + client.setPathInfo("/authn/basicAuth"); + client.addHeader("Accept", "text/plain"); + client.send(); + + + Future future = client.futureReadString(); + if(future.get(7000)) { + System.out.println("BasicAuth Validated"); + } else { + System.out.println("Failure " + future.code() + ":" + future.body()); + } + } catch (CadiException | LocatorException | APIException e) { + e.printStackTrace(); + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java index abd1c40f..dd8b1262 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java @@ -55,122 +55,122 @@ import aaf.v2_0.Users; import aaf.v2_0.Users.User; public class AAFListedCertIdentity implements CertIdentity { - //TODO should 8 hours be configurable? - private static final long EIGHT_HOURS = 1000*60*60*8L; - - private static Map certs = null; - - // Did this to add other Trust Mechanisms - // Trust mechanism set by Property: - private static final String[] authMechanisms = new String[] {"tguard","basicAuth","csp"}; - private static String[] certIDs; - - private static Map> trusted =null; + //TODO should 8 hours be configurable? + private static final long EIGHT_HOURS = 1000*60*60*8L; + + private static Map certs = null; + + // Did this to add other Trust Mechanisms + // Trust mechanism set by Property: + private static final String[] authMechanisms = new String[] {"tguard","basicAuth","csp"}; + private static String[] certIDs; + + private static Map> trusted =null; - public AAFListedCertIdentity(Access access, AAFCon aafcon) throws APIException { - synchronized(AAFListedCertIdentity.class) { - if(certIDs==null) { - String cip = access.getProperty(Config.AAF_CERT_IDS, null); - if(cip!=null) { - certIDs = Split.split(',',cip); - } - } - if(certIDs!=null && certs==null) { - TimerTask cu = new CertUpdate(aafcon); - cu.run(); // want this to run in this thread first... - new Timer("AAF Identity Refresh Timer",true).scheduleAtFixedRate(cu, EIGHT_HOURS,EIGHT_HOURS); - } - } - } + public AAFListedCertIdentity(Access access, AAFCon aafcon) throws APIException { + synchronized(AAFListedCertIdentity.class) { + if(certIDs==null) { + String cip = access.getProperty(Config.AAF_CERT_IDS, null); + if(cip!=null) { + certIDs = Split.split(',',cip); + } + } + if(certIDs!=null && certs==null) { + TimerTask cu = new CertUpdate(aafcon); + cu.run(); // want this to run in this thread first... + new Timer("AAF Identity Refresh Timer",true).scheduleAtFixedRate(cu, EIGHT_HOURS,EIGHT_HOURS); + } + } + } - public static Set trusted(String authMech) { - return trusted.get(authMech); - } - - public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] certBytes) throws CertificateException { - if(cert==null && certBytes==null)return null; - if(certBytes==null)certBytes = cert.getEncoded(); - byte[] fingerprint = X509Taf.getFingerPrint(certBytes); - String id = certs.get(new ByteArrayHolder(fingerprint)); - if(id!=null) { // Caller is Validated - return new X509Principal(id,cert,certBytes,null); - } - return null; - } + public static Set trusted(String authMech) { + return trusted.get(authMech); + } + + public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] certBytes) throws CertificateException { + if(cert==null && certBytes==null)return null; + if(certBytes==null)certBytes = cert.getEncoded(); + byte[] fingerprint = X509Taf.getFingerPrint(certBytes); + String id = certs.get(new ByteArrayHolder(fingerprint)); + if(id!=null) { // Caller is Validated + return new X509Principal(id,cert,certBytes,null); + } + return null; + } - private static class ByteArrayHolder implements Comparable { - private byte[] ba; - public ByteArrayHolder(byte[] ba) { - this.ba = ba; - } - public int compareTo(ByteArrayHolder b) { - return Hash.compareTo(ba, b.ba); - } - } - - private class CertUpdate extends TimerTask { + private static class ByteArrayHolder implements Comparable { + private byte[] ba; + public ByteArrayHolder(byte[] ba) { + this.ba = ba; + } + public int compareTo(ByteArrayHolder b) { + return Hash.compareTo(ba, b.ba); + } + } + + private class CertUpdate extends TimerTask { - private AAFCon aafcon; - public CertUpdate(AAFCon con) { - aafcon = con; - } - - @Override - public void run() { - try { - TreeMap newCertsMap = new TreeMap<>(); - Map> newTrustMap = new TreeMap<>(); - Set userLookup = new HashSet<>(); - for(String s : certIDs) { - userLookup.add(s); - } - for(String authMech : authMechanisms) { - Future fusr = aafcon.client(Config.AAF_DEFAULT_VERSION).read("/authz/users/perm/com.att.aaf.trust/"+authMech+"/authenticate", Users.class, aafcon.usersDF); - if(fusr.get(5000)) { - List users = fusr.value.getUser(); - if(users.isEmpty()) { - aafcon.access.log(Level.WARN, "AAF Lookup-No IDs in Role com.att.aaf.trustForID <> "+authMech); - } else { - aafcon.access.log(Level.INFO,"Loading Trust Authentication Info for",authMech); - Set hsUser = new HashSet<>(); - for(User u : users) { - userLookup.add(u.getId()); - hsUser.add(u.getId()); - } - newTrustMap.put(authMech,hsUser); - } - } else { - aafcon.access.log(Level.WARN, "Could not get Users in Perm com.att.trust|tguard|authenticate",fusr.code(),fusr.body()); - } - - } - - for(String u : userLookup) { - Future fc = aafcon.client(Config.AAF_DEFAULT_VERSION).read("/authn/cert/id/"+u, Certs.class, aafcon.certsDF); - XMLGregorianCalendar now = Chrono.timeStamp(); - if(fc.get(5000)) { - List certs = fc.value.getCert(); - if(certs.isEmpty()) { - aafcon.access.log(Level.WARN, "No Cert Associations for",u); - } else { - for(Cert c : fc.value.getCert()) { - XMLGregorianCalendar then =c.getExpires(); - if(then !=null && then.compare(now)>0) { - newCertsMap.put(new ByteArrayHolder(c.getFingerprint()), c.getId()); - aafcon.access.log(Level.INIT,"Associating "+ c.getId() + " expiring " + Chrono.dateOnlyStamp(c.getExpires()) + " with " + c.getX500()); - } - } - } - } else { - aafcon.access.log(Level.WARN, "Could not get Certificates for",u); - } - } + private AAFCon aafcon; + public CertUpdate(AAFCon con) { + aafcon = con; + } + + @Override + public void run() { + try { + TreeMap newCertsMap = new TreeMap<>(); + Map> newTrustMap = new TreeMap<>(); + Set userLookup = new HashSet<>(); + for(String s : certIDs) { + userLookup.add(s); + } + for(String authMech : authMechanisms) { + Future fusr = aafcon.client(Config.AAF_DEFAULT_VERSION).read("/authz/users/perm/com.att.aaf.trust/"+authMech+"/authenticate", Users.class, aafcon.usersDF); + if(fusr.get(5000)) { + List users = fusr.value.getUser(); + if(users.isEmpty()) { + aafcon.access.log(Level.WARN, "AAF Lookup-No IDs in Role com.att.aaf.trustForID <> "+authMech); + } else { + aafcon.access.log(Level.INFO,"Loading Trust Authentication Info for",authMech); + Set hsUser = new HashSet<>(); + for(User u : users) { + userLookup.add(u.getId()); + hsUser.add(u.getId()); + } + newTrustMap.put(authMech,hsUser); + } + } else { + aafcon.access.log(Level.WARN, "Could not get Users in Perm com.att.trust|tguard|authenticate",fusr.code(),fusr.body()); + } + + } + + for(String u : userLookup) { + Future fc = aafcon.client(Config.AAF_DEFAULT_VERSION).read("/authn/cert/id/"+u, Certs.class, aafcon.certsDF); + XMLGregorianCalendar now = Chrono.timeStamp(); + if(fc.get(5000)) { + List certs = fc.value.getCert(); + if(certs.isEmpty()) { + aafcon.access.log(Level.WARN, "No Cert Associations for",u); + } else { + for(Cert c : fc.value.getCert()) { + XMLGregorianCalendar then =c.getExpires(); + if(then !=null && then.compare(now)>0) { + newCertsMap.put(new ByteArrayHolder(c.getFingerprint()), c.getId()); + aafcon.access.log(Level.INIT,"Associating "+ c.getId() + " expiring " + Chrono.dateOnlyStamp(c.getExpires()) + " with " + c.getX500()); + } + } + } + } else { + aafcon.access.log(Level.WARN, "Could not get Certificates for",u); + } + } - certs = newCertsMap; - trusted = newTrustMap; - } catch(Exception e) { - aafcon.access.log(e, "Failure to update Certificate Identities from AAF"); - } - } - } + certs = newCertsMap; + trusted = newTrustMap; + } catch(Exception e) { + aafcon.access.log(e, "Failure to update Certificate Identities from AAF"); + } + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java index 0fb4d60d..e878d740 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java @@ -33,64 +33,64 @@ import org.onap.aaf.misc.rosetta.env.RosettaEnv; import aaf.v2_0.Error; public class ErrMessage { - private RosettaDF errDF; - - public ErrMessage(RosettaEnv env) throws APIException { - errDF = env.newDataFactory(Error.class); - } + private RosettaDF errDF; + + public ErrMessage(RosettaEnv env) throws APIException { + errDF = env.newDataFactory(Error.class); + } - /** - * AT&T Requires a specific Error Format for RESTful Services, which AAF complies with. - * - * This code will create a meaningful string from this format. - * - * @param ps - * @param df - * @param r - * @throws APIException - */ - public void printErr(PrintStream ps, String attErrJson) throws APIException { - StringBuilder sb = new StringBuilder(); - Error err = errDF.newData().in(TYPE.JSON).load(attErrJson).asObject(); - ps.println(toMsg(sb,err)); - } - - /** - * AT&T Requires a specific Error Format for RESTful Services, which AAF complies with. - * - * This code will create a meaningful string from this format. - * - * @param sb - * @param df - * @param r - * @throws APIException - */ - public StringBuilder toMsg(StringBuilder sb, String attErrJson) throws APIException { - return toMsg(sb,errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()); - } - - public StringBuilder toMsg(Future future) { - return toMsg(new StringBuilder(),future); - } - - public StringBuilder toMsg(StringBuilder sb, Future future) { - try { - toMsg(sb,errDF.newData().in(TYPE.JSON).load(future.body()).asObject()); - } catch(Exception e) { - //just print what we can - sb.append(future.code()); - sb.append(": "); - sb.append(future.body()); - } - return sb; - } + /** + * AT&T Requires a specific Error Format for RESTful Services, which AAF complies with. + * + * This code will create a meaningful string from this format. + * + * @param ps + * @param df + * @param r + * @throws APIException + */ + public void printErr(PrintStream ps, String attErrJson) throws APIException { + StringBuilder sb = new StringBuilder(); + Error err = errDF.newData().in(TYPE.JSON).load(attErrJson).asObject(); + ps.println(toMsg(sb,err)); + } + + /** + * AT&T Requires a specific Error Format for RESTful Services, which AAF complies with. + * + * This code will create a meaningful string from this format. + * + * @param sb + * @param df + * @param r + * @throws APIException + */ + public StringBuilder toMsg(StringBuilder sb, String attErrJson) throws APIException { + return toMsg(sb,errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()); + } + + public StringBuilder toMsg(Future future) { + return toMsg(new StringBuilder(),future); + } + + public StringBuilder toMsg(StringBuilder sb, Future future) { + try { + toMsg(sb,errDF.newData().in(TYPE.JSON).load(future.body()).asObject()); + } catch(Exception e) { + //just print what we can + sb.append(future.code()); + sb.append(": "); + sb.append(future.body()); + } + return sb; + } - public StringBuilder toMsg(StringBuilder sb, Error err) { - sb.append(err.getMessageId()); - sb.append(' '); - String[] vars = new String[err.getVariables().size()]; - err.getVariables().toArray(vars); - Vars.convert(sb, err.getText(),vars); - return sb; - } + public StringBuilder toMsg(StringBuilder sb, Error err) { + sb.append(err.getMessageId()); + sb.append(' '); + String[] vars = new String[err.getVariables().size()]; + err.getVariables().toArray(vars); + Vars.convert(sb, err.getText(),vars); + return sb; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java index c55d3b37..0cf48de6 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java @@ -58,397 +58,397 @@ import aaf.v2_0.Users; import aaf.v2_0.Users.User; public class Examples { - public static String print(RosettaEnv env, String nameOrContentType, boolean optional) throws APIException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { - // Discover ClassName - String className = null; - String version = null; - TYPE type = TYPE.JSON; // default - if(nameOrContentType.startsWith("application/")) { - for(String ct : nameOrContentType.split("\\s*,\\s*")) { - for(String elem : ct.split("\\s*;\\s*")) { - if(elem.endsWith("+json")) { - type = TYPE.JSON; - className = elem.substring(elem.indexOf('/')+1, elem.length()-5); - } else if(elem.endsWith("+xml")) { - type = TYPE.XML; - className = elem.substring(elem.indexOf('/')+1, elem.length()-4); - } else if(elem.startsWith("version=")) { - version = elem.substring(8); - } - } - if(className!=null && version!=null) - break; - } - if(className==null) { - throw new APIException(nameOrContentType + " does not contain Class Information"); - } - } else { - className = nameOrContentType; - } - - // No Void.class in aaf.v2_0 package causing errors when trying to use a newVoidv2_0 - // method similar to others in this class. This makes it work, but is it right? - if ("Void".equals(className)) - return ""; - - if("1.1".equals(version)) { - version = "v1_0"; - } else if(version!=null) { - version = "v" + version.replace('.', '_'); - } else { - version = "v2_0"; - } - - Class cls; - try { - cls = Examples.class.getClassLoader().loadClass("aaf."+version+'.'+className); - } catch (ClassNotFoundException e) { - throw new APIException(e); - } - - Method meth; - try { - meth = Examples.class.getDeclaredMethod("new"+cls.getSimpleName()+version,boolean.class); - } catch (Exception e) { - throw new APIException("ERROR: " + cls.getName() + " does not have an Example in Code. Request from AAF Developers"); - } - - RosettaDF df = env.newDataFactory(cls); - df.option(Data.PRETTY); - - Object data = meth.invoke(null,optional); - - @SuppressWarnings("unchecked") - String rv = df.newData().load((C)data).out(type).asString(); -// Object obj = df.newData().in(type).load(rv).asObject(); - return rv; - } - - /* - * Set Base Class Request (easier than coding over and over) - */ - private static void setOptional(Request req) { - GregorianCalendar gc = new GregorianCalendar(); - req.setStart(Chrono.timeStamp(gc)); - gc.add(GregorianCalendar.MONTH, 6); - req.setEnd(Chrono.timeStamp(gc)); -// req.setForce("false"); - - } - - @SuppressWarnings("unused") - private static Request newRequestv2_0(boolean optional) { - Request r = new Request(); - setOptional(r); - return r; - } - @SuppressWarnings("unused") - private static RolePermRequest newRolePermRequestv2_0(boolean optional) { - RolePermRequest rpr = new RolePermRequest(); - Pkey pkey = new Pkey(); - pkey.setType("org.osaaf.myns.mytype"); - pkey.setInstance("myInstance"); - pkey.setAction("myAction"); - rpr.setPerm(pkey); - rpr.setRole("org.osaaf.myns.myrole"); - if(optional)setOptional(rpr); - return rpr; - } - - @SuppressWarnings("unused") - private static Roles newRolesv2_0(boolean optional) { - Role r; - Pkey p; - Roles rs = new Roles(); + public static String print(RosettaEnv env, String nameOrContentType, boolean optional) throws APIException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { + // Discover ClassName + String className = null; + String version = null; + TYPE type = TYPE.JSON; // default + if(nameOrContentType.startsWith("application/")) { + for(String ct : nameOrContentType.split("\\s*,\\s*")) { + for(String elem : ct.split("\\s*;\\s*")) { + if(elem.endsWith("+json")) { + type = TYPE.JSON; + className = elem.substring(elem.indexOf('/')+1, elem.length()-5); + } else if(elem.endsWith("+xml")) { + type = TYPE.XML; + className = elem.substring(elem.indexOf('/')+1, elem.length()-4); + } else if(elem.startsWith("version=")) { + version = elem.substring(8); + } + } + if(className!=null && version!=null) + break; + } + if(className==null) { + throw new APIException(nameOrContentType + " does not contain Class Information"); + } + } else { + className = nameOrContentType; + } + + // No Void.class in aaf.v2_0 package causing errors when trying to use a newVoidv2_0 + // method similar to others in this class. This makes it work, but is it right? + if ("Void".equals(className)) + return ""; + + if("1.1".equals(version)) { + version = "v1_0"; + } else if(version!=null) { + version = "v" + version.replace('.', '_'); + } else { + version = "v2_0"; + } + + Class cls; + try { + cls = Examples.class.getClassLoader().loadClass("aaf."+version+'.'+className); + } catch (ClassNotFoundException e) { + throw new APIException(e); + } + + Method meth; + try { + meth = Examples.class.getDeclaredMethod("new"+cls.getSimpleName()+version,boolean.class); + } catch (Exception e) { + throw new APIException("ERROR: " + cls.getName() + " does not have an Example in Code. Request from AAF Developers"); + } + + RosettaDF df = env.newDataFactory(cls); + df.option(Data.PRETTY); + + Object data = meth.invoke(null,optional); + + @SuppressWarnings("unchecked") + String rv = df.newData().load((C)data).out(type).asString(); +// Object obj = df.newData().in(type).load(rv).asObject(); + return rv; + } + + /* + * Set Base Class Request (easier than coding over and over) + */ + private static void setOptional(Request req) { + GregorianCalendar gc = new GregorianCalendar(); + req.setStart(Chrono.timeStamp(gc)); + gc.add(GregorianCalendar.MONTH, 6); + req.setEnd(Chrono.timeStamp(gc)); +// req.setForce("false"); + + } + + @SuppressWarnings("unused") + private static Request newRequestv2_0(boolean optional) { + Request r = new Request(); + setOptional(r); + return r; + } + @SuppressWarnings("unused") + private static RolePermRequest newRolePermRequestv2_0(boolean optional) { + RolePermRequest rpr = new RolePermRequest(); + Pkey pkey = new Pkey(); + pkey.setType("org.osaaf.myns.mytype"); + pkey.setInstance("myInstance"); + pkey.setAction("myAction"); + rpr.setPerm(pkey); + rpr.setRole("org.osaaf.myns.myrole"); + if(optional)setOptional(rpr); + return rpr; + } + + @SuppressWarnings("unused") + private static Roles newRolesv2_0(boolean optional) { + Role r; + Pkey p; + Roles rs = new Roles(); r = new Role(); - rs.getRole().add(r); - r.setName("org.osaaf.myns.myRole"); + rs.getRole().add(r); + r.setName("org.osaaf.myns.myRole"); p = new Pkey(); - r.getPerms().add(p); - p.setType("org.osaaf.myns.myType"); - p.setInstance("myInstance"); - p.setAction("myAction"); + r.getPerms().add(p); + p.setType("org.osaaf.myns.myType"); + p.setInstance("myInstance"); + p.setAction("myAction"); p = new Pkey(); - r.getPerms().add(p); - p.setType("org.osaaf.myns.myType"); - p.setInstance("myInstance"); - p.setAction("myOtherAction"); + r.getPerms().add(p); + p.setType("org.osaaf.myns.myType"); + p.setInstance("myInstance"); + p.setAction("myOtherAction"); r = new Role(); - rs.getRole().add(r); - r.setName("org.osaaf.myns.myOtherRole"); + rs.getRole().add(r); + r.setName("org.osaaf.myns.myOtherRole"); p = new Pkey(); - r.getPerms().add(p); - p.setType("org.osaaf.myns.myOtherType"); - p.setInstance("myInstance"); - p.setAction("myAction"); + r.getPerms().add(p); + p.setType("org.osaaf.myns.myOtherType"); + p.setInstance("myInstance"); + p.setAction("myAction"); p = new Pkey(); - r.getPerms().add(p); - p.setType("org.osaaf.myns.myOthertype"); - p.setInstance("myInstance"); - p.setAction("myOtherAction"); + r.getPerms().add(p); + p.setType("org.osaaf.myns.myOthertype"); + p.setInstance("myInstance"); + p.setAction("myOtherAction"); - return rs; - } - - - @SuppressWarnings("unused") - private static PermRequest newPermRequestv2_0(boolean optional) { - PermRequest pr = new PermRequest(); - pr.setType("org.osaaf.myns.myType"); - pr.setInstance("myInstance"); - pr.setAction("myAction"); - if(optional) { - pr.setDescription("Short and meaningful verbiage about the Permission"); - - setOptional(pr); - } - return pr; - } - - @SuppressWarnings("unused") - private static Perm newPermv2_0(boolean optional) { - Perm pr = new Perm(); - pr.setType("org.osaaf.myns.myType"); - pr.setInstance("myInstance"); - pr.setAction("myAction"); - pr.getRoles().add("org.osaaf.aaf.myRole"); - pr.getRoles().add("org.osaaf.aaf.myRole2"); - pr.setDescription("This is my description, and I'm sticking with it"); - if(optional) { - pr.setDescription("Short and meaningful verbiage about the Permission"); - } - return pr; - } + return rs; + } + + + @SuppressWarnings("unused") + private static PermRequest newPermRequestv2_0(boolean optional) { + PermRequest pr = new PermRequest(); + pr.setType("org.osaaf.myns.myType"); + pr.setInstance("myInstance"); + pr.setAction("myAction"); + if(optional) { + pr.setDescription("Short and meaningful verbiage about the Permission"); + + setOptional(pr); + } + return pr; + } + + @SuppressWarnings("unused") + private static Perm newPermv2_0(boolean optional) { + Perm pr = new Perm(); + pr.setType("org.osaaf.myns.myType"); + pr.setInstance("myInstance"); + pr.setAction("myAction"); + pr.getRoles().add("org.osaaf.aaf.myRole"); + pr.getRoles().add("org.osaaf.aaf.myRole2"); + pr.setDescription("This is my description, and I'm sticking with it"); + if(optional) { + pr.setDescription("Short and meaningful verbiage about the Permission"); + } + return pr; + } - @SuppressWarnings("unused") - private static PermKey newPermKeyv2_0(boolean optional) { - PermKey pr = new PermKey(); - pr.setType("org.osaaf.myns.myType"); - pr.setInstance("myInstance"); - pr.setAction("myAction"); - return pr; - } - - @SuppressWarnings("unused") - private static Perms newPermsv2_0(boolean optional) { - Perms perms = new Perms(); - Perm p=new Perm(); - perms.getPerm().add(p); - p.setType("org.osaaf.myns.myType"); - p.setInstance("myInstance"); - p.setAction("myAction"); - p.getRoles().add("org.osaaf.myns.myRole"); - p.getRoles().add("org.osaaf.myns.myRole2"); + @SuppressWarnings("unused") + private static PermKey newPermKeyv2_0(boolean optional) { + PermKey pr = new PermKey(); + pr.setType("org.osaaf.myns.myType"); + pr.setInstance("myInstance"); + pr.setAction("myAction"); + return pr; + } + + @SuppressWarnings("unused") + private static Perms newPermsv2_0(boolean optional) { + Perms perms = new Perms(); + Perm p=new Perm(); + perms.getPerm().add(p); + p.setType("org.osaaf.myns.myType"); + p.setInstance("myInstance"); + p.setAction("myAction"); + p.getRoles().add("org.osaaf.myns.myRole"); + p.getRoles().add("org.osaaf.myns.myRole2"); p=new Perm(); - perms.getPerm().add(p); - p.setType("org.osaaf.myns.myOtherType"); - p.setInstance("myInstance"); - p.setAction("myOtherAction"); - p.getRoles().add("org.osaaf.myns.myRole"); - p.getRoles().add("org.osaaf.myns.myRole2"); + perms.getPerm().add(p); + p.setType("org.osaaf.myns.myOtherType"); + p.setInstance("myInstance"); + p.setAction("myOtherAction"); + p.getRoles().add("org.osaaf.myns.myRole"); + p.getRoles().add("org.osaaf.myns.myRole2"); - return perms; - - } - - @SuppressWarnings("unused") - private static UserRoleRequest newUserRoleRequestv2_0(boolean optional) { - UserRoleRequest urr = new UserRoleRequest(); - urr.setRole("org.osaaf.myns.myRole"); - urr.setUser("ab1234@people.osaaf.org"); - if(optional) setOptional(urr); - return urr; - } - - @SuppressWarnings("unused") - private static NsRequest newNsRequestv2_0(boolean optional) { - NsRequest nr = new NsRequest(); - nr.setName("org.osaaf.myns"); - nr.getResponsible().add("ab1234@people.osaaf.org"); - nr.getResponsible().add("cd5678@people.osaaf.org"); - nr.getAdmin().add("zy9876@people.osaaf.org"); - nr.getAdmin().add("xw5432@people.osaaf.org"); - if(optional) { - nr.setDescription("This is my Namespace to set up"); - nr.setType("APP"); - setOptional(nr); - } - return nr; - } - - - @SuppressWarnings("unused") - private static Nss newNssv2_0(boolean optional) { - Ns ns; - - Nss nss = new Nss(); - nss.getNs().add(ns = new Nss.Ns()); - ns.setName("org.osaaf.myns"); - ns.getResponsible().add("ab1234@people.osaaf.org"); - ns.getResponsible().add("cd5678@people.osaaf.org"); - ns.getAdmin().add("zy9876@people.osaaf.org"); - ns.getAdmin().add("xw5432@people.osaaf.org"); - ns.setDescription("This is my Namespace to set up"); - - nss.getNs().add(ns = new Nss.Ns()); - ns.setName("org.osaaf.myOtherNs"); - ns.getResponsible().add("ab1234@people.osaaf.org"); - ns.getResponsible().add("cd5678@people.osaaf.org"); - ns.getAdmin().add("zy9876@people.osaaf.org"); - ns.getAdmin().add("xw5432@people.osaaf.org"); - - return nss; - } - @SuppressWarnings("unused") - private static RoleRequest newRoleRequestv2_0(boolean optional) { - RoleRequest rr = new RoleRequest(); - rr.setName("org.osaaf.myns.myRole"); - if(optional) { - rr.setDescription("This is my Role"); - setOptional(rr); - } - return rr; - } + return perms; + + } + + @SuppressWarnings("unused") + private static UserRoleRequest newUserRoleRequestv2_0(boolean optional) { + UserRoleRequest urr = new UserRoleRequest(); + urr.setRole("org.osaaf.myns.myRole"); + urr.setUser("ab1234@people.osaaf.org"); + if(optional) setOptional(urr); + return urr; + } + + @SuppressWarnings("unused") + private static NsRequest newNsRequestv2_0(boolean optional) { + NsRequest nr = new NsRequest(); + nr.setName("org.osaaf.myns"); + nr.getResponsible().add("ab1234@people.osaaf.org"); + nr.getResponsible().add("cd5678@people.osaaf.org"); + nr.getAdmin().add("zy9876@people.osaaf.org"); + nr.getAdmin().add("xw5432@people.osaaf.org"); + if(optional) { + nr.setDescription("This is my Namespace to set up"); + nr.setType("APP"); + setOptional(nr); + } + return nr; + } + + + @SuppressWarnings("unused") + private static Nss newNssv2_0(boolean optional) { + Ns ns; + + Nss nss = new Nss(); + nss.getNs().add(ns = new Nss.Ns()); + ns.setName("org.osaaf.myns"); + ns.getResponsible().add("ab1234@people.osaaf.org"); + ns.getResponsible().add("cd5678@people.osaaf.org"); + ns.getAdmin().add("zy9876@people.osaaf.org"); + ns.getAdmin().add("xw5432@people.osaaf.org"); + ns.setDescription("This is my Namespace to set up"); + + nss.getNs().add(ns = new Nss.Ns()); + ns.setName("org.osaaf.myOtherNs"); + ns.getResponsible().add("ab1234@people.osaaf.org"); + ns.getResponsible().add("cd5678@people.osaaf.org"); + ns.getAdmin().add("zy9876@people.osaaf.org"); + ns.getAdmin().add("xw5432@people.osaaf.org"); + + return nss; + } + @SuppressWarnings("unused") + private static RoleRequest newRoleRequestv2_0(boolean optional) { + RoleRequest rr = new RoleRequest(); + rr.setName("org.osaaf.myns.myRole"); + if(optional) { + rr.setDescription("This is my Role"); + setOptional(rr); + } + return rr; + } - @SuppressWarnings("unused") - private static CredRequest newCredRequestv2_0(boolean optional) { - CredRequest cr = new CredRequest(); - cr.setId("myID@fully.qualified.domain"); - if(optional) { - cr.setType(2); - cr.setEntry("0x125AB256344CE"); - } else { - cr.setPassword("This is my provisioned password"); - } + @SuppressWarnings("unused") + private static CredRequest newCredRequestv2_0(boolean optional) { + CredRequest cr = new CredRequest(); + cr.setId("myID@fully.qualified.domain"); + if(optional) { + cr.setType(2); + cr.setEntry("0x125AB256344CE"); + } else { + cr.setPassword("This is my provisioned password"); + } - return cr; - } - - @SuppressWarnings("unused") - private static Users newUsersv2_0(boolean optional) { - User user; - - Users users = new Users(); + return cr; + } + + @SuppressWarnings("unused") + private static Users newUsersv2_0(boolean optional) { + User user; + + Users users = new Users(); user = new Users.User(); - users.getUser().add(user); - user.setId("ab1234@people.osaaf.org"); - GregorianCalendar gc = new GregorianCalendar(); - user.setExpires(Chrono.timeStamp(gc)); + users.getUser().add(user); + user.setId("ab1234@people.osaaf.org"); + GregorianCalendar gc = new GregorianCalendar(); + user.setExpires(Chrono.timeStamp(gc)); user = new Users.User(); - users.getUser().add(user); - user.setId("zy9876@people.osaaf.org"); - user.setExpires(Chrono.timeStamp(gc)); - - return users; - } + users.getUser().add(user); + user.setId("zy9876@people.osaaf.org"); + user.setExpires(Chrono.timeStamp(gc)); + + return users; + } - @SuppressWarnings("unused") - private static Role newRolev2_0(boolean optional) { - Role r = new Role(); - Pkey p; - r.setName("org.osaaf.myns.myRole"); - r.getPerms().add(p = new Pkey()); - p.setType("org.osaaf.myns.myType"); - p.setInstance("myInstance"); - p.setAction("myAction"); + @SuppressWarnings("unused") + private static Role newRolev2_0(boolean optional) { + Role r = new Role(); + Pkey p; + r.setName("org.osaaf.myns.myRole"); + r.getPerms().add(p = new Pkey()); + p.setType("org.osaaf.myns.myType"); + p.setInstance("myInstance"); + p.setAction("myAction"); return r; } - @SuppressWarnings("unused") - private static RoleKey newRoleKeyv2_0(boolean optional) { - RoleKey r = new RoleKey(); - Pkey p; - r.setName("org.osaaf.myns.myRole"); + @SuppressWarnings("unused") + private static RoleKey newRoleKeyv2_0(boolean optional) { + RoleKey r = new RoleKey(); + Pkey p; + r.setName("org.osaaf.myns.myRole"); return r; } - @SuppressWarnings("unused") - private static Keys newKeysv2_0(boolean optional) { - Keys ks = new Keys(); - ks.getKey().add("Reponse 1"); - ks.getKey().add("Response 2"); + @SuppressWarnings("unused") + private static Keys newKeysv2_0(boolean optional) { + Keys ks = new Keys(); + ks.getKey().add("Reponse 1"); + ks.getKey().add("Response 2"); return ks; } - @SuppressWarnings("unused") - private static UserRoles newUserRolesv2_0(boolean optional) { - UserRoles urs = new UserRoles(); - UserRole ur = new UserRole(); - ur.setUser("xy1234"); - ur.setRole("com.test.myapp.myRole"); - ur.setExpires(Chrono.timeStamp()); - urs.getUserRole().add(ur); - - ur = new UserRole(); - ur.setUser("yx4321"); - ur.setRole("com.test.yourapp.yourRole"); - ur.setExpires(Chrono.timeStamp()); - urs.getUserRole().add(ur); + @SuppressWarnings("unused") + private static UserRoles newUserRolesv2_0(boolean optional) { + UserRoles urs = new UserRoles(); + UserRole ur = new UserRole(); + ur.setUser("xy1234"); + ur.setRole("com.test.myapp.myRole"); + ur.setExpires(Chrono.timeStamp()); + urs.getUserRole().add(ur); + + ur = new UserRole(); + ur.setUser("yx4321"); + ur.setRole("com.test.yourapp.yourRole"); + ur.setExpires(Chrono.timeStamp()); + urs.getUserRole().add(ur); return urs; } - @SuppressWarnings("unused") - private static Approvals newApprovalsv2_0(boolean optional) { - Approvals as = new Approvals(); - Approval a = new Approval(); - a.setApprover("MyApprover"); - a.setId("MyID"); - a.setMemo("My memo (and then some)"); - a.setOperation("MyOperation"); - a.setStatus("MyStatus"); - a.setTicket("MyTicket"); - a.setType("MyType"); - a.setUpdated(Chrono.timeStamp()); - a.setUser("MyUser"); - as.getApprovals().add(a); - a = new Approval(); - a.setApprover("MyApprover2"); - a.setId("MyID2"); - a.setMemo("My memo (and then some)2"); - a.setOperation("MyOperation2"); - a.setStatus("MyStatus2"); - a.setTicket("MyTicket2"); - a.setType("MyType2"); - a.setUpdated(Chrono.timeStamp()); - a.setUser("MyUser2"); - as.getApprovals().add(a); + @SuppressWarnings("unused") + private static Approvals newApprovalsv2_0(boolean optional) { + Approvals as = new Approvals(); + Approval a = new Approval(); + a.setApprover("MyApprover"); + a.setId("MyID"); + a.setMemo("My memo (and then some)"); + a.setOperation("MyOperation"); + a.setStatus("MyStatus"); + a.setTicket("MyTicket"); + a.setType("MyType"); + a.setUpdated(Chrono.timeStamp()); + a.setUser("MyUser"); + as.getApprovals().add(a); + a = new Approval(); + a.setApprover("MyApprover2"); + a.setId("MyID2"); + a.setMemo("My memo (and then some)2"); + a.setOperation("MyOperation2"); + a.setStatus("MyStatus2"); + a.setTicket("MyTicket2"); + a.setType("MyType2"); + a.setUpdated(Chrono.timeStamp()); + a.setUser("MyUser2"); + as.getApprovals().add(a); return as; } - @SuppressWarnings("unused") - private static Approval newApprovalv2_0(boolean optional) { - Approval a = new Approval(); - a.setApprover("MyApprover"); - a.setId("MyID"); - a.setMemo("My memo (and then some)"); - a.setOperation("MyOperation"); - a.setStatus("MyStatus"); - a.setTicket("MyTicket"); - a.setType("MyType"); - a.setUpdated(Chrono.timeStamp()); - a.setUser("MyUser"); + @SuppressWarnings("unused") + private static Approval newApprovalv2_0(boolean optional) { + Approval a = new Approval(); + a.setApprover("MyApprover"); + a.setId("MyID"); + a.setMemo("My memo (and then some)"); + a.setOperation("MyOperation"); + a.setStatus("MyStatus"); + a.setTicket("MyTicket"); + a.setType("MyType"); + a.setUpdated(Chrono.timeStamp()); + a.setUser("MyUser"); return a; } - + - @SuppressWarnings("unused") - private static aaf.v2_0.Error newErrorv2_0(boolean optional) { - aaf.v2_0.Error err = new aaf.v2_0.Error(); - err.setMessageId("SVC1403"); - err.setText("MyText %s, %s: The last three digits are usually the HTTP Code"); - err.getVariables().add("Variable 1"); - err.getVariables().add("Variable 2"); - return err; - } + @SuppressWarnings("unused") + private static aaf.v2_0.Error newErrorv2_0(boolean optional) { + aaf.v2_0.Error err = new aaf.v2_0.Error(); + err.setMessageId("SVC1403"); + err.setText("MyText %s, %s: The last three digits are usually the HTTP Code"); + err.getVariables().add("Variable 1"); + err.getVariables().add("Variable 2"); + return err; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertMarshal.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertMarshal.java index 5ceb082f..eb116490 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertMarshal.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertMarshal.java @@ -31,35 +31,35 @@ import org.onap.aaf.misc.rosetta.marshal.ObjMarshal; import aaf.v2_0.Certs.Cert; public class CertMarshal extends ObjMarshal { - public CertMarshal() { - add(new FieldHexBinary("fingerprint") { - @Override - protected byte[] data(Cert t) { - return t.getFingerprint(); - } - }); + public CertMarshal() { + add(new FieldHexBinary("fingerprint") { + @Override + protected byte[] data(Cert t) { + return t.getFingerprint(); + } + }); - add(new FieldString("id") { - @Override - protected String data(Cert t) { - return t.getId(); - } - }); + add(new FieldString("id") { + @Override + protected String data(Cert t) { + return t.getId(); + } + }); - add(new FieldString("x500") { - @Override - protected String data(Cert t) { - return t.getX500(); - } - }); - - add(new FieldDateTime("expires") { - @Override - protected XMLGregorianCalendar data(Cert t) { - return t.getExpires(); - } - }); + add(new FieldString("x500") { + @Override + protected String data(Cert t) { + return t.getX500(); + } + }); + + add(new FieldDateTime("expires") { + @Override + protected XMLGregorianCalendar data(Cert t) { + return t.getExpires(); + } + }); - } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertsMarshal.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertsMarshal.java index c6e28408..93530793 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertsMarshal.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/marshal/CertsMarshal.java @@ -31,14 +31,14 @@ import aaf.v2_0.Certs.Cert; public class CertsMarshal extends ObjMarshal { - public CertsMarshal() { - add(new ObjArray("cert",new CertMarshal()) { - @Override - protected List data(Certs t) { - return t.getCert(); - } - }); - } + public CertsMarshal() { + add(new ObjArray("cert",new CertMarshal()) { + @Override + protected List data(Certs t) { + return t.getCert(); + } + }); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java index b350e2a7..edacdfdd 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java @@ -34,137 +34,137 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.lur.ConfigPrincipal; public class AAFAuthn extends AbsUserCache { - private AAFCon con; - private String realm; - - /** - * Configure with Standard AAF properties, Stand alone - * @param con - * @throws Exception .. - */ - // Package on purpose - AAFAuthn(AAFCon con) { - super(con.access,con.cleanInterval,con.highCount,con.usageRefreshTriggerCount); - this.con = con; - } + private AAFCon con; + private String realm; + + /** + * Configure with Standard AAF properties, Stand alone + * @param con + * @throws Exception .. + */ + // Package on purpose + AAFAuthn(AAFCon con) { + super(con.access,con.cleanInterval,con.highCount,con.usageRefreshTriggerCount); + this.con = con; + } - /** - * Configure with Standard AAF properties, but share the Cache (with AAF Lur) - * @param con - * @throws Exception - */ - // Package on purpose - AAFAuthn(AAFCon con, AbsUserCache cache) { - super(cache); - this.con = con; - } - - /** - * Return Native Realm of AAF Instance. - * - * @return - */ - public String getRealm() { - return realm; - } + /** + * Configure with Standard AAF properties, but share the Cache (with AAF Lur) + * @param con + * @throws Exception + */ + // Package on purpose + AAFAuthn(AAFCon con, AbsUserCache cache) { + super(cache); + this.con = con; + } + + /** + * Return Native Realm of AAF Instance. + * + * @return + */ + public String getRealm() { + return realm; + } - /** - * Returns null if ok, or an Error String; - * - * Convenience function. Passes "null" for State object - */ - public String validate(String user, String password) throws IOException { - return validate(user,password,null); - } - - /** - * Returns null if ok, or an Error String; - * - * For State Object, you may put in HTTPServletRequest or AuthzTrans, if available. Otherwise, - * leave null - * - * @param user - * @param password - * @return - * @throws IOException - * @throws CadiException - * @throws Exception - */ - public String validate(String user, String password, Object state) throws IOException { - password = access.decrypt(password, false); - byte[] bytes = password.getBytes(); - User usr = getUser(user,bytes); + /** + * Returns null if ok, or an Error String; + * + * Convenience function. Passes "null" for State object + */ + public String validate(String user, String password) throws IOException { + return validate(user,password,null); + } + + /** + * Returns null if ok, or an Error String; + * + * For State Object, you may put in HTTPServletRequest or AuthzTrans, if available. Otherwise, + * leave null + * + * @param user + * @param password + * @return + * @throws IOException + * @throws CadiException + * @throws Exception + */ + public String validate(String user, String password, Object state) throws IOException { + password = access.decrypt(password, false); + byte[] bytes = password.getBytes(); + User usr = getUser(user,bytes); - if(usr != null && !usr.permExpired()) { - if(usr.principal==null) { - return "User already denied"; - } else { - return null; // good - } - } + if(usr != null && !usr.permExpired()) { + if(usr.principal==null) { + return "User already denied"; + } else { + return null; // good + } + } - AAFCachedPrincipal cp = new AAFCachedPrincipal(user, bytes, con.cleanInterval); - // Since I've relocated the Validation piece in the Principal, just revalidate, then do Switch - // Statement - switch(cp.revalidate(state)) { - case REVALIDATED: - if(usr!=null) { - usr.principal = cp; - } else { - addUser(new User(cp,con.timeout)); - } - return null; - case INACCESSIBLE: - return "AAF Inaccessible"; - case UNVALIDATED: - addUser(new User(user,bytes,con.timeout)); - return "User/Pass combo invalid for " + user; - case DENIED: - return "AAF denies API for " + user; - default: - return "AAFAuthn doesn't handle Principal " + user; - } - } - - private class AAFCachedPrincipal extends ConfigPrincipal implements CachedPrincipal { - private long expires; - private long timeToLive; + AAFCachedPrincipal cp = new AAFCachedPrincipal(user, bytes, con.cleanInterval); + // Since I've relocated the Validation piece in the Principal, just revalidate, then do Switch + // Statement + switch(cp.revalidate(state)) { + case REVALIDATED: + if(usr!=null) { + usr.principal = cp; + } else { + addUser(new User(cp,con.timeout)); + } + return null; + case INACCESSIBLE: + return "AAF Inaccessible"; + case UNVALIDATED: + addUser(new User(user,bytes,con.timeout)); + return "User/Pass combo invalid for " + user; + case DENIED: + return "AAF denies API for " + user; + default: + return "AAFAuthn doesn't handle Principal " + user; + } + } + + private class AAFCachedPrincipal extends ConfigPrincipal implements CachedPrincipal { + private long expires; + private long timeToLive; - private AAFCachedPrincipal(String name, byte[] pass, int timeToLive) { - super(name,pass); - this.timeToLive = timeToLive; - expires = timeToLive + System.currentTimeMillis(); - } + private AAFCachedPrincipal(String name, byte[] pass, int timeToLive) { + super(name,pass); + this.timeToLive = timeToLive; + expires = timeToLive + System.currentTimeMillis(); + } - public Resp revalidate(Object state) { - try { - Miss missed = missed(getName(),getCred()); - if(missed==null || missed.mayContinue()) { - Rcli client = con.client(Config.AAF_DEFAULT_VERSION).forUser(con.basicAuth(getName(), new String(getCred()))); - Future fp = client.read( - "/authn/basicAuth", - "text/plain" - ); - if(fp.get(con.timeout)) { - expires = System.currentTimeMillis() + timeToLive; - addUser(new User(this, expires)); - return Resp.REVALIDATED; - } else { - addMiss(getName(), getCred()); - return Resp.UNVALIDATED; - } - } else { - return Resp.UNVALIDATED; - } - } catch (Exception e) { - con.access.log(e); - return Resp.INACCESSIBLE; - } - } + public Resp revalidate(Object state) { + try { + Miss missed = missed(getName(),getCred()); + if(missed==null || missed.mayContinue()) { + Rcli client = con.client(Config.AAF_DEFAULT_VERSION).forUser(con.basicAuth(getName(), new String(getCred()))); + Future fp = client.read( + "/authn/basicAuth", + "text/plain" + ); + if(fp.get(con.timeout)) { + expires = System.currentTimeMillis() + timeToLive; + addUser(new User(this, expires)); + return Resp.REVALIDATED; + } else { + addMiss(getName(), getCred()); + return Resp.UNVALIDATED; + } + } else { + return Resp.UNVALIDATED; + } + } catch (Exception e) { + con.access.log(e); + return Resp.INACCESSIBLE; + } + } - public long expires() { - return expires; - } - } + public long expires() { + return expires; + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java index 32107131..cda6dfb9 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java @@ -58,316 +58,316 @@ import aaf.v2_0.Perms; import aaf.v2_0.Users; public abstract class AAFCon implements Connector { - final public Access access; - // Package access - final public int timeout, cleanInterval, connTimeout; - final public int highCount, userExpires, usageRefreshTriggerCount; - private Map> clients = new ConcurrentHashMap<>(); - final public RosettaDF permsDF; - final public RosettaDF certsDF; - final public RosettaDF usersDF; - final public RosettaDF errDF; - private String realm; - public final String app; - protected SecurityInfoC si; + final public Access access; + // Package access + final public int timeout, cleanInterval, connTimeout; + final public int highCount, userExpires, usageRefreshTriggerCount; + private Map> clients = new ConcurrentHashMap<>(); + final public RosettaDF permsDF; + final public RosettaDF certsDF; + final public RosettaDF usersDF; + final public RosettaDF errDF; + private String realm; + public final String app; + protected SecurityInfoC si; - private AAFLurPerm lur; + private AAFLurPerm lur; - final public RosettaEnv env; - protected abstract URI initURI(); - protected abstract void setInitURI(String uriString) throws CadiException; - /* - protected abstract SecuritySetter bestSS(SecurityInfoC si) throws CadiException; - */ - - /** - * Use this call to get the appropriate client based on configuration (HTTP, future) - * - * @param apiVersion - * @return - * @throws CadiException - */ - public Rcli client(String apiVersion) throws CadiException { - Rcli client = clients.get(apiVersion); - if(client==null) { - client = rclient(initURI(),si.defSS); - client.apiVersion(apiVersion) - .readTimeout(connTimeout); - clients.put(apiVersion, client); - } - return client; - } + final public RosettaEnv env; + protected abstract URI initURI(); + protected abstract void setInitURI(String uriString) throws CadiException; + /* + protected abstract SecuritySetter bestSS(SecurityInfoC si) throws CadiException; + */ + + /** + * Use this call to get the appropriate client based on configuration (HTTP, future) + * + * @param apiVersion + * @return + * @throws CadiException + */ + public Rcli client(String apiVersion) throws CadiException { + Rcli client = clients.get(apiVersion); + if(client==null) { + client = rclient(initURI(),si.defSS); + client.apiVersion(apiVersion) + .readTimeout(connTimeout); + clients.put(apiVersion, client); + } + return client; + } - public Rcli client(URI uri) throws CadiException { - return rclient(uri,si.defSS).readTimeout(connTimeout); - } - - /** - * Use this API when you have permission to have your call act as the end client's ID. - * - * Your calls will get 403 errors if you do not have this permission. it is a special setup, rarely given. - * - * @param apiVersion - * @param req - * @return - * @throws CadiException - */ - public Rcli clientAs(String apiVersion, TaggedPrincipal p) throws CadiException { - Rcli cl = client(apiVersion); - return cl.forUser(transferSS(p)); - } - - protected AAFCon(AAFCon copy) { - access = copy.access; - timeout = copy.timeout; - cleanInterval = copy.cleanInterval; - connTimeout = copy.connTimeout; - highCount = copy.highCount; - userExpires = copy.userExpires; - usageRefreshTriggerCount = copy.usageRefreshTriggerCount; - permsDF = copy.permsDF; - certsDF = copy.certsDF; - usersDF = copy.usersDF; - errDF = copy.errDF; - app = copy.app; - si = copy.si; - env = copy.env; - realm = copy.realm; - } - - protected AAFCon(Access access, String tag, SecurityInfoC si) throws CadiException{ - if(tag==null) { - throw new CadiException("AAFCon cannot be constructed without a property tag or URL"); - } else { - String str = access.getProperty(tag,null); - if(str==null) { - if(tag.contains("://")) { // assume a URL - str = tag; - } else { - throw new CadiException("A URL or " + tag + " property is required."); - } - } - setInitURI(str); - } - try { - this.access = access; - this.si = si; - if(si.defSS.getID().equals(SecurityInfoC.DEF_ID)) { // it's the Preliminary SS, try to get a better one - String mechid = access.getProperty(Config.AAF_APPID, null); - if(mechid==null) { - mechid=access.getProperty(Config.OAUTH_CLIENT_ID,null); - } - String encpass = access.getProperty(Config.AAF_APPPASS, null); - if(encpass==null) { - encpass = access.getProperty(Config.OAUTH_CLIENT_SECRET,null); - } - if(encpass==null) { - String alias = access.getProperty(Config.CADI_ALIAS, mechid); - if(alias==null) { - access.printf(Access.Level.WARN,"%s, %s or %s required before use.", Config.CADI_ALIAS, Config.AAF_APPID, Config.OAUTH_CLIENT_ID); - set(si.defSS); - } else { - si.defSS=x509Alias(alias); - set(si.defSS); - } - } else { - if(mechid!=null) { - si.defSS=basicAuth(mechid, encpass); - set(si.defSS); - } else { - si.defSS=new SecuritySetter() { + public Rcli client(URI uri) throws CadiException { + return rclient(uri,si.defSS).readTimeout(connTimeout); + } + + /** + * Use this API when you have permission to have your call act as the end client's ID. + * + * Your calls will get 403 errors if you do not have this permission. it is a special setup, rarely given. + * + * @param apiVersion + * @param req + * @return + * @throws CadiException + */ + public Rcli clientAs(String apiVersion, TaggedPrincipal p) throws CadiException { + Rcli cl = client(apiVersion); + return cl.forUser(transferSS(p)); + } + + protected AAFCon(AAFCon copy) { + access = copy.access; + timeout = copy.timeout; + cleanInterval = copy.cleanInterval; + connTimeout = copy.connTimeout; + highCount = copy.highCount; + userExpires = copy.userExpires; + usageRefreshTriggerCount = copy.usageRefreshTriggerCount; + permsDF = copy.permsDF; + certsDF = copy.certsDF; + usersDF = copy.usersDF; + errDF = copy.errDF; + app = copy.app; + si = copy.si; + env = copy.env; + realm = copy.realm; + } + + protected AAFCon(Access access, String tag, SecurityInfoC si) throws CadiException{ + if(tag==null) { + throw new CadiException("AAFCon cannot be constructed without a property tag or URL"); + } else { + String str = access.getProperty(tag,null); + if(str==null) { + if(tag.contains("://")) { // assume a URL + str = tag; + } else { + throw new CadiException("A URL or " + tag + " property is required."); + } + } + setInitURI(str); + } + try { + this.access = access; + this.si = si; + if(si.defSS.getID().equals(SecurityInfoC.DEF_ID)) { // it's the Preliminary SS, try to get a better one + String mechid = access.getProperty(Config.AAF_APPID, null); + if(mechid==null) { + mechid=access.getProperty(Config.OAUTH_CLIENT_ID,null); + } + String encpass = access.getProperty(Config.AAF_APPPASS, null); + if(encpass==null) { + encpass = access.getProperty(Config.OAUTH_CLIENT_SECRET,null); + } + if(encpass==null) { + String alias = access.getProperty(Config.CADI_ALIAS, mechid); + if(alias==null) { + access.printf(Access.Level.WARN,"%s, %s or %s required before use.", Config.CADI_ALIAS, Config.AAF_APPID, Config.OAUTH_CLIENT_ID); + set(si.defSS); + } else { + si.defSS=x509Alias(alias); + set(si.defSS); + } + } else { + if(mechid!=null) { + si.defSS=basicAuth(mechid, encpass); + set(si.defSS); + } else { + si.defSS=new SecuritySetter() { - @Override - public String getID() { - return ""; - } + @Override + public String getID() { + return ""; + } - @Override - public void setSecurity(CLIENT client) throws CadiException { - throw new CadiException("AAFCon has not been initialized with Credentials (SecuritySetter)"); - } + @Override + public void setSecurity(CLIENT client) throws CadiException { + throw new CadiException("AAFCon has not been initialized with Credentials (SecuritySetter)"); + } - @Override - public int setLastResponse(int respCode) { - return 0; - } - }; - set(si.defSS); - } - } - } - - timeout = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT, Config.AAF_CALL_TIMEOUT_DEF)); - cleanInterval = Integer.parseInt(access.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)); - highCount = Integer.parseInt(access.getProperty(Config.AAF_HIGH_COUNT, Config.AAF_HIGH_COUNT_DEF).trim()); - connTimeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF).trim()); - userExpires = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim()); - usageRefreshTriggerCount = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim())-1; // zero based - - app=FQI.reverseDomain(si.defSS.getID()); - //TODO Get Realm from AAF - realm="people.osaaf.org"; - - env = new RosettaEnv(); - permsDF = env.newDataFactory(Perms.class); - usersDF = env.newDataFactory(Users.class); - certsDF = env.newDataFactory(Certs.class); - certsDF.rootMarshal(new CertsMarshal()); // Speedier Marshaling - errDF = env.newDataFactory(Error.class); - } catch (APIException e) { - throw new CadiException("AAFCon cannot be configured",e); - } - } - - public RosettaEnv env() { - return env; - } - - /** - * Return the backing AAFCon, if there is a Lur Setup that is AAF. - * - * If there is no AAFLur setup, it will return "null" - * @param servletRequest - * @return - */ - public static final AAFCon obtain(Object servletRequest) { - if(servletRequest instanceof CadiWrap) { - Lur lur = ((CadiWrap)servletRequest).getLur(); - if(lur != null) { - if(lur instanceof EpiLur) { - AbsAAFLur aal = (AbsAAFLur) ((EpiLur)lur).subLur(AbsAAFLur.class); - if(aal!=null) { - return aal.aaf; - } - } else { - if(lur instanceof AbsAAFLur) { - return ((AbsAAFLur)lur).aaf; - } - } - } - } - return null; - } - - public abstract AAFCon clone(String url) throws CadiException, LocatorException; - - public AAFAuthn newAuthn() throws APIException { - try { - return new AAFAuthn<>(this); - } catch (Exception e) { - throw new APIException(e); - } - } + @Override + public int setLastResponse(int respCode) { + return 0; + } + }; + set(si.defSS); + } + } + } + + timeout = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT, Config.AAF_CALL_TIMEOUT_DEF)); + cleanInterval = Integer.parseInt(access.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)); + highCount = Integer.parseInt(access.getProperty(Config.AAF_HIGH_COUNT, Config.AAF_HIGH_COUNT_DEF).trim()); + connTimeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF).trim()); + userExpires = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim()); + usageRefreshTriggerCount = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim())-1; // zero based + + app=FQI.reverseDomain(si.defSS.getID()); + //TODO Get Realm from AAF + realm="people.osaaf.org"; + + env = new RosettaEnv(); + permsDF = env.newDataFactory(Perms.class); + usersDF = env.newDataFactory(Users.class); + certsDF = env.newDataFactory(Certs.class); + certsDF.rootMarshal(new CertsMarshal()); // Speedier Marshaling + errDF = env.newDataFactory(Error.class); + } catch (APIException e) { + throw new CadiException("AAFCon cannot be configured",e); + } + } + + public RosettaEnv env() { + return env; + } + + /** + * Return the backing AAFCon, if there is a Lur Setup that is AAF. + * + * If there is no AAFLur setup, it will return "null" + * @param servletRequest + * @return + */ + public static final AAFCon obtain(Object servletRequest) { + if(servletRequest instanceof CadiWrap) { + Lur lur = ((CadiWrap)servletRequest).getLur(); + if(lur != null) { + if(lur instanceof EpiLur) { + AbsAAFLur aal = (AbsAAFLur) ((EpiLur)lur).subLur(AbsAAFLur.class); + if(aal!=null) { + return aal.aaf; + } + } else { + if(lur instanceof AbsAAFLur) { + return ((AbsAAFLur)lur).aaf; + } + } + } + } + return null; + } + + public abstract AAFCon clone(String url) throws CadiException, LocatorException; + + public AAFAuthn newAuthn() throws APIException { + try { + return new AAFAuthn<>(this); + } catch (Exception e) { + throw new APIException(e); + } + } - public AAFAuthn newAuthn(AbsUserCache c) { - return new AAFAuthn<>(this, c); - } + public AAFAuthn newAuthn(AbsUserCache c) { + return new AAFAuthn<>(this, c); + } - public AAFLurPerm newLur() throws CadiException { - try { - if(lur==null) { - lur = new AAFLurPerm(this); - return lur; - } else { - return new AAFLurPerm(this,lur); - } - } catch (CadiException e) { - throw e; - } catch (Exception e) { - throw new CadiException(e); - } - } - - public AAFLurPerm newLur(AbsUserCache c) throws APIException { - try { - return new AAFLurPerm(this,c); - } catch (APIException e) { - throw e; - } catch (Exception e) { - throw new APIException(e); - } - } + public AAFLurPerm newLur() throws CadiException { + try { + if(lur==null) { + lur = new AAFLurPerm(this); + return lur; + } else { + return new AAFLurPerm(this,lur); + } + } catch (CadiException e) { + throw e; + } catch (Exception e) { + throw new CadiException(e); + } + } + + public AAFLurPerm newLur(AbsUserCache c) throws APIException { + try { + return new AAFLurPerm(this,c); + } catch (APIException e) { + throw e; + } catch (Exception e) { + throw new APIException(e); + } + } - protected abstract Rcli rclient(URI uri, SecuritySetter ss) throws CadiException; - - public abstract Rcli rclient(Locator loc, SecuritySetter ss) throws CadiException; + protected abstract Rcli rclient(URI uri, SecuritySetter ss) throws CadiException; + + public abstract Rcli rclient(Locator loc, SecuritySetter ss) throws CadiException; - public Rcli client(Locator locator) throws CadiException { - return rclient(locator,si.defSS); - } - - public abstract RET best(Retryable retryable) throws LocatorException, CadiException, APIException; + public Rcli client(Locator locator) throws CadiException { + return rclient(locator,si.defSS); + } + + public abstract RET best(Retryable retryable) throws LocatorException, CadiException, APIException; - public abstract RET bestForUser(GetSetter get, Retryable retryable) throws LocatorException, CadiException, APIException; + public abstract RET bestForUser(GetSetter get, Retryable retryable) throws LocatorException, CadiException, APIException; - public abstract SecuritySetter basicAuth(String user, String password) throws CadiException; - - public abstract SecuritySetter transferSS(TaggedPrincipal principal) throws CadiException; - - public abstract SecuritySetter basicAuthSS(BasicPrincipal principal) throws CadiException; - - public abstract SecuritySetter tokenSS(final String client_id, final String accessToken) throws CadiException; - - public abstract SecuritySetter x509Alias(String alias) throws APIException, CadiException; - + public abstract SecuritySetter basicAuth(String user, String password) throws CadiException; + + public abstract SecuritySetter transferSS(TaggedPrincipal principal) throws CadiException; + + public abstract SecuritySetter basicAuthSS(BasicPrincipal principal) throws CadiException; + + public abstract SecuritySetter tokenSS(final String client_id, final String accessToken) throws CadiException; + + public abstract SecuritySetter x509Alias(String alias) throws APIException, CadiException; + - public String getRealm() { - return realm; + public String getRealm() { + return realm; - } - - /** - * This interface allows the AAFCon, even though generic, to pass in correctly typed values based on the above SS commands. - * @author Jonathan - * - */ - public interface GetSetter { - public SecuritySetter get(AAFCon con) throws CadiException; - } + } + + /** + * This interface allows the AAFCon, even though generic, to pass in correctly typed values based on the above SS commands. + * @author Jonathan + * + */ + public interface GetSetter { + public SecuritySetter get(AAFCon con) throws CadiException; + } - public SecuritySetter set(final SecuritySetter ss) { - si.set(ss); - for(Rcli client : clients.values()) { - client.setSecuritySetter(ss); - } - return ss; - } - - public SecurityInfoC securityInfo() { - return si; - } + public SecuritySetter set(final SecuritySetter ss) { + si.set(ss); + for(Rcli client : clients.values()) { + client.setSecuritySetter(ss); + } + return ss; + } + + public SecurityInfoC securityInfo() { + return si; + } - public String defID() { - if(si!=null) { - return si.defSS.getID(); - } - return "unknown"; - } - - public void invalidate() throws CadiException { - for(Rcli client : clients.values()) { - client.invalidate(); - } - clients.clear(); - } + public String defID() { + if(si!=null) { + return si.defSS.getID(); + } + return "unknown"; + } + + public void invalidate() throws CadiException { + for(Rcli client : clients.values()) { + client.invalidate(); + } + clients.clear(); + } - public String readableErrMsg(Future f) { - String text = f.body(); - if(text==null || text.length()==0) { - text = f.code() + ": **No Message**"; - } else if(text.contains("%")) { - try { - Error err = errDF.newData().in(TYPE.JSON).load(f.body()).asObject(); - return Vars.convert(err.getText(),err.getVariables()); - } catch (APIException e){ - access.log(e); - } - } - return text; - } - - public static AAFCon newInstance(PropAccess pa) throws CadiException, LocatorException { - // Potentially add plugin for other kinds of Access - return new AAFConHttp(pa); - } + public String readableErrMsg(Future f) { + String text = f.body(); + if(text==null || text.length()==0) { + text = f.code() + ": **No Message**"; + } else if(text.contains("%")) { + try { + Error err = errDF.newData().in(TYPE.JSON).load(f.body()).asObject(); + return Vars.convert(err.getText(),err.getVariables()); + } catch (APIException e){ + access.log(e); + } + } + return text; + } + + public static AAFCon newInstance(PropAccess pa) throws CadiException, LocatorException { + // Potentially add plugin for other kinds of Access + return new AAFConHttp(pa); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java index a06b7aff..cc70ae3c 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java @@ -47,174 +47,174 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; import org.onap.aaf.misc.env.APIException; public class AAFConHttp extends AAFCon { - private final HMangr hman; - - public AAFConHttp(Access access) throws CadiException, LocatorException { - super(access,Config.AAF_URL,SecurityInfoC.instance(access, HttpURLConnection.class)); - hman = new HMangr(access,Config.loadLocator(si, access.getProperty(Config.AAF_URL,null))); - } - - protected SecuritySetter bestSS(SecurityInfoC si) throws CadiException { - return si.defSS; - } - - public AAFConHttp(Access access, String tag) throws CadiException, LocatorException { - super(access,tag,SecurityInfoC.instance(access, HttpURLConnection.class)); - bestSS(si); - hman = new HMangr(access,Config.loadLocator(si, access.getProperty(tag,tag/*try the content itself*/))); - } - - public AAFConHttp(Access access, String urlTag, SecurityInfoC si) throws CadiException, LocatorException { - super(access,urlTag,si); - bestSS(si); - hman = new HMangr(access,Config.loadLocator(si, access.getProperty(urlTag,null))); - } - - public AAFConHttp(Access access, Locator locator) throws CadiException, LocatorException { - super(access,Config.AAF_URL,SecurityInfoC.instance(access, HttpURLConnection.class)); - bestSS(si); - hman = new HMangr(access,locator); - } - - public AAFConHttp(Access access, Locator locator, SecurityInfoC si) throws CadiException, LocatorException, APIException { - super(access,Config.AAF_URL,si); - bestSS(si); - hman = new HMangr(access,locator); - } - - public AAFConHttp(Access access, Locator locator, SecurityInfoC si, String tag) throws CadiException, LocatorException, APIException { - super(access,tag,si); - bestSS(si); - hman = new HMangr(access, locator); - } - - private AAFConHttp(AAFCon aafcon, String url) throws LocatorException { - super(aafcon); - si=aafcon.si; - hman = new HMangr(aafcon.access,Config.loadLocator(si, url)); - } - - @Override - public AAFCon clone(String url) throws LocatorException { - return new AAFConHttp(this,url); - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#basicAuth(java.lang.String, java.lang.String) - */ - @Override - public SecuritySetter basicAuth(String user, String password) throws CadiException { - if(password.startsWith("enc:")) { - try { - password = access.decrypt(password, true); - } catch (IOException e) { - throw new CadiException("Error decrypting password",e); - } - } - try { - return new HBasicAuthSS(si,user,password); - } catch (IOException e) { - throw new CadiException("Error creating HBasicAuthSS",e); - } - } - - public SecuritySetter x509Alias(String alias) throws CadiException { - try { - return set(new HX509SS(alias,si)); - } catch (Exception e) { - throw new CadiException("Error creating X509SS",e); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#rclient(java.net.URI, org.onap.aaf.cadi.SecuritySetter) - */ - @Override - protected Rcli rclient(URI ignoredURI, SecuritySetter ss) throws CadiException { - if(hman.loc==null) { - throw new CadiException("No Locator set in AAFConHttp"); - } - try { - return new HRcli(hman, hman.loc.best() ,ss); - } catch (Exception e) { - throw new CadiException(e); - } - } - - @Override - public Rcli rclient(Locator loc, SecuritySetter ss) throws CadiException { - try { - HMangr newHMan = new HMangr(access, loc); - return new HRcli(newHMan,newHMan.loc.best(),ss); - } catch (Exception e) { - throw new CadiException(e); - } - } - @Override - public AbsTransferSS transferSS(TaggedPrincipal principal) { - return new HTransferSS(principal, app,si); - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#basicAuthSS(java.security.Principal) - */ - @Override - public SecuritySetter basicAuthSS(BasicPrincipal principal) throws CadiException { - try { - return new HBasicAuthSS(principal,si); - } catch (IOException e) { - throw new CadiException("Error creating HBasicAuthSS",e); - } - } - - @Override - public SecuritySetter tokenSS(final String client_id, final String accessToken) throws CadiException { - try { - return new HTokenSS(si, client_id, accessToken); - } catch (IOException e) { - throw new CadiException(e); - } - } - - public HMangr hman() { - return hman; - } - - @Override - public RET best(Retryable retryable) throws LocatorException, CadiException, APIException { - return hman.best(si.defSS, retryable); - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#bestForUser(org.onap.aaf.cadi.SecuritySetter, org.onap.aaf.cadi.client.Retryable) - */ - @Override - public RET bestForUser(GetSetter getSetter, Retryable retryable) throws LocatorException, CadiException, APIException { - return hman.best(getSetter.get(this), retryable); - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#initURI() - */ - @Override - protected URI initURI() { - try { - Item item = hman.loc.best(); - if(item!=null) { - return hman.loc.get(item); - } - } catch (LocatorException e) { - access.log(e, "Error in AAFConHttp obtaining initial URI"); - } - return null; - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#setInitURI(java.lang.String) - */ - @Override - protected void setInitURI(String uriString) { - // Using Locator, not URLString, which is mostly for DME2 - } + private final HMangr hman; + + public AAFConHttp(Access access) throws CadiException, LocatorException { + super(access,Config.AAF_URL,SecurityInfoC.instance(access, HttpURLConnection.class)); + hman = new HMangr(access,Config.loadLocator(si, access.getProperty(Config.AAF_URL,null))); + } + + protected SecuritySetter bestSS(SecurityInfoC si) throws CadiException { + return si.defSS; + } + + public AAFConHttp(Access access, String tag) throws CadiException, LocatorException { + super(access,tag,SecurityInfoC.instance(access, HttpURLConnection.class)); + bestSS(si); + hman = new HMangr(access,Config.loadLocator(si, access.getProperty(tag,tag/*try the content itself*/))); + } + + public AAFConHttp(Access access, String urlTag, SecurityInfoC si) throws CadiException, LocatorException { + super(access,urlTag,si); + bestSS(si); + hman = new HMangr(access,Config.loadLocator(si, access.getProperty(urlTag,null))); + } + + public AAFConHttp(Access access, Locator locator) throws CadiException, LocatorException { + super(access,Config.AAF_URL,SecurityInfoC.instance(access, HttpURLConnection.class)); + bestSS(si); + hman = new HMangr(access,locator); + } + + public AAFConHttp(Access access, Locator locator, SecurityInfoC si) throws CadiException, LocatorException, APIException { + super(access,Config.AAF_URL,si); + bestSS(si); + hman = new HMangr(access,locator); + } + + public AAFConHttp(Access access, Locator locator, SecurityInfoC si, String tag) throws CadiException, LocatorException, APIException { + super(access,tag,si); + bestSS(si); + hman = new HMangr(access, locator); + } + + private AAFConHttp(AAFCon aafcon, String url) throws LocatorException { + super(aafcon); + si=aafcon.si; + hman = new HMangr(aafcon.access,Config.loadLocator(si, url)); + } + + @Override + public AAFCon clone(String url) throws LocatorException { + return new AAFConHttp(this,url); + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#basicAuth(java.lang.String, java.lang.String) + */ + @Override + public SecuritySetter basicAuth(String user, String password) throws CadiException { + if(password.startsWith("enc:")) { + try { + password = access.decrypt(password, true); + } catch (IOException e) { + throw new CadiException("Error decrypting password",e); + } + } + try { + return new HBasicAuthSS(si,user,password); + } catch (IOException e) { + throw new CadiException("Error creating HBasicAuthSS",e); + } + } + + public SecuritySetter x509Alias(String alias) throws CadiException { + try { + return set(new HX509SS(alias,si)); + } catch (Exception e) { + throw new CadiException("Error creating X509SS",e); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#rclient(java.net.URI, org.onap.aaf.cadi.SecuritySetter) + */ + @Override + protected Rcli rclient(URI ignoredURI, SecuritySetter ss) throws CadiException { + if(hman.loc==null) { + throw new CadiException("No Locator set in AAFConHttp"); + } + try { + return new HRcli(hman, hman.loc.best() ,ss); + } catch (Exception e) { + throw new CadiException(e); + } + } + + @Override + public Rcli rclient(Locator loc, SecuritySetter ss) throws CadiException { + try { + HMangr newHMan = new HMangr(access, loc); + return new HRcli(newHMan,newHMan.loc.best(),ss); + } catch (Exception e) { + throw new CadiException(e); + } + } + @Override + public AbsTransferSS transferSS(TaggedPrincipal principal) { + return new HTransferSS(principal, app,si); + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#basicAuthSS(java.security.Principal) + */ + @Override + public SecuritySetter basicAuthSS(BasicPrincipal principal) throws CadiException { + try { + return new HBasicAuthSS(principal,si); + } catch (IOException e) { + throw new CadiException("Error creating HBasicAuthSS",e); + } + } + + @Override + public SecuritySetter tokenSS(final String client_id, final String accessToken) throws CadiException { + try { + return new HTokenSS(si, client_id, accessToken); + } catch (IOException e) { + throw new CadiException(e); + } + } + + public HMangr hman() { + return hman; + } + + @Override + public RET best(Retryable retryable) throws LocatorException, CadiException, APIException { + return hman.best(si.defSS, retryable); + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#bestForUser(org.onap.aaf.cadi.SecuritySetter, org.onap.aaf.cadi.client.Retryable) + */ + @Override + public RET bestForUser(GetSetter getSetter, Retryable retryable) throws LocatorException, CadiException, APIException { + return hman.best(getSetter.get(this), retryable); + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#initURI() + */ + @Override + protected URI initURI() { + try { + Item item = hman.loc.best(); + if(item!=null) { + return hman.loc.get(item); + } + } catch (LocatorException e) { + access.log(e, "Error in AAFConHttp obtaining initial URI"); + } + return null; + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.aaf.v2_0.AAFCon#setInitURI(java.lang.String) + */ + @Override + protected void setInitURI(String uriString) { + // Using Locator, not URLString, which is mostly for DME2 + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java index 00a40568..468bb915 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java @@ -46,95 +46,95 @@ import locate.v1_0.Endpoint; import locate.v1_0.Endpoints; public class AAFLocator extends AbsAAFLocator { - private static RosettaEnv env; - HClient client; - private RosettaDF epsDF; + private static RosettaEnv env; + HClient client; + private RosettaDF epsDF; - public AAFLocator(SecurityInfoC si, URI locatorURI) throws LocatorException { - super(si.access, nameFromLocatorURI(locatorURI), 10000L /* Wait at least 10 seconds between refreshes */); - synchronized(sr) { - if(env==null) { - env = new RosettaEnv(access.getProperties()); - } - } - - int connectTimeout = Integer.parseInt(si.access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); - try { - String[] path = Split.split('/',locatorURI.getPath()); - String host = locatorURI.getHost(); - if(host==null) { - host = locatorURI.getAuthority(); // this happens when no port - } - if("AAF_LOCATE_URL".equals(host)) { - URI uri = new URI( - locatorURI.getScheme(), - locatorURI.getUserInfo(), - aaf_locator_uri.getHost(), - aaf_locator_uri.getPort(), - "/locate"+locatorURI.getPath(), - null, - null - ); - client = createClient(si.defSS, uri, connectTimeout); - } else if(path.length>1 && "locate".equals(path[1])) { - StringBuilder sb = new StringBuilder(); - for(int i=3;i si, URI locatorURI) throws LocatorException { + super(si.access, nameFromLocatorURI(locatorURI), 10000L /* Wait at least 10 seconds between refreshes */); + synchronized(sr) { + if(env==null) { + env = new RosettaEnv(access.getProperties()); + } + } + + int connectTimeout = Integer.parseInt(si.access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); + try { + String[] path = Split.split('/',locatorURI.getPath()); + String host = locatorURI.getHost(); + if(host==null) { + host = locatorURI.getAuthority(); // this happens when no port + } + if("AAF_LOCATE_URL".equals(host)) { + URI uri = new URI( + locatorURI.getScheme(), + locatorURI.getUserInfo(), + aaf_locator_uri.getHost(), + aaf_locator_uri.getPort(), + "/locate"+locatorURI.getPath(), + null, + null + ); + client = createClient(si.defSS, uri, connectTimeout); + } else if(path.length>1 && "locate".equals(path[1])) { + StringBuilder sb = new StringBuilder(); + for(int i=3;i fr = client.futureRead(epsDF, TYPE.JSON); - if(fr.get(client.timeout())) { - List epl = new LinkedList<>(); - for(Endpoint endpoint : fr.value.getEndpoint()) { - epl.add(new EP(endpoint,latitude,longitude)); - } - - Collections.sort(epl); - replace(epl); - return true; - } else { - env.error().printf("Error reading location information from %s: %d %s\n",client.getURI().toString(),fr.code(),fr.body()); - } - } catch (CadiException | URISyntaxException | APIException e) { - env.error().log(e,"Error connecting " + client.getURI() + " for location."); - } - return false; - } + @Override + public boolean refresh() { + try { + client.setMethod("GET"); + client.send(); + Future fr = client.futureRead(epsDF, TYPE.JSON); + if(fr.get(client.timeout())) { + List epl = new LinkedList<>(); + for(Endpoint endpoint : fr.value.getEndpoint()) { + epl.add(new EP(endpoint,latitude,longitude)); + } + + Collections.sort(epl); + replace(epl); + return true; + } else { + env.error().printf("Error reading location information from %s: %d %s\n",client.getURI().toString(),fr.code(),fr.body()); + } + } catch (CadiException | URISyntaxException | APIException e) { + env.error().log(e,"Error connecting " + client.getURI() + " for location."); + } + return false; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator#getURI() - */ - @Override - protected URI getURI() { - return client.getURI(); - } - - protected HClient createClient(SecuritySetter ss, URI uri, int connectTimeout) throws LocatorException { - return new HClient(ss, uri, connectTimeout); - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator#getURI() + */ + @Override + protected URI getURI() { + return client.getURI(); + } + + protected HClient createClient(SecuritySetter ss, URI uri, int connectTimeout) throws LocatorException { + return new HClient(ss, uri, connectTimeout); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java index 682540ea..b1c600a0 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java @@ -61,197 +61,197 @@ import aaf.v2_0.Perms; * */ public class AAFLurPerm extends AbsAAFLur { - private static final String ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR = "org.osaaf.cadi.oauth.OAuth2Lur"; + private static final String ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR = "org.osaaf.cadi.oauth.OAuth2Lur"; - /** - * Need to be able to transmutate a Principal into either Person or AppID, which are the only ones accepted at this - * point by AAF. There is no "domain", aka, no "@att.com" in "ab1234@att.com". - * - * The only thing that matters here for AAF is that we don't waste calls with IDs that obviously aren't valid. - * Thus, we validate that the ID portion follows the rules before we waste time accessing AAF remotely - * @throws APIException - * @throws URISyntaxException - * @throws DME2Exception - */ - // Package on purpose - AAFLurPerm(AAFCon con) throws CadiException, APIException { - super(con); - attachOAuth2(con); - } + /** + * Need to be able to transmutate a Principal into either Person or AppID, which are the only ones accepted at this + * point by AAF. There is no "domain", aka, no "@att.com" in "ab1234@att.com". + * + * The only thing that matters here for AAF is that we don't waste calls with IDs that obviously aren't valid. + * Thus, we validate that the ID portion follows the rules before we waste time accessing AAF remotely + * @throws APIException + * @throws URISyntaxException + * @throws DME2Exception + */ + // Package on purpose + AAFLurPerm(AAFCon con) throws CadiException, APIException { + super(con); + attachOAuth2(con); + } - // Package on purpose - AAFLurPerm(AAFCon con, AbsUserCache auc) throws APIException { - super(con,auc); - attachOAuth2(con); - } - - private void attachOAuth2(AAFCon con) throws APIException { - String oauth2_url; - Class tmcls = Config.loadClass(access,"org.osaaf.cadi.oauth.TokenMgr"); - if(tmcls!=null) { - if((oauth2_url = con.access.getProperty(Config.CADI_OAUTH2_URL,null))!=null) { - try { - Constructor tmconst = tmcls.getConstructor(AAFCon.class,String.class); - Object tokMangr = tmconst.newInstance(con,oauth2_url); - @SuppressWarnings("unchecked") - Class oa2cls = (Class)Config.loadClass(access,ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR); - Constructor oa2const = oa2cls.getConstructor(tmcls); - Lur oa2 = oa2const.newInstance(tokMangr); - setPreemptiveLur(oa2); - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new APIException(e); - } - } else { - access.log(Level.INIT, "Both cadi-oauth jar and Property",Config.CADI_OAUTH2_URL,"is required to initialize OAuth2"); - } - } - } + // Package on purpose + AAFLurPerm(AAFCon con, AbsUserCache auc) throws APIException { + super(con,auc); + attachOAuth2(con); + } + + private void attachOAuth2(AAFCon con) throws APIException { + String oauth2_url; + Class tmcls = Config.loadClass(access,"org.osaaf.cadi.oauth.TokenMgr"); + if(tmcls!=null) { + if((oauth2_url = con.access.getProperty(Config.CADI_OAUTH2_URL,null))!=null) { + try { + Constructor tmconst = tmcls.getConstructor(AAFCon.class,String.class); + Object tokMangr = tmconst.newInstance(con,oauth2_url); + @SuppressWarnings("unchecked") + Class oa2cls = (Class)Config.loadClass(access,ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR); + Constructor oa2const = oa2cls.getConstructor(tmcls); + Lur oa2 = oa2const.newInstance(tokMangr); + setPreemptiveLur(oa2); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new APIException(e); + } + } else { + access.log(Level.INIT, "Both cadi-oauth jar and Property",Config.CADI_OAUTH2_URL,"is required to initialize OAuth2"); + } + } + } - protected User loadUser(final Principal principal) { - final String name = principal.getName(); - final long start = System.nanoTime(); - final Holder remote = new Holder(0f); + protected User loadUser(final Principal principal) { + final String name = principal.getName(); + final long start = System.nanoTime(); + final Holder remote = new Holder(0f); - final boolean[] success = new boolean[]{false}; - - try { - return aaf.best(new Retryable>() { - @Override - public User code(Rcli client) throws CadiException, ConnectException, APIException { - final long remoteStart = System.nanoTime(); - Future fp = client.read("/authz/perms/user/"+name,aaf.permsDF); - - // In the meantime, lookup User, create if necessary - User user = getUser(principal); - Principal p; - if(user!=null && user.principal == null) { - p = new Principal() {// Create a holder for lookups - private String n = name; - public String getName() { - return n; - } - }; - } else { - p = principal; - } - - if(user==null) { - addUser(user = new User(p,aaf.userExpires)); // no password - } - - // OK, done all we can, now get content - boolean ok = fp.get(aaf.timeout); - remote.set(Timing.millis(remoteStart)); - if(ok) { - success[0]=true; - Map newMap = user.newMap(); - boolean willLog = aaf.access.willLog(Level.DEBUG); - for(Perm perm : fp.value.getPerm()) { - user.add(newMap,new AAFPermission(perm.getNs(),perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles())); - if(willLog) { - aaf.access.log(Level.DEBUG, name,"has '",perm.getType(),'|',perm.getInstance(),'|',perm.getAction(),'\''); - } - } - user.setMap(newMap); - } else { - int code; - switch(code=fp.code()) { - case 401: - aaf.access.log(Access.Level.ERROR, code, "Unauthorized to make AAF calls"); - break; - case 404: - user.setNoPerms(); - break; - default: - aaf.access.log(Access.Level.ERROR, code, fp.body()); - } - } + final boolean[] success = new boolean[]{false}; + + try { + return aaf.best(new Retryable>() { + @Override + public User code(Rcli client) throws CadiException, ConnectException, APIException { + final long remoteStart = System.nanoTime(); + Future fp = client.read("/authz/perms/user/"+name,aaf.permsDF); + + // In the meantime, lookup User, create if necessary + User user = getUser(principal); + Principal p; + if(user!=null && user.principal == null) { + p = new Principal() {// Create a holder for lookups + private String n = name; + public String getName() { + return n; + } + }; + } else { + p = principal; + } + + if(user==null) { + addUser(user = new User(p,aaf.userExpires)); // no password + } + + // OK, done all we can, now get content + boolean ok = fp.get(aaf.timeout); + remote.set(Timing.millis(remoteStart)); + if(ok) { + success[0]=true; + Map newMap = user.newMap(); + boolean willLog = aaf.access.willLog(Level.DEBUG); + for(Perm perm : fp.value.getPerm()) { + user.add(newMap,new AAFPermission(perm.getNs(),perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles())); + if(willLog) { + aaf.access.log(Level.DEBUG, name,"has '",perm.getType(),'|',perm.getInstance(),'|',perm.getAction(),'\''); + } + } + user.setMap(newMap); + } else { + int code; + switch(code=fp.code()) { + case 401: + aaf.access.log(Access.Level.ERROR, code, "Unauthorized to make AAF calls"); + break; + case 404: + user.setNoPerms(); + break; + default: + aaf.access.log(Access.Level.ERROR, code, fp.body()); + } + } - return user; - } - }); - } catch (Exception e) { - aaf.access.log(e,"Calling","/authz/perms/user/"+name); - success[0]=false; - return null; - } finally { - aaf.access.printf(Level.INFO, "AAFLurPerm: %s %s perms from AAF in %f ms, remote=%f", - (success[0]?"Loaded":"Load Failure"),name,Timing.millis(start),remote.get()); - } - } + return user; + } + }); + } catch (Exception e) { + aaf.access.log(e,"Calling","/authz/perms/user/"+name); + success[0]=false; + return null; + } finally { + aaf.access.printf(Level.INFO, "AAFLurPerm: %s %s perms from AAF in %f ms, remote=%f", + (success[0]?"Loaded":"Load Failure"),name,Timing.millis(start),remote.get()); + } + } - public Resp reload(final User user) { - final String name = user.name; - long start = System.nanoTime(); - final Holder remote = new Holder(0f); - final Holder success = new Holder(false); - try { - Resp rv = aaf.best(new Retryable() { - @Override - public Resp code(Rcli client) throws CadiException, ConnectException, APIException { - final long remoteStart = System.nanoTime(); - Future fp = aaf.client(Config.AAF_DEFAULT_VERSION).read( - "/authz/perms/user/"+name, - aaf.permsDF - ); - - // OK, done all we can, now get content - boolean ok = fp.get(aaf.timeout); - remote.set(Timing.millis(remoteStart)); - if(ok) { - success.set(true); - Map newMap = user.newMap(); - boolean willLog = aaf.access.willLog(Level.DEBUG); - for(Perm perm : fp.value.getPerm()) { - user.add(newMap, new AAFPermission(perm.getNs(),perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles())); - if(willLog) { - aaf.access.log(Level.DEBUG, name,"has",perm.getType(),perm.getInstance(),perm.getAction()); - } - } - user.renewPerm(); - return Resp.REVALIDATED; - } else { - int code; - switch(code=fp.code()) { - case 401: - aaf.access.log(Access.Level.ERROR, code, "Unauthorized to make AAF calls"); - break; - default: - aaf.access.log(Access.Level.ERROR, code, fp.body()); - } - return Resp.UNVALIDATED; - } - } - }); - return rv; - } catch (Exception e) { - aaf.access.log(e,"Calling","/authz/perms/user/"+name); - return Resp.INACCESSIBLE; - } finally { - aaf.access.printf(Level.INFO, "AAFLurPerm: %s %s perms from AAF in %f ms (remote=%f)", - (success.get()?"Reloaded":"Reload Failure"),name,Timing.millis(start),remote.get()); - } - } + public Resp reload(final User user) { + final String name = user.name; + long start = System.nanoTime(); + final Holder remote = new Holder(0f); + final Holder success = new Holder(false); + try { + Resp rv = aaf.best(new Retryable() { + @Override + public Resp code(Rcli client) throws CadiException, ConnectException, APIException { + final long remoteStart = System.nanoTime(); + Future fp = aaf.client(Config.AAF_DEFAULT_VERSION).read( + "/authz/perms/user/"+name, + aaf.permsDF + ); + + // OK, done all we can, now get content + boolean ok = fp.get(aaf.timeout); + remote.set(Timing.millis(remoteStart)); + if(ok) { + success.set(true); + Map newMap = user.newMap(); + boolean willLog = aaf.access.willLog(Level.DEBUG); + for(Perm perm : fp.value.getPerm()) { + user.add(newMap, new AAFPermission(perm.getNs(),perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles())); + if(willLog) { + aaf.access.log(Level.DEBUG, name,"has",perm.getType(),perm.getInstance(),perm.getAction()); + } + } + user.renewPerm(); + return Resp.REVALIDATED; + } else { + int code; + switch(code=fp.code()) { + case 401: + aaf.access.log(Access.Level.ERROR, code, "Unauthorized to make AAF calls"); + break; + default: + aaf.access.log(Access.Level.ERROR, code, fp.body()); + } + return Resp.UNVALIDATED; + } + } + }); + return rv; + } catch (Exception e) { + aaf.access.log(e,"Calling","/authz/perms/user/"+name); + return Resp.INACCESSIBLE; + } finally { + aaf.access.printf(Level.INFO, "AAFLurPerm: %s %s perms from AAF in %f ms (remote=%f)", + (success.get()?"Reloaded":"Reload Failure"),name,Timing.millis(start),remote.get()); + } + } - @Override - protected boolean isCorrectPermType(Permission pond) { - return pond instanceof AAFPermission; - } + @Override + protected boolean isCorrectPermType(Permission pond) { + return pond instanceof AAFPermission; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) - */ - @Override - public Permission createPerm(String p) { - String[] params = Split.split('|', p); - switch(params.length) { - case 3: - return new AAFPermission(null,params[0],params[1],params[2]); - case 4: - return new AAFPermission(params[0],params[1],params[2],params[3]); - default: - return new LocalPermission(p); - } - } - + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) + */ + @Override + public Permission createPerm(String p) { + String[] params = Split.split('|', p); + switch(params.length) { + case 3: + return new AAFPermission(null,params[0],params[1],params[2]); + case 4: + return new AAFPermission(params[0],params[1],params[2],params[3]); + default: + return new LocalPermission(p); + } + } + } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java index 6159726b..2cfe1227 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java @@ -51,148 +51,148 @@ import org.onap.aaf.cadi.taf.basic.BasicHttpTafResp; import org.onap.aaf.misc.env.APIException; public class AAFTaf extends AbsUserCache implements HttpTaf { - private AAFCon aaf; - private boolean warn; + private AAFCon aaf; + private boolean warn; - public AAFTaf(AAFCon con, boolean turnOnWarning) { - super(con.access,con.cleanInterval,con.highCount, con.usageRefreshTriggerCount); - aaf = con; - warn = turnOnWarning; - } + public AAFTaf(AAFCon con, boolean turnOnWarning) { + super(con.access,con.cleanInterval,con.highCount, con.usageRefreshTriggerCount); + aaf = con; + warn = turnOnWarning; + } - public AAFTaf(AAFCon con, boolean turnOnWarning, AbsUserCache other) { - super(other); - aaf = con; - warn = turnOnWarning; - } - - // Note: Needed for Creation of this Object with Generics - @SuppressWarnings("unchecked") - public AAFTaf(Connector mustBeAAFCon, boolean turnOnWarning, AbsUserCache other) { - this((AAFCon)mustBeAAFCon,turnOnWarning,other); - } + public AAFTaf(AAFCon con, boolean turnOnWarning, AbsUserCache other) { + super(other); + aaf = con; + warn = turnOnWarning; + } + + // Note: Needed for Creation of this Object with Generics + @SuppressWarnings("unchecked") + public AAFTaf(Connector mustBeAAFCon, boolean turnOnWarning, AbsUserCache other) { + this((AAFCon)mustBeAAFCon,turnOnWarning,other); + } - // Note: Needed for Creation of this Object with Generics - @SuppressWarnings("unchecked") - public AAFTaf(Connector mustBeAAFCon, boolean turnOnWarning) { - this((AAFCon)mustBeAAFCon,turnOnWarning); - } + // Note: Needed for Creation of this Object with Generics + @SuppressWarnings("unchecked") + public AAFTaf(Connector mustBeAAFCon, boolean turnOnWarning) { + this((AAFCon)mustBeAAFCon,turnOnWarning); + } - public TafResp validate(final LifeForm reading, final HttpServletRequest req, final HttpServletResponse resp) { - //TODO Do we allow just anybody to validate? + public TafResp validate(final LifeForm reading, final HttpServletRequest req, final HttpServletResponse resp) { + //TODO Do we allow just anybody to validate? - // Note: Either Carbon or Silicon based LifeForms ok - String authz = req.getHeader("Authorization"); - if(authz != null && authz.startsWith("Basic ")) { - if(warn&&!req.isSecure()) { - aaf.access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); - } - try { - final CachedBasicPrincipal bp; - if(req.getUserPrincipal() instanceof CachedBasicPrincipal) { - bp = (CachedBasicPrincipal)req.getUserPrincipal(); - } else { - bp = new CachedBasicPrincipal(this,authz,aaf.getRealm(),aaf.userExpires); - } - // First try Cache - final User usr = getUser(bp); - if(usr != null - && usr.principal instanceof GetCred - && Hash.isEqual(bp.getCred(),((GetCred)usr.principal).getCred())) { - return new BasicHttpTafResp(aaf.access,bp,bp.getName()+" authenticated by cached AAF password",RESP.IS_AUTHENTICATED,resp,aaf.getRealm(),false); - } + // Note: Either Carbon or Silicon based LifeForms ok + String authz = req.getHeader("Authorization"); + if(authz != null && authz.startsWith("Basic ")) { + if(warn&&!req.isSecure()) { + aaf.access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); + } + try { + final CachedBasicPrincipal bp; + if(req.getUserPrincipal() instanceof CachedBasicPrincipal) { + bp = (CachedBasicPrincipal)req.getUserPrincipal(); + } else { + bp = new CachedBasicPrincipal(this,authz,aaf.getRealm(),aaf.userExpires); + } + // First try Cache + final User usr = getUser(bp); + if(usr != null + && usr.principal instanceof GetCred + && Hash.isEqual(bp.getCred(),((GetCred)usr.principal).getCred())) { + return new BasicHttpTafResp(aaf.access,bp,bp.getName()+" authenticated by cached AAF password",RESP.IS_AUTHENTICATED,resp,aaf.getRealm(),false); + } - Miss miss = missed(bp.getName(), bp.getCred()); - if(miss!=null && !miss.mayContinue()) { - return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, - "User/Pass Retry limit exceeded"), - RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),true); - } - - return aaf.bestForUser( - new GetSetter() { - @Override - public SecuritySetter get(AAFCon con) throws CadiException { - return con.basicAuthSS(bp); - } - },new Retryable() { - @Override - public BasicHttpTafResp code(Rcli client) throws CadiException, APIException { - Future fp = client.read("/authn/basicAuth", "text/plain"); - if(fp.get(aaf.timeout)) { - if(usr!=null) { - usr.principal = bp; - } else { - addUser(new User(bp,aaf.userExpires)); - } - return new BasicHttpTafResp(aaf.access,bp,bp.getName()+" authenticated by AAF password",RESP.IS_AUTHENTICATED,resp,aaf.getRealm(),false); - } else { - // Note: AddMiss checks for miss==null, and is part of logic - boolean rv= addMiss(bp.getName(),bp.getCred()); - if(rv) { - return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, - "user/pass combo invalid via AAF from " + req.getRemoteAddr()), - RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),true); - } else { - return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, - "user/pass combo invalid via AAF from " + req.getRemoteAddr() + " - Retry limit exceeded"), - RESP.FAIL,resp,aaf.getRealm(),true); - } - } - } - } - ); - } catch (IOException e) { - String msg = buildMsg(null,req,"Invalid Auth Token"); - aaf.access.log(Level.WARN,msg,'(', e.getMessage(), ')'); - return new BasicHttpTafResp(aaf.access,null,msg, RESP.TRY_AUTHENTICATING, resp, aaf.getRealm(),true); - } catch (Exception e) { - String msg = buildMsg(null,req,"Authenticating Service unavailable"); - try { - aaf.invalidate(); - } catch (CadiException e1) { - aaf.access.log(e1, "Error Invalidating Client"); - } - aaf.access.log(Level.WARN,msg,'(', e.getMessage(), ')'); - return new BasicHttpTafResp(aaf.access,null,msg, RESP.FAIL, resp, aaf.getRealm(),false); - } - } - return new BasicHttpTafResp(aaf.access,null,"Requesting HTTP Basic Authorization",RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),false); - } - - private String buildMsg(Principal pr, HttpServletRequest req, Object... msg) { - StringBuilder sb = new StringBuilder(); - for(Object s : msg) { - sb.append(s.toString()); - } - if(pr!=null) { - sb.append(" for "); - sb.append(pr.getName()); - } - sb.append(" from "); - sb.append(req.getRemoteAddr()); - sb.append(':'); - sb.append(req.getRemotePort()); - return sb.toString(); - } + Miss miss = missed(bp.getName(), bp.getCred()); + if(miss!=null && !miss.mayContinue()) { + return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, + "User/Pass Retry limit exceeded"), + RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),true); + } + + return aaf.bestForUser( + new GetSetter() { + @Override + public SecuritySetter get(AAFCon con) throws CadiException { + return con.basicAuthSS(bp); + } + },new Retryable() { + @Override + public BasicHttpTafResp code(Rcli client) throws CadiException, APIException { + Future fp = client.read("/authn/basicAuth", "text/plain"); + if(fp.get(aaf.timeout)) { + if(usr!=null) { + usr.principal = bp; + } else { + addUser(new User(bp,aaf.userExpires)); + } + return new BasicHttpTafResp(aaf.access,bp,bp.getName()+" authenticated by AAF password",RESP.IS_AUTHENTICATED,resp,aaf.getRealm(),false); + } else { + // Note: AddMiss checks for miss==null, and is part of logic + boolean rv= addMiss(bp.getName(),bp.getCred()); + if(rv) { + return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, + "user/pass combo invalid via AAF from " + req.getRemoteAddr()), + RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),true); + } else { + return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, + "user/pass combo invalid via AAF from " + req.getRemoteAddr() + " - Retry limit exceeded"), + RESP.FAIL,resp,aaf.getRealm(),true); + } + } + } + } + ); + } catch (IOException e) { + String msg = buildMsg(null,req,"Invalid Auth Token"); + aaf.access.log(Level.WARN,msg,'(', e.getMessage(), ')'); + return new BasicHttpTafResp(aaf.access,null,msg, RESP.TRY_AUTHENTICATING, resp, aaf.getRealm(),true); + } catch (Exception e) { + String msg = buildMsg(null,req,"Authenticating Service unavailable"); + try { + aaf.invalidate(); + } catch (CadiException e1) { + aaf.access.log(e1, "Error Invalidating Client"); + } + aaf.access.log(Level.WARN,msg,'(', e.getMessage(), ')'); + return new BasicHttpTafResp(aaf.access,null,msg, RESP.FAIL, resp, aaf.getRealm(),false); + } + } + return new BasicHttpTafResp(aaf.access,null,"Requesting HTTP Basic Authorization",RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),false); + } + + private String buildMsg(Principal pr, HttpServletRequest req, Object... msg) { + StringBuilder sb = new StringBuilder(); + for(Object s : msg) { + sb.append(s.toString()); + } + if(pr!=null) { + sb.append(" for "); + sb.append(pr.getName()); + } + sb.append(" from "); + sb.append(req.getRemoteAddr()); + sb.append(':'); + sb.append(req.getRemotePort()); + return sb.toString(); + } - - public Resp revalidate(CachedPrincipal prin, Object state) { - // !!!! TEST THIS.. Things may not be revalidated, if not BasicPrincipal - if(prin instanceof BasicPrincipal) { - Future fp; - try { - Rcli userAAF = aaf.client(Config.AAF_DEFAULT_VERSION).forUser(aaf.transferSS((BasicPrincipal)prin)); - fp = userAAF.read("/authn/basicAuth", "text/plain"); - return fp.get(aaf.timeout)?Resp.REVALIDATED:Resp.UNVALIDATED; - } catch (Exception e) { - aaf.access.log(e, "Cannot Revalidate",prin.getName()); - return Resp.INACCESSIBLE; - } - } - return Resp.NOT_MINE; - } + + public Resp revalidate(CachedPrincipal prin, Object state) { + // !!!! TEST THIS.. Things may not be revalidated, if not BasicPrincipal + if(prin instanceof BasicPrincipal) { + Future fp; + try { + Rcli userAAF = aaf.client(Config.AAF_DEFAULT_VERSION).forUser(aaf.transferSS((BasicPrincipal)prin)); + fp = userAAF.read("/authn/basicAuth", "text/plain"); + return fp.get(aaf.timeout)?Resp.REVALIDATED:Resp.UNVALIDATED; + } catch (Exception e) { + aaf.access.log(e, "Cannot Revalidate",prin.getName()); + return Resp.INACCESSIBLE; + } + } + return Resp.NOT_MINE; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java index bf85beef..db6ae963 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java @@ -36,91 +36,91 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.util.Split; public class AAFTrustChecker implements TrustChecker { - private final String tag, id; - private final AAFPermission perm; - private Lur lur; + private final String tag, id; + private final AAFPermission perm; + private Lur lur; - /** - * - * Instance will be replaced by Identity - * @param lur - * - * @param tag - * @param perm - */ - public AAFTrustChecker(final Env env) { - tag = env.getProperty(Config.CADI_USER_CHAIN_TAG, Config.CADI_USER_CHAIN); - id = env.getProperty(Config.CADI_ALIAS,env.getProperty(Config.AAF_APPID)); // share between components - String str = env.getProperty(Config.CADI_TRUST_PERM); - AAFPermission temp=null; - if(str!=null) { - String[] sp = Split.splitTrim('|', str); - switch(sp.length) { - case 3: - temp = new AAFPermission(null,sp[0],sp[1],sp[2]); - break; - case 4: - temp = new AAFPermission(sp[0],sp[1],sp[2],sp[3]); - break; - } - } - perm=temp; - } + /** + * + * Instance will be replaced by Identity + * @param lur + * + * @param tag + * @param perm + */ + public AAFTrustChecker(final Env env) { + tag = env.getProperty(Config.CADI_USER_CHAIN_TAG, Config.CADI_USER_CHAIN); + id = env.getProperty(Config.CADI_ALIAS,env.getProperty(Config.AAF_APPID)); // share between components + String str = env.getProperty(Config.CADI_TRUST_PERM); + AAFPermission temp=null; + if(str!=null) { + String[] sp = Split.splitTrim('|', str); + switch(sp.length) { + case 3: + temp = new AAFPermission(null,sp[0],sp[1],sp[2]); + break; + case 4: + temp = new AAFPermission(sp[0],sp[1],sp[2],sp[3]); + break; + } + } + perm=temp; + } - public AAFTrustChecker(final Access access) { - tag = access.getProperty(Config.CADI_USER_CHAIN_TAG, Config.CADI_USER_CHAIN); - id = access.getProperty(Config.CADI_ALIAS,access.getProperty(Config.AAF_APPID,null)); // share between components - String str = access.getProperty(Config.CADI_TRUST_PERM,null); - AAFPermission temp=null; - if(str!=null) { - String[] sp = Split.splitTrim('|', str); - switch(sp.length) { - case 3: - temp = new AAFPermission(null,sp[0],sp[1],sp[2]); - break; - case 4: - temp = new AAFPermission(sp[0],sp[1],sp[2],sp[3]); - break; - } - } - perm=temp; - } + public AAFTrustChecker(final Access access) { + tag = access.getProperty(Config.CADI_USER_CHAIN_TAG, Config.CADI_USER_CHAIN); + id = access.getProperty(Config.CADI_ALIAS,access.getProperty(Config.AAF_APPID,null)); // share between components + String str = access.getProperty(Config.CADI_TRUST_PERM,null); + AAFPermission temp=null; + if(str!=null) { + String[] sp = Split.splitTrim('|', str); + switch(sp.length) { + case 3: + temp = new AAFPermission(null,sp[0],sp[1],sp[2]); + break; + case 4: + temp = new AAFPermission(sp[0],sp[1],sp[2],sp[3]); + break; + } + } + perm=temp; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.TrustChecker#setLur(org.onap.aaf.cadi.Lur) - */ - @Override - public void setLur(Lur lur) { - this.lur = lur; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.TrustChecker#setLur(org.onap.aaf.cadi.Lur) + */ + @Override + public void setLur(Lur lur) { + this.lur = lur; + } - @Override - public TafResp mayTrust(TafResp tresp, HttpServletRequest req) { - String user_info = req.getHeader(tag); - if (user_info == null) { - return tresp; - } + @Override + public TafResp mayTrust(TafResp tresp, HttpServletRequest req) { + String user_info = req.getHeader(tag); + if (user_info == null) { + return tresp; + } - String[] info = Split.split(',', user_info); - String[] flds = Split.splitTrim(':', info[0]); - if (flds.length < 4) { - return tresp; - } - if (!("AS".equals(flds[3]))) { // is it set for "AS" - return tresp; - } + String[] info = Split.split(',', user_info); + String[] flds = Split.splitTrim(':', info[0]); + if (flds.length < 4) { + return tresp; + } + if (!("AS".equals(flds[3]))) { // is it set for "AS" + return tresp; + } - String principalName = tresp.getPrincipal().getName(); - if(principalName.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept - || lur.fish(tresp.getPrincipal(), perm)) { // Have Perm set by Config.CADI_TRUST_PERM - String desc = " " + flds[0] + " validated using " + flds[2] + " by " + flds[1] + ','; - return new TrustTafResp(tresp, new TrustPrincipal(tresp.getPrincipal(), flds[0]), desc); - } else if(principalName.equals(flds[0])) { // Ignore if same identity - return tresp; - } else { - String desc = tresp.getPrincipal().getName() + " requested trust as " + flds[0] + ", but does not have Authorization"; - return new TrustNotTafResp(tresp, desc); - } - } + String principalName = tresp.getPrincipal().getName(); + if(principalName.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept + || lur.fish(tresp.getPrincipal(), perm)) { // Have Perm set by Config.CADI_TRUST_PERM + String desc = " " + flds[0] + " validated using " + flds[2] + " by " + flds[1] + ','; + return new TrustTafResp(tresp, new TrustPrincipal(tresp.getPrincipal(), flds[0]), desc); + } else if(principalName.equals(flds[0])) { // Ignore if same identity + return tresp; + } else { + String desc = tresp.getPrincipal().getName() + " requested trust as " + flds[0] + ", but does not have Authorization"; + return new TrustNotTafResp(tresp, desc); + } + } } \ No newline at end of file diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java index fca23740..3f6d7475 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java @@ -44,462 +44,462 @@ import org.onap.aaf.misc.env.util.Split; import locate.v1_0.Endpoint; public abstract class AbsAAFLocator implements Locator { - protected static final SecureRandom sr = new SecureRandom(); - private static LocatorCreator locatorCreator; - protected final Access access; - - protected final double latitude; - protected final double longitude; - protected List epList; - protected final String name, version; - private String pathInfo = null; - private String query = null; - private String fragment = null; - private boolean additional = false; - protected String myhostname; - protected int myport; - protected final String aaf_locator_host; - protected final URI aaf_locator_uri; - private long earliest; - private final long refreshWait; - - - public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException { - aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL, null); - if(aaf_locator_host==null) { - aaf_locator_uri = null; - } else { - try { - aaf_locator_uri = new URI(aaf_locator_host); - } catch (URISyntaxException e) { - throw new LocatorException(e); - } - } - - epList = new LinkedList<>(); - refreshWait = refreshMin; - - this.access = access; - String lat = access.getProperty(Config.CADI_LATITUDE,null); - String lng = access.getProperty(Config.CADI_LONGITUDE,null); - if(lat==null || lng==null) { - throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required."); - } else { - latitude = Double.parseDouble(lat); - longitude = Double.parseDouble(lng); - } - if(name.startsWith(Defaults.AAF_NS)) { - String root_ns = access.getProperty(Config.AAF_ROOT_NS, null); - if(root_ns!=null) { - name=name.replace(Defaults.AAF_NS, root_ns); - } - } - if(name.startsWith("http")) { // simple URL - this.name = name; - this.version = Config.AAF_DEFAULT_VERSION; - } else { - String[] split = Split.split(':', name); - this.name = split[0]; - this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION; - } - - } - - /** - * This is the way to setup specialized AAFLocators ahead of time. - * @param preload - */ - public static void setCreator(LocatorCreator lc) { - locatorCreator = lc; - } - - public static Locator create(String key) throws LocatorException { - String name = null; - String version = Config.AAF_DEFAULT_VERSION; - String pathInfo = null; - int prev = key.indexOf("/locate"); - if(prev>0) { - prev = key.indexOf('/',prev+6); - if(prev>0) { - int next = key.indexOf('/',++prev); - if(next>0) { - name = key.substring(prev, next); - pathInfo=key.substring(next); - } else { - name = key.substring(prev); - } - String[] split = Split.split(':', name); - switch(split.length) { - case 3: - case 2: - version = split[1]; - name = split[0]; - break; - default: - break; - } - } - } - - if(key.startsWith("http")) { - if(name!=null) { - if(locatorCreator != null) { - AbsAAFLocator aal = locatorCreator.create(name, version); - if(pathInfo!=null) { - aal.setPathInfo(pathInfo); - } - return aal; - } - } else { - return new PropertyLocator(key); - } - } - return null; - } - - public static Locator create(final String name, final String version) throws LocatorException { - return locatorCreator.create(name, version); - } - - public interface LocatorCreator { - public AbsAAFLocator create(String key, String version) throws LocatorException; - public void setSelf(String hostname, int port); - } - - protected static String nameFromLocatorURI(URI locatorURI) { - String[] path = Split.split('/', locatorURI.getPath()); - if(path.length>2 && "locate".equals(path[1])) { - return path[2]; - } else { - return locatorURI.toString(); - } - } - - /** - * Setting "self" excludes this service from the list. Critical for contacting peers. - */ - public void setSelf(final String hostname, final int port) { - myhostname=hostname; - myport=port; - } - - - public static void setCreatorSelf(final String hostname, final int port) { - if(locatorCreator!=null) { - locatorCreator.setSelf(hostname,port); - } - } - - protected final synchronized void replace(List list) { - epList = list; - } - - /** - * Call _refresh as needed during calls, but actual refresh will not occur if there - * are existing entities or if it has been called in the last 10 (settable) seconds. - * Timed Refreshes happen by Scheduled Thread - */ - private final boolean _refresh() { - boolean rv = false; - long now=System.currentTimeMillis(); - if(noEntries()) { - if(earliest iter = epList.iterator(); iter.hasNext(); ) { - EP ep = iter.next(); - if(ep.valid) { - return true; - } - } - isEmpty = true; - } - if(_refresh()) { // is refreshed... check again - isEmpty = epList.isEmpty(); - } - return !isEmpty; - } - - @Override - public void invalidate(Item item) throws LocatorException { - if(item!=null) { - if(item instanceof AAFLItem) { - AAFLItem ali =(AAFLItem)item; - EP ep = ali.ep; - synchronized(epList) { - epList.remove(ep); - } - ep.invalid(); - ali.iter = getIterator(); // for next guy... fresh iterator - } else { - throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator"); - } - } - } - - @Override - public Item best() throws LocatorException { - if(!hasItems()) { - throw new LocatorException("No Entries found for '" + aaf_locator_uri.toString() + "/locate/" + name + ':' + version + '\''); - } - List lep = new ArrayList<>(); - EP first = null; - // Note: Deque is sorted on the way by closest distance - Iterator iter = getIterator(); - EP ep; - while(iter.hasNext()) { - ep = iter.next(); - if(ep.valid) { - if(first==null) { - first = ep; - lep.add(first); - } else { - if(Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues. - lep.add(ep); - } else { - break; - } - } - } - } - switch(lep.size()) { - case 0: - return null; - case 1: - return new AAFLItem(iter,first); - default: - int rand = sr.nextInt(); // Sonar chokes without. - int i = Math.abs(rand)%lep.size(); - if(i<0) { - return null; - } else { - return new AAFLItem(iter,lep.get(i)); - } - - } - } - - private Iterator getIterator() { - Object[] epa = epList.toArray(); - if(epa.length==0) { - _refresh(); - epa = epList.toArray(); - } - return new EPIterator(epa, epList); - } - - public class EPIterator implements Iterator { - private final Object[] epa; - private final List epList; - private int idx; - - public EPIterator(Object[] epa, List epList) { - this.epa = epa; - this.epList = epList; - idx = epa.length>0?0:-1; - } - - @Override - public boolean hasNext() { - if(idx<0) { - return false; - } else { - Object obj; - while(idx=0 && idx iter = getIterator(); - EP ep = AAFLItem.next(iter); - if(ep==null) { - return null; - } - return new AAFLItem(iter,ep); - } - - @Override - public Item next(Item prev) throws LocatorException { - if(prev==null) { - StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null."); - int lines = 0; - for(StackTraceElement st : Thread.currentThread().getStackTrace()) { - sb.append("\n\t"); - sb.append(st.toString()); - if(++lines > 5) { - sb.append("\n\t..."); - break; - } - } - access.log(Level.ERROR, sb); - } else { - if(prev instanceof AAFLItem) { - AAFLItem ali = (AAFLItem)prev; - EP ep = AAFLItem.next(ali.iter); - if(ep!=null) { - return new AAFLItem(ali.iter,ep); - } - } else { - throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator"); - } - } - return null; - } - - protected static class AAFLItem implements Item { - private Iterator iter; - private URI uri; - private EP ep; - - public AAFLItem(Iterator iter, EP ep) { - this.iter = iter; - this.ep = ep; - uri = ep.uri; - } - - private static EP next(Iterator iter) { - EP ep=null; - while(iter.hasNext() && (ep==null || !ep.valid)) { - ep = iter.next(); - } - return ep; - } - - public String toString() { - return ep==null?"Locator Item Invalid":ep.toString(); - } - } - - protected static class EP implements Comparable { - private URI uri; - private final double distance; - private boolean valid; - - public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException { - uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null); - distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude()); - valid = true; - } - - public void invalid() { - valid = false; - } - - @Override - public int compareTo(EP o) { - if(distanceo.distance) { - return 1; - } else { - return 0; - } - } - - @Override - public String toString() { - return distance + ": " + uri + (valid?" valid":" invalidate"); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Locator#destroy() - */ - @Override - public void destroy() { - // Nothing to do - } - - @Override - public String toString() { - return "AAFLocator for " + name + " on " + getURI(); - } - - public AbsAAFLocator setPathInfo(String pathInfo) { - this.pathInfo = pathInfo; - additional=true; - return this; - } - - public AbsAAFLocator setQuery(String query) { - this.query = query; - additional=true; - return this; - } - - public AbsAAFLocator setFragment(String fragment) { - this.fragment = fragment; - additional=true; - return this; - } - - // Core URI, for reporting purposes - protected abstract URI getURI(); - - protected URI getURI(URI rv) throws LocatorException { - if(additional) { - try { - return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment); - } catch (URISyntaxException e) { - throw new LocatorException("Error copying URL", e); - } - } - return rv; - } + protected static final SecureRandom sr = new SecureRandom(); + private static LocatorCreator locatorCreator; + protected final Access access; + + protected final double latitude; + protected final double longitude; + protected List epList; + protected final String name, version; + private String pathInfo = null; + private String query = null; + private String fragment = null; + private boolean additional = false; + protected String myhostname; + protected int myport; + protected final String aaf_locator_host; + protected final URI aaf_locator_uri; + private long earliest; + private final long refreshWait; + + + public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException { + aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL, null); + if(aaf_locator_host==null) { + aaf_locator_uri = null; + } else { + try { + aaf_locator_uri = new URI(aaf_locator_host); + } catch (URISyntaxException e) { + throw new LocatorException(e); + } + } + + epList = new LinkedList<>(); + refreshWait = refreshMin; + + this.access = access; + String lat = access.getProperty(Config.CADI_LATITUDE,null); + String lng = access.getProperty(Config.CADI_LONGITUDE,null); + if(lat==null || lng==null) { + throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required."); + } else { + latitude = Double.parseDouble(lat); + longitude = Double.parseDouble(lng); + } + if(name.startsWith(Defaults.AAF_NS)) { + String root_ns = access.getProperty(Config.AAF_ROOT_NS, null); + if(root_ns!=null) { + name=name.replace(Defaults.AAF_NS, root_ns); + } + } + if(name.startsWith("http")) { // simple URL + this.name = name; + this.version = Config.AAF_DEFAULT_VERSION; + } else { + String[] split = Split.split(':', name); + this.name = split[0]; + this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION; + } + + } + + /** + * This is the way to setup specialized AAFLocators ahead of time. + * @param preload + */ + public static void setCreator(LocatorCreator lc) { + locatorCreator = lc; + } + + public static Locator create(String key) throws LocatorException { + String name = null; + String version = Config.AAF_DEFAULT_VERSION; + String pathInfo = null; + int prev = key.indexOf("/locate"); + if(prev>0) { + prev = key.indexOf('/',prev+6); + if(prev>0) { + int next = key.indexOf('/',++prev); + if(next>0) { + name = key.substring(prev, next); + pathInfo=key.substring(next); + } else { + name = key.substring(prev); + } + String[] split = Split.split(':', name); + switch(split.length) { + case 3: + case 2: + version = split[1]; + name = split[0]; + break; + default: + break; + } + } + } + + if(key.startsWith("http")) { + if(name!=null) { + if(locatorCreator != null) { + AbsAAFLocator aal = locatorCreator.create(name, version); + if(pathInfo!=null) { + aal.setPathInfo(pathInfo); + } + return aal; + } + } else { + return new PropertyLocator(key); + } + } + return null; + } + + public static Locator create(final String name, final String version) throws LocatorException { + return locatorCreator.create(name, version); + } + + public interface LocatorCreator { + public AbsAAFLocator create(String key, String version) throws LocatorException; + public void setSelf(String hostname, int port); + } + + protected static String nameFromLocatorURI(URI locatorURI) { + String[] path = Split.split('/', locatorURI.getPath()); + if(path.length>2 && "locate".equals(path[1])) { + return path[2]; + } else { + return locatorURI.toString(); + } + } + + /** + * Setting "self" excludes this service from the list. Critical for contacting peers. + */ + public void setSelf(final String hostname, final int port) { + myhostname=hostname; + myport=port; + } + + + public static void setCreatorSelf(final String hostname, final int port) { + if(locatorCreator!=null) { + locatorCreator.setSelf(hostname,port); + } + } + + protected final synchronized void replace(List list) { + epList = list; + } + + /** + * Call _refresh as needed during calls, but actual refresh will not occur if there + * are existing entities or if it has been called in the last 10 (settable) seconds. + * Timed Refreshes happen by Scheduled Thread + */ + private final boolean _refresh() { + boolean rv = false; + long now=System.currentTimeMillis(); + if(noEntries()) { + if(earliest iter = epList.iterator(); iter.hasNext(); ) { + EP ep = iter.next(); + if(ep.valid) { + return true; + } + } + isEmpty = true; + } + if(_refresh()) { // is refreshed... check again + isEmpty = epList.isEmpty(); + } + return !isEmpty; + } + + @Override + public void invalidate(Item item) throws LocatorException { + if(item!=null) { + if(item instanceof AAFLItem) { + AAFLItem ali =(AAFLItem)item; + EP ep = ali.ep; + synchronized(epList) { + epList.remove(ep); + } + ep.invalid(); + ali.iter = getIterator(); // for next guy... fresh iterator + } else { + throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator"); + } + } + } + + @Override + public Item best() throws LocatorException { + if(!hasItems()) { + throw new LocatorException("No Entries found for '" + aaf_locator_uri.toString() + "/locate/" + name + ':' + version + '\''); + } + List lep = new ArrayList<>(); + EP first = null; + // Note: Deque is sorted on the way by closest distance + Iterator iter = getIterator(); + EP ep; + while(iter.hasNext()) { + ep = iter.next(); + if(ep.valid) { + if(first==null) { + first = ep; + lep.add(first); + } else { + if(Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues. + lep.add(ep); + } else { + break; + } + } + } + } + switch(lep.size()) { + case 0: + return null; + case 1: + return new AAFLItem(iter,first); + default: + int rand = sr.nextInt(); // Sonar chokes without. + int i = Math.abs(rand)%lep.size(); + if(i<0) { + return null; + } else { + return new AAFLItem(iter,lep.get(i)); + } + + } + } + + private Iterator getIterator() { + Object[] epa = epList.toArray(); + if(epa.length==0) { + _refresh(); + epa = epList.toArray(); + } + return new EPIterator(epa, epList); + } + + public class EPIterator implements Iterator { + private final Object[] epa; + private final List epList; + private int idx; + + public EPIterator(Object[] epa, List epList) { + this.epa = epa; + this.epList = epList; + idx = epa.length>0?0:-1; + } + + @Override + public boolean hasNext() { + if(idx<0) { + return false; + } else { + Object obj; + while(idx=0 && idx iter = getIterator(); + EP ep = AAFLItem.next(iter); + if(ep==null) { + return null; + } + return new AAFLItem(iter,ep); + } + + @Override + public Item next(Item prev) throws LocatorException { + if(prev==null) { + StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null."); + int lines = 0; + for(StackTraceElement st : Thread.currentThread().getStackTrace()) { + sb.append("\n\t"); + sb.append(st.toString()); + if(++lines > 5) { + sb.append("\n\t..."); + break; + } + } + access.log(Level.ERROR, sb); + } else { + if(prev instanceof AAFLItem) { + AAFLItem ali = (AAFLItem)prev; + EP ep = AAFLItem.next(ali.iter); + if(ep!=null) { + return new AAFLItem(ali.iter,ep); + } + } else { + throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator"); + } + } + return null; + } + + protected static class AAFLItem implements Item { + private Iterator iter; + private URI uri; + private EP ep; + + public AAFLItem(Iterator iter, EP ep) { + this.iter = iter; + this.ep = ep; + uri = ep.uri; + } + + private static EP next(Iterator iter) { + EP ep=null; + while(iter.hasNext() && (ep==null || !ep.valid)) { + ep = iter.next(); + } + return ep; + } + + public String toString() { + return ep==null?"Locator Item Invalid":ep.toString(); + } + } + + protected static class EP implements Comparable { + private URI uri; + private final double distance; + private boolean valid; + + public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException { + uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null); + distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude()); + valid = true; + } + + public void invalid() { + valid = false; + } + + @Override + public int compareTo(EP o) { + if(distanceo.distance) { + return 1; + } else { + return 0; + } + } + + @Override + public String toString() { + return distance + ": " + uri + (valid?" valid":" invalidate"); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Locator#destroy() + */ + @Override + public void destroy() { + // Nothing to do + } + + @Override + public String toString() { + return "AAFLocator for " + name + " on " + getURI(); + } + + public AbsAAFLocator setPathInfo(String pathInfo) { + this.pathInfo = pathInfo; + additional=true; + return this; + } + + public AbsAAFLocator setQuery(String query) { + this.query = query; + additional=true; + return this; + } + + public AbsAAFLocator setFragment(String fragment) { + this.fragment = fragment; + additional=true; + return this; + } + + // Core URI, for reporting purposes + protected abstract URI getURI(); + + protected URI getURI(URI rv) throws LocatorException { + if(additional) { + try { + return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment); + } catch (URISyntaxException e) { + throw new LocatorException("Error copying URL", e); + } + } + return rv; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java index 89106cc1..e347ffb6 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java @@ -38,264 +38,264 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.util.Split; public abstract class AbsAAFLur extends AbsUserCache implements CachingLur { - protected static final byte[] BLANK_PASSWORD = new byte[0]; - private String[] debug = null; - public AAFCon aaf; - public Lur preemptiveLur=null; // Initial Use is for OAuth2, preemptive Lur - private String[] supports; + protected static final byte[] BLANK_PASSWORD = new byte[0]; + private String[] debug = null; + public AAFCon aaf; + public Lur preemptiveLur=null; // Initial Use is for OAuth2, preemptive Lur + private String[] supports; - public AbsAAFLur(AAFCon con) throws APIException { - super(con.access, con.cleanInterval, con.highCount, con.usageRefreshTriggerCount); - aaf = con; - setLur(this); - supports = con.access.getProperty(Config.AAF_DOMAIN_SUPPORT, Config.AAF_DOMAIN_SUPPORT_DEF).split("\\s*:\\s*"); - } + public AbsAAFLur(AAFCon con) throws APIException { + super(con.access, con.cleanInterval, con.highCount, con.usageRefreshTriggerCount); + aaf = con; + setLur(this); + supports = con.access.getProperty(Config.AAF_DOMAIN_SUPPORT, Config.AAF_DOMAIN_SUPPORT_DEF).split("\\s*:\\s*"); + } - public AbsAAFLur(AAFCon con, AbsUserCache auc) throws APIException { - super(auc); - aaf = con; - setLur(this); - supports = con.access.getProperty(Config.AAF_DOMAIN_SUPPORT, Config.AAF_DOMAIN_SUPPORT_DEF).split("\\s*:\\s*"); - } + public AbsAAFLur(AAFCon con, AbsUserCache auc) throws APIException { + super(auc); + aaf = con; + setLur(this); + supports = con.access.getProperty(Config.AAF_DOMAIN_SUPPORT, Config.AAF_DOMAIN_SUPPORT_DEF).split("\\s*:\\s*"); + } - @Override - public void setDebug(String ids) { - this.debug = ids==null?null:Split.split(',', ids); - } - - public void setPreemptiveLur(Lur preemptive) { - this.preemptiveLur = preemptive; - } - - protected abstract User loadUser(Principal bait); + @Override + public void setDebug(String ids) { + this.debug = ids==null?null:Split.split(',', ids); + } + + public void setPreemptiveLur(Lur preemptive) { + this.preemptiveLur = preemptive; + } + + protected abstract User loadUser(Principal bait); - @Override - public final boolean handles(Principal principal) { - if(preemptiveLur!=null) { - if(preemptiveLur.handles(principal)) { - return true; - } - } - String userName=principal.getName(); - if(userName!=null) { - for(String s : supports) { - if(userName.endsWith(s)) - return true; - } - } - return false; - } + @Override + public final boolean handles(Principal principal) { + if(preemptiveLur!=null) { + if(preemptiveLur.handles(principal)) { + return true; + } + } + String userName=principal.getName(); + if(userName!=null) { + for(String s : supports) { + if(userName.endsWith(s)) + return true; + } + } + return false; + } - - protected abstract boolean isCorrectPermType(Permission pond); - - // This is where you build AAF CLient Code. Answer the question "Is principal "bait" in the "pond" - public boolean fish(Principal bait, Permission ... pond) { - if(preemptiveLur!=null && preemptiveLur.handles(bait)) { - return preemptiveLur.fish(bait, pond); - } else { - if(pond==null) { - return false; - } - if(isDebug(bait)) { - boolean rv = false; - StringBuilder sb = new StringBuilder("Log for "); - sb.append(bait); - if(handles(bait)) { - User user = getUser(bait); - if(user==null) { - sb.append("\n\tUser is not in Cache"); - } else { - if(user.noPerms()) { - sb.append("\n\tUser has no Perms"); - } - if(user.permExpired()) { - sb.append("\n\tUser's perm expired ["); - sb.append(new Date(user.permExpires())); - sb.append(']'); - } else { - sb.append("\n\tUser's perm expires ["); - sb.append(new Date(user.permExpires())); - sb.append(']'); - } - } - if(user==null || user.permsUnloaded() || user.permExpired()) { - user = loadUser(bait); - sb.append("\n\tloadUser called"); - } - for (Permission p : pond) { - if(user==null) { - sb.append("\n\tUser was not Loaded"); - break; - } else if(user.contains(p)) { - sb.append("\n\tUser contains "); - sb.append(p.getKey()); - rv = true; - } else { - sb.append("\n\tUser does not contain "); - sb.append(p.getKey()); - List perms = new ArrayList<>(); - user.copyPermsTo(perms); - for(Permission perm : perms) { - sb.append("\n\t\t"); - sb.append(perm.getKey()); - } - } - } - } else { - sb.append("AAF Lur does not support ["); - sb.append(bait); - sb.append("]"); - } - aaf.access.log(Level.INFO, sb); - return rv; - } else { - boolean rv = false; - if(handles(bait)) { - User user = getUser(bait); - if(user==null || user.permsUnloaded() || user.permExpired()) { - user = loadUser(bait); - } - if(user==null) { - return false; - } else { - for(Permission p : pond) { - if(rv=user.contains(p)) { - break; - } - } - } - } - return rv; - } - } - } + + protected abstract boolean isCorrectPermType(Permission pond); + + // This is where you build AAF CLient Code. Answer the question "Is principal "bait" in the "pond" + public boolean fish(Principal bait, Permission ... pond) { + if(preemptiveLur!=null && preemptiveLur.handles(bait)) { + return preemptiveLur.fish(bait, pond); + } else { + if(pond==null) { + return false; + } + if(isDebug(bait)) { + boolean rv = false; + StringBuilder sb = new StringBuilder("Log for "); + sb.append(bait); + if(handles(bait)) { + User user = getUser(bait); + if(user==null) { + sb.append("\n\tUser is not in Cache"); + } else { + if(user.noPerms()) { + sb.append("\n\tUser has no Perms"); + } + if(user.permExpired()) { + sb.append("\n\tUser's perm expired ["); + sb.append(new Date(user.permExpires())); + sb.append(']'); + } else { + sb.append("\n\tUser's perm expires ["); + sb.append(new Date(user.permExpires())); + sb.append(']'); + } + } + if(user==null || user.permsUnloaded() || user.permExpired()) { + user = loadUser(bait); + sb.append("\n\tloadUser called"); + } + for (Permission p : pond) { + if(user==null) { + sb.append("\n\tUser was not Loaded"); + break; + } else if(user.contains(p)) { + sb.append("\n\tUser contains "); + sb.append(p.getKey()); + rv = true; + } else { + sb.append("\n\tUser does not contain "); + sb.append(p.getKey()); + List perms = new ArrayList<>(); + user.copyPermsTo(perms); + for(Permission perm : perms) { + sb.append("\n\t\t"); + sb.append(perm.getKey()); + } + } + } + } else { + sb.append("AAF Lur does not support ["); + sb.append(bait); + sb.append("]"); + } + aaf.access.log(Level.INFO, sb); + return rv; + } else { + boolean rv = false; + if(handles(bait)) { + User user = getUser(bait); + if(user==null || user.permsUnloaded() || user.permExpired()) { + user = loadUser(bait); + } + if(user==null) { + return false; + } else { + for(Permission p : pond) { + if(rv=user.contains(p)) { + break; + } + } + } + } + return rv; + } + } + } - public void fishAll(Principal bait, List perms) { - if(preemptiveLur!=null && preemptiveLur.handles(bait)) { - preemptiveLur.fishAll(bait, perms); - } else { - if(isDebug(bait)) { - StringBuilder sb = new StringBuilder("Log for "); - sb.append(bait); - if(handles(bait)) { - User user = getUser(bait); - if(user==null) { - sb.append("\n\tUser is not in Cache"); - } else { - if(user.noPerms()) { - sb.append("\n\tUser has no Perms"); - } - if(user.permExpired()) { - sb.append("\n\tUser's perm expired ["); - sb.append(new Date(user.permExpires())); - sb.append(']'); - } else { - sb.append("\n\tUser's perm expires ["); - sb.append(new Date(user.permExpires())); - sb.append(']'); - } - } - if(user==null || user.permsUnloaded() || user.permExpired()) { - user = loadUser(bait); - sb.append("\n\tloadUser called"); - } - if(user==null) { - sb.append("\n\tUser was not Loaded"); - } else { - sb.append("\n\tCopying Perms "); - user.copyPermsTo(perms); - for(Permission p : perms) { - sb.append("\n\t\t"); - sb.append(p.getKey()); - } - } - } else { - sb.append("AAF Lur does not support ["); - sb.append(bait); - sb.append("]"); - } - aaf.access.log(Level.INFO, sb); - } else { - if(handles(bait)) { - User user = getUser(bait); - if(user==null || user.permsUnloaded() || user.permExpired()) { - user = loadUser(bait); - } - if(user!=null) { - user.copyPermsTo(perms); - } - } - } - } - } - - @Override - public void remove(String user) { - super.remove(user); - } + public void fishAll(Principal bait, List perms) { + if(preemptiveLur!=null && preemptiveLur.handles(bait)) { + preemptiveLur.fishAll(bait, perms); + } else { + if(isDebug(bait)) { + StringBuilder sb = new StringBuilder("Log for "); + sb.append(bait); + if(handles(bait)) { + User user = getUser(bait); + if(user==null) { + sb.append("\n\tUser is not in Cache"); + } else { + if(user.noPerms()) { + sb.append("\n\tUser has no Perms"); + } + if(user.permExpired()) { + sb.append("\n\tUser's perm expired ["); + sb.append(new Date(user.permExpires())); + sb.append(']'); + } else { + sb.append("\n\tUser's perm expires ["); + sb.append(new Date(user.permExpires())); + sb.append(']'); + } + } + if(user==null || user.permsUnloaded() || user.permExpired()) { + user = loadUser(bait); + sb.append("\n\tloadUser called"); + } + if(user==null) { + sb.append("\n\tUser was not Loaded"); + } else { + sb.append("\n\tCopying Perms "); + user.copyPermsTo(perms); + for(Permission p : perms) { + sb.append("\n\t\t"); + sb.append(p.getKey()); + } + } + } else { + sb.append("AAF Lur does not support ["); + sb.append(bait); + sb.append("]"); + } + aaf.access.log(Level.INFO, sb); + } else { + if(handles(bait)) { + User user = getUser(bait); + if(user==null || user.permsUnloaded() || user.permExpired()) { + user = loadUser(bait); + } + if(user!=null) { + user.copyPermsTo(perms); + } + } + } + } + } + + @Override + public void remove(String user) { + super.remove(user); + } - private boolean isDebug(Principal p) { - if(debug!=null) { - if(debug.length==1 && "all".equals(debug[0])) { - return true; - } - String name = p.getName(); - for(String s : debug) { - if(s.equals(name)) { - return true; - } - } - } - return false; - } - /** - * This special case minimizes loops, avoids multiple Set hits, and calls all the appropriate Actions found. - * - * @param bait - * @param obj - * @param type - * @param instance - * @param actions - */ - public void fishOneOf(Principal princ, A obj, String type, String instance, List> actions) { - User user = getUser(princ); - if(user==null || user.permsUnloaded() || user.permExpired()) { - user = loadUser(princ); - } - if(user!=null) { - ReuseAAFPermission perm = new ReuseAAFPermission(type,instance); - for(Action action : actions) { - perm.setAction(action.getName()); - if(user.contains(perm)) { - if(action.exec(obj))return; - } - } - } - } - - public static interface Action { - public String getName(); - /** - * Return false to continue, True to end now - * @return - */ - public boolean exec(A a); - } - - private class ReuseAAFPermission extends AAFPermission { - public ReuseAAFPermission(String type, String instance) { - super(type,instance,null,null); - } + private boolean isDebug(Principal p) { + if(debug!=null) { + if(debug.length==1 && "all".equals(debug[0])) { + return true; + } + String name = p.getName(); + for(String s : debug) { + if(s.equals(name)) { + return true; + } + } + } + return false; + } + /** + * This special case minimizes loops, avoids multiple Set hits, and calls all the appropriate Actions found. + * + * @param bait + * @param obj + * @param type + * @param instance + * @param actions + */ + public void fishOneOf(Principal princ, A obj, String type, String instance, List> actions) { + User user = getUser(princ); + if(user==null || user.permsUnloaded() || user.permExpired()) { + user = loadUser(princ); + } + if(user!=null) { + ReuseAAFPermission perm = new ReuseAAFPermission(type,instance); + for(Action action : actions) { + perm.setAction(action.getName()); + if(user.contains(perm)) { + if(action.exec(obj))return; + } + } + } + } + + public static interface Action { + public String getName(); + /** + * Return false to continue, True to end now + * @return + */ + public boolean exec(A a); + } + + private class ReuseAAFPermission extends AAFPermission { + public ReuseAAFPermission(String type, String instance) { + super(type,instance,null,null); + } - public void setAction(String s) { - action = s; - } - - /** - * This function understands that AAF Keys are hierarchical, :A:B:C, - * Cassandra follows a similar method, so we'll short circuit and do it more efficiently when there isn't a first hit - * @return - */ - } + public void setAction(String s) { + action = s; + } + + /** + * This function understands that AAF Keys are hierarchical, :A:B:C, + * Cassandra follows a similar method, so we'll short circuit and do it more efficiently when there isn't a first hit + * @return + */ + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java index ef73adaa..83204d1b 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java @@ -86,1016 +86,1016 @@ import locate.v1_1.Configuration; import locate.v1_1.Configuration.Props; public class Agent { - private static final String HASHES = "################################################################"; - private static final String PRINT = "print"; - private static final String FILE = "file"; - public static final String PKCS12 = "pkcs12"; - public static final String JKS = "jks"; - private static final String SCRIPT="script"; - - private static final String CM_VER = "1.0"; - public static final int PASS_SIZE = 24; - private static int TIMEOUT; - - private static RosettaDF reqDF; - private static RosettaDF certDF; - private static RosettaDF artifactsDF; - private static RosettaDF configDF; - private static RosettaDF permDF; - private static ErrMessage errMsg; - private static Map placeArtifact; - private static RosettaEnv env; - - private static boolean doExit; - private static AAFCon aafcon; + private static final String HASHES = "################################################################"; + private static final String PRINT = "print"; + private static final String FILE = "file"; + public static final String PKCS12 = "pkcs12"; + public static final String JKS = "jks"; + private static final String SCRIPT="script"; + + private static final String CM_VER = "1.0"; + public static final int PASS_SIZE = 24; + private static int TIMEOUT; + + private static RosettaDF reqDF; + private static RosettaDF certDF; + private static RosettaDF artifactsDF; + private static RosettaDF configDF; + private static RosettaDF permDF; + private static ErrMessage errMsg; + private static Map placeArtifact; + private static RosettaEnv env; + + private static boolean doExit; + private static AAFCon aafcon; - public static void main(String[] args) { - int exitCode = 0; - doExit = true; - if(args.length>0 && "cadi".equals(args[0])) { - String[] newArgs = new String[args.length-1]; - System.arraycopy(args, 1, newArgs, 0, newArgs.length); - if(newArgs.length==0) { - System.out.println(HASHES); - System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t" - + "Agent, always preface with \"cadi\",\n\tex: cadi keygen []"); - System.out.println(HASHES); - } - CmdLine.main(newArgs); - } else { - try { - AAFSSO aafsso=null; - PropAccess access; - - if(args.length>1 && args[0].equals("validate") ) { - int idx = args[1].indexOf('='); - aafsso = null; - access = new PropAccess( - (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+ - '='+ - (idx<0?args[1]:args[1].substring(idx+1))); - } else { - aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() { - @Override - public Properties process(String[] args, Properties props) { - if(args.length>1) { - if (!args[0].equals("keypairgen")) { - props.put("aaf_id", args[1]); - } - } - return props; - } - }); - access = aafsso.access(); - } - - if(aafsso!=null && aafsso.loginOnly()) { - aafsso.setLogDefault(); - aafsso.writeFiles(); - System.out.println("AAF SSO information created in ~/.aaf"); - } else { - env = new RosettaEnv(access.getProperties()); - Deque cmds = new ArrayDeque(); - for(String p : args) { - if("-noexit".equalsIgnoreCase(p)) { - doExit = false; - } else if(p.indexOf('=') < 0) { - cmds.add(p); - } - } - - if(cmds.size()==0) { - if(aafsso!=null) { - aafsso.setLogDefault(); - } - // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not - System.out.println("Usage: java -jar cmd []*"); - System.out.println(" create []"); - System.out.println(" read []"); - System.out.println(" update []"); - System.out.println(" delete []"); - System.out.println(" copy [,]*"); - System.out.println(" place []"); - System.out.println(" showpass []"); - System.out.println(" check []"); - System.out.println(" keypairgen "); - System.out.println(" config "); - System.out.println(" validate .props>"); - System.out.println(" --- Additional Tool Access ---"); - System.out.println(" ** Type with no params for Tool Help"); - System.out.println(" ** If using with Agent, preface with \"cadi\""); - System.out.println(" cadi "); - - if (doExit) { - System.exit(1); - } - } - - TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000")); - - reqDF = env.newDataFactory(CertificateRequest.class); - artifactsDF = env.newDataFactory(Artifacts.class); - certDF = env.newDataFactory(CertInfo.class); - configDF = env.newDataFactory(Configuration.class); - permDF = env.newDataFactory(Perms.class); - errMsg = new ErrMessage(env); - - placeArtifact = new HashMap<>(); - placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS)); - placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12)); - placeArtifact.put(FILE, new PlaceArtifactInFiles()); - placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out)); - placeArtifact.put(SCRIPT, new PlaceArtifactScripts()); - - Trans trans = env.newTrans(); - String token; - if((token=access.getProperty("oauth_token"))!=null) { - trans.setProperty("oauth_token", token); - } - try { - if(aafsso!=null) { - // show Std out again - aafsso.setLogDefault(); - aafsso.setStdErrDefault(); - - // if CM_URL can be obtained, add to sso.props, if written - String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": "); - if(cm_url!=null) { - aafsso.addProp(Config.CM_URL, cm_url); - } - aafsso.writeFiles(); - } - - - - String cmd = cmds.removeFirst(); - switch(cmd) { - case "place": - placeCerts(trans,aafcon(access),cmds); - break; - case "create": - createArtifact(trans, aafcon(access),cmds); - break; - case "read": - readArtifact(trans, aafcon(access), cmds); - break; - case "copy": - copyArtifact(trans, aafcon(access), cmds); - break; - case "update": - updateArtifact(trans, aafcon(access), cmds); - break; - case "delete": - deleteArtifact(trans, aafcon(access), cmds); - break; - case "showpass": - showPass(trans, aafcon(access), cmds); - break; - case "keypairgen": - keypairGen(trans, access, cmds); - break; - case "config": - if(access.getProperty(Config.CADI_PROP_FILES)!=null) { - // Get Properties from initialization Prop Files - config(trans,access,null,cmds); - } else { - // Get Properties from existing AAF Instance - config(trans,access,aafcon(access),cmds); - } - break; - case "validate": - validate(access); - break; - case "check": - try { - exitCode = check(trans,aafcon(access),cmds); - } catch (Exception e) { - exitCode = 1; - throw e; - } - break; - default: - AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd); - } - } finally { - StringBuilder sb = new StringBuilder(); - trans.auditTrail(4, sb, Trans.REMOTE); - if(sb.length()>0) { - trans.info().log("Trans Info\n",sb); - } - } - if(aafsso!=null) { - aafsso.close(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - if(exitCode != 0 && doExit) { - System.exit(exitCode); - } - } + public static void main(String[] args) { + int exitCode = 0; + doExit = true; + if(args.length>0 && "cadi".equals(args[0])) { + String[] newArgs = new String[args.length-1]; + System.arraycopy(args, 1, newArgs, 0, newArgs.length); + if(newArgs.length==0) { + System.out.println(HASHES); + System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t" + + "Agent, always preface with \"cadi\",\n\tex: cadi keygen []"); + System.out.println(HASHES); + } + CmdLine.main(newArgs); + } else { + try { + AAFSSO aafsso=null; + PropAccess access; + + if(args.length>1 && args[0].equals("validate") ) { + int idx = args[1].indexOf('='); + aafsso = null; + access = new PropAccess( + (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+ + '='+ + (idx<0?args[1]:args[1].substring(idx+1))); + } else { + aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() { + @Override + public Properties process(String[] args, Properties props) { + if(args.length>1) { + if (!args[0].equals("keypairgen")) { + props.put("aaf_id", args[1]); + } + } + return props; + } + }); + access = aafsso.access(); + } + + if(aafsso!=null && aafsso.loginOnly()) { + aafsso.setLogDefault(); + aafsso.writeFiles(); + System.out.println("AAF SSO information created in ~/.aaf"); + } else { + env = new RosettaEnv(access.getProperties()); + Deque cmds = new ArrayDeque(); + for(String p : args) { + if("-noexit".equalsIgnoreCase(p)) { + doExit = false; + } else if(p.indexOf('=') < 0) { + cmds.add(p); + } + } + + if(cmds.size()==0) { + if(aafsso!=null) { + aafsso.setLogDefault(); + } + // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not + System.out.println("Usage: java -jar cmd []*"); + System.out.println(" create []"); + System.out.println(" read []"); + System.out.println(" update []"); + System.out.println(" delete []"); + System.out.println(" copy [,]*"); + System.out.println(" place []"); + System.out.println(" showpass []"); + System.out.println(" check []"); + System.out.println(" keypairgen "); + System.out.println(" config "); + System.out.println(" validate .props>"); + System.out.println(" --- Additional Tool Access ---"); + System.out.println(" ** Type with no params for Tool Help"); + System.out.println(" ** If using with Agent, preface with \"cadi\""); + System.out.println(" cadi "); + + if (doExit) { + System.exit(1); + } + } + + TIMEOUT = Integer.parseInt(env.getProperty(Config.AAF_CONN_TIMEOUT, "5000")); + + reqDF = env.newDataFactory(CertificateRequest.class); + artifactsDF = env.newDataFactory(Artifacts.class); + certDF = env.newDataFactory(CertInfo.class); + configDF = env.newDataFactory(Configuration.class); + permDF = env.newDataFactory(Perms.class); + errMsg = new ErrMessage(env); + + placeArtifact = new HashMap<>(); + placeArtifact.put(JKS, new PlaceArtifactInKeystore(JKS)); + placeArtifact.put(PKCS12, new PlaceArtifactInKeystore(PKCS12)); + placeArtifact.put(FILE, new PlaceArtifactInFiles()); + placeArtifact.put(PRINT, new PlaceArtifactOnStream(System.out)); + placeArtifact.put(SCRIPT, new PlaceArtifactScripts()); + + Trans trans = env.newTrans(); + String token; + if((token=access.getProperty("oauth_token"))!=null) { + trans.setProperty("oauth_token", token); + } + try { + if(aafsso!=null) { + // show Std out again + aafsso.setLogDefault(); + aafsso.setStdErrDefault(); + + // if CM_URL can be obtained, add to sso.props, if written + String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": "); + if(cm_url!=null) { + aafsso.addProp(Config.CM_URL, cm_url); + } + aafsso.writeFiles(); + } + + + + String cmd = cmds.removeFirst(); + switch(cmd) { + case "place": + placeCerts(trans,aafcon(access),cmds); + break; + case "create": + createArtifact(trans, aafcon(access),cmds); + break; + case "read": + readArtifact(trans, aafcon(access), cmds); + break; + case "copy": + copyArtifact(trans, aafcon(access), cmds); + break; + case "update": + updateArtifact(trans, aafcon(access), cmds); + break; + case "delete": + deleteArtifact(trans, aafcon(access), cmds); + break; + case "showpass": + showPass(trans, aafcon(access), cmds); + break; + case "keypairgen": + keypairGen(trans, access, cmds); + break; + case "config": + if(access.getProperty(Config.CADI_PROP_FILES)!=null) { + // Get Properties from initialization Prop Files + config(trans,access,null,cmds); + } else { + // Get Properties from existing AAF Instance + config(trans,access,aafcon(access),cmds); + } + break; + case "validate": + validate(access); + break; + case "check": + try { + exitCode = check(trans,aafcon(access),cmds); + } catch (Exception e) { + exitCode = 1; + throw e; + } + break; + default: + AAFSSO.cons.printf("Unknown command \"%s\"\n", cmd); + } + } finally { + StringBuilder sb = new StringBuilder(); + trans.auditTrail(4, sb, Trans.REMOTE); + if(sb.length()>0) { + trans.info().log("Trans Info\n",sb); + } + } + if(aafsso!=null) { + aafsso.close(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + if(exitCode != 0 && doExit) { + System.exit(exitCode); + } + } - private static synchronized AAFCon aafcon(PropAccess access) throws APIException, CadiException, LocatorException { - if(aafcon==null) { - aafcon = new AAFConHttp(access,Config.CM_URL); - } - return aafcon; - } + private static synchronized AAFCon aafcon(PropAccess access) throws APIException, CadiException, LocatorException { + if(aafcon==null) { + aafcon = new AAFConHttp(access,Config.CM_URL); + } + return aafcon; + } - private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) { - String value; - if((value=pa.getProperty(tag))==null) { - if(secure) { - value = new String(AAFSSO.cons.readPassword(prompt, def)); - } else { - value = AAFSSO.cons.readLine(prompt,def).trim(); - } - if(value!=null) { - if(value.length()>0) { - pa.setProperty(tag,value); - env.setProperty(tag,value); - } else if(def.length==1) { - value=def[0].toString(); - pa.setProperty(tag,value); - env.setProperty(tag,value); - } - } - } - return value; - } + private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) { + String value; + if((value=pa.getProperty(tag))==null) { + if(secure) { + value = new String(AAFSSO.cons.readPassword(prompt, def)); + } else { + value = AAFSSO.cons.readLine(prompt,def).trim(); + } + if(value!=null) { + if(value.length()>0) { + pa.setProperty(tag,value); + env.setProperty(tag,value); + } else if(def.length==1) { + value=def[0].toString(); + pa.setProperty(tag,value); + env.setProperty(tag,value); + } + } + } + return value; + } - private static String fqi(Deque cmds) { - if(cmds.size()<1) { - String alias = env.getProperty(Config.CADI_ALIAS); - return alias!=null?alias:AAFSSO.cons.readLine("AppID: "); - } - return cmds.removeFirst(); - } + private static String fqi(Deque cmds) { + if(cmds.size()<1) { + String alias = env.getProperty(Config.CADI_ALIAS); + return alias!=null?alias:AAFSSO.cons.readLine("AppID: "); + } + return cmds.removeFirst(); + } - private static String machine(Deque cmds) throws UnknownHostException { - if(cmds.size()>0) { - return cmds.removeFirst(); - } else { - String mach = env.getProperty(Config.HOSTNAME); - return mach!=null?mach:InetAddress.getLocalHost().getHostName(); - } - } + private static String machine(Deque cmds) throws UnknownHostException { + if(cmds.size()>0) { + return cmds.removeFirst(); + } else { + String mach = env.getProperty(Config.HOSTNAME); + return mach!=null?mach:InetAddress.getLocalHost().getHostName(); + } + } - private static String[] machines(Deque cmds) { - String machines; - if(cmds.size()>0) { - machines = cmds.removeFirst(); - } else { - machines = AAFSSO.cons.readLine("Machines (sep by ','): "); - } - return Split.split(',', machines); - } + private static String[] machines(Deque cmds) { + String machines; + if(cmds.size()>0) { + machines = cmds.removeFirst(); + } else { + machines = AAFSSO.cons.readLine("Machines (sep by ','): "); + } + return Split.split(',', machines); + } - private static void createArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - final String mechID = fqi(cmds); - final String machine = machine(cmds); + private static void createArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + final String mechID = fqi(cmds); + final String machine = machine(cmds); - Artifacts artifacts = new Artifacts(); - Artifact arti = new Artifact(); - artifacts.getArtifact().add(arti); - arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: ")); - arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName())); - arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf")); - - String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12); - for(String s : Split.splitTrim(',', resp)) { - arti.getType().add(s); - } - // Always do Script - if(!resp.contains(SCRIPT)) { - arti.getType().add(SCRIPT); - } + Artifacts artifacts = new Artifacts(); + Artifact arti = new Artifact(); + artifacts.getArtifact().add(arti); + arti.setMechid(mechID!=null?mechID:AAFSSO.cons.readLine("AppID: ")); + arti.setMachine(machine!=null?machine:AAFSSO.cons.readLine("Machine (%s): ",InetAddress.getLocalHost().getHostName())); + arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf")); + + String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12); + for(String s : Split.splitTrim(',', resp)) { + arti.getType().add(s); + } + // Always do Script + if(!resp.contains(SCRIPT)) { + arti.getType().add(SCRIPT); + } - // Note: Sponsor is set on Creation by CM - String configRootName = FQI.reverseDomain(arti.getMechid()); - arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName)); - arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir"))); - arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name"))); - arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30"))); - arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", ""))); - - TimeTaken tt = trans.start("Create Artifact", Env.REMOTE); - try { - Future future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts); - if(future.get(TIMEOUT)) { - trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine()); - } else { - trans.error().printf("Call to AAF Certman failed, %s", - errMsg.toMsg(future)); - } - } finally { - tt.done(); - } - } + // Note: Sponsor is set on Creation by CM + String configRootName = FQI.reverseDomain(arti.getMechid()); + arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",configRootName)); + arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", System.getProperty("user.dir"))); + arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", System.getProperty("user.name"))); + arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renewal Days (%s):", "30"))); + arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (mailto owner):", ""))); + + TimeTaken tt = trans.start("Create Artifact", Env.REMOTE); + try { + Future future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts); + if(future.get(TIMEOUT)) { + trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine()); + } else { + trans.error().printf("Call to AAF Certman failed, %s", + errMsg.toMsg(future)); + } + } finally { + tt.done(); + } + } - private static String toNotification(String notification) { - if(notification==null) { - notification=""; - } else if(notification.length()>0) { - if(notification.indexOf(':')<0) { - notification = "mailto:" + notification; - } - } - return notification; - } - + private static String toNotification(String notification) { + if(notification==null) { + notification=""; + } else if(notification.length()>0) { + if(notification.indexOf(':')<0) { + notification = "mailto:" + notification; + } + } + return notification; + } + - private static void readArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - String mechID = fqi(cmds); - String machine = machine(cmds); + private static void readArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + String mechID = fqi(cmds); + String machine = machine(cmds); - TimeTaken tt = trans.start("Read Artifact", Env.SUB); - try { - Future future = aafcon.client(CM_VER) - .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token")); - - if(future.get(TIMEOUT)) { - boolean printed = false; - for(Artifact a : future.value.getArtifact()) { - AAFSSO.cons.printf("AppID: %s\n",a.getMechid()); - AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor()); - AAFSSO.cons.printf("Machine: %s\n",a.getMachine()); - AAFSSO.cons.printf("CA: %s\n",a.getCa()); - StringBuilder sb = new StringBuilder(); - boolean first = true; - for(String t : a.getType()) { - if(first) {first=false;} - else{sb.append(',');} - sb.append(t); - } - AAFSSO.cons.printf("Types: %s\n",sb); - AAFSSO.cons.printf("Namespace: %s\n",a.getNs()); - AAFSSO.cons.printf("Directory: %s\n",a.getDir()); - AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser()); - AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays()); - AAFSSO.cons.printf("Notification %s\n",a.getNotification()); - printed = true; - } - if(!printed) { - AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine); - } - } else { - trans.error().log(errMsg.toMsg(future)); - } - } finally { - tt.done(); - } - } - - private static void copyArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - String mechID = fqi(cmds); - String machine = machine(cmds); - String[] newmachs = machines(cmds); - if(machine==null || newmachs == null) { - trans.error().log("No machines listed to copy to"); - } else { - TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE); - try { - Future future = aafcon.client(CM_VER) - .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - - if(future.get(TIMEOUT)) { - boolean printed = false; - for(Artifact a : future.value.getArtifact()) { - for(String m : newmachs) { - a.setMachine(m); - Future fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value); - if(fup.get(TIMEOUT)) { - trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m); - } else { - trans.error().printf("Call to AAF Certman failed, %s", - errMsg.toMsg(fup)); - } - - printed = true; - } - } - if(!printed) { - AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine); - } - } else { - trans.error().log(errMsg.toMsg(future)); - } - } finally { - tt.done(); - } - } - } + TimeTaken tt = trans.start("Read Artifact", Env.SUB); + try { + Future future = aafcon.client(CM_VER) + .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token")); + + if(future.get(TIMEOUT)) { + boolean printed = false; + for(Artifact a : future.value.getArtifact()) { + AAFSSO.cons.printf("AppID: %s\n",a.getMechid()); + AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor()); + AAFSSO.cons.printf("Machine: %s\n",a.getMachine()); + AAFSSO.cons.printf("CA: %s\n",a.getCa()); + StringBuilder sb = new StringBuilder(); + boolean first = true; + for(String t : a.getType()) { + if(first) {first=false;} + else{sb.append(',');} + sb.append(t); + } + AAFSSO.cons.printf("Types: %s\n",sb); + AAFSSO.cons.printf("Namespace: %s\n",a.getNs()); + AAFSSO.cons.printf("Directory: %s\n",a.getDir()); + AAFSSO.cons.printf("O/S User: %s\n",a.getOsUser()); + AAFSSO.cons.printf("Renew Days: %d\n",a.getRenewDays()); + AAFSSO.cons.printf("Notification %s\n",a.getNotification()); + printed = true; + } + if(!printed) { + AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine); + } + } else { + trans.error().log(errMsg.toMsg(future)); + } + } finally { + tt.done(); + } + } + + private static void copyArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + String mechID = fqi(cmds); + String machine = machine(cmds); + String[] newmachs = machines(cmds); + if(machine==null || newmachs == null) { + trans.error().log("No machines listed to copy to"); + } else { + TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE); + try { + Future future = aafcon.client(CM_VER) + .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); + + if(future.get(TIMEOUT)) { + boolean printed = false; + for(Artifact a : future.value.getArtifact()) { + for(String m : newmachs) { + a.setMachine(m); + Future fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value); + if(fup.get(TIMEOUT)) { + trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m); + } else { + trans.error().printf("Call to AAF Certman failed, %s", + errMsg.toMsg(fup)); + } + + printed = true; + } + } + if(!printed) { + AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine); + } + } else { + trans.error().log(errMsg.toMsg(future)); + } + } finally { + tt.done(); + } + } + } - private static void updateArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - String mechID = fqi(cmds); - String machine = machine(cmds); + private static void updateArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + String mechID = fqi(cmds); + String machine = machine(cmds); - TimeTaken tt = trans.start("Update Artifact", Env.REMOTE); - try { - Future fread = aafcon.client(CM_VER) - .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - - if(fread.get(TIMEOUT)) { - Artifacts artifacts = new Artifacts(); - for(Artifact a : fread.value.getArtifact()) { - Artifact arti = new Artifact(); - artifacts.getArtifact().add(arti); - - AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine()); - arti.setMechid(a.getMechid()); - arti.setMachine(a.getMachine()); - arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa())); - StringBuilder sb = new StringBuilder(); - boolean first = true; - for(String t : a.getType()) { - if(first) {first=false;} - else{sb.append(',');} - sb.append(t); - } - - String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb); - for(String s : Split.splitTrim(',', resp)) { - arti.getType().add(s); - } - // Always do Script - if(!resp.contains(SCRIPT)) { - arti.getType().add(SCRIPT); - } + TimeTaken tt = trans.start("Update Artifact", Env.REMOTE); + try { + Future fread = aafcon.client(CM_VER) + .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); + + if(fread.get(TIMEOUT)) { + Artifacts artifacts = new Artifacts(); + for(Artifact a : fread.value.getArtifact()) { + Artifact arti = new Artifact(); + artifacts.getArtifact().add(arti); + + AAFSSO.cons.printf("For %s on %s\n", a.getMechid(),a.getMachine()); + arti.setMechid(a.getMechid()); + arti.setMachine(a.getMachine()); + arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa())); + StringBuilder sb = new StringBuilder(); + boolean first = true; + for(String t : a.getType()) { + if(first) {first=false;} + else{sb.append(',');} + sb.append(t); + } + + String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb); + for(String s : Split.splitTrim(',', resp)) { + arti.getType().add(s); + } + // Always do Script + if(!resp.contains(SCRIPT)) { + arti.getType().add(SCRIPT); + } - // Note: Sponsor is set on Creation by CM - arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs())); - arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir())); - arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser())); - arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays()))); - arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification()))); - - } - if(artifacts.getArtifact().size()==0) { - AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine); - } else { - Future fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts); - if(fup.get(TIMEOUT)) { - trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine); - } else { - trans.error().printf("Call to AAF Certman failed, %s", - errMsg.toMsg(fup)); - } - } - } else { - trans.error().printf("Call to AAF Certman failed, %s %s, %s", - errMsg.toMsg(fread),mechID,machine); - } - } finally { - tt.done(); - } - } - - private static void deleteArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - String mechid = fqi(cmds); - String machine = machine(cmds); - - TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE); - try { - Future future = aafcon.client(CM_VER) - .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" ); - - if(future.get(TIMEOUT)) { - trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine); - } else { - trans.error().printf("Call to AAF Certman failed, %s %s, %s", - errMsg.toMsg(future),mechid,machine); - } - } finally { - tt.done(); - } - } + // Note: Sponsor is set on Creation by CM + arti.setNs(AAFSSO.cons.readLine("Namespace (%s): ",a.getNs())); + arti.setDir(AAFSSO.cons.readLine("Directory (%s): ", a.getDir())); + arti.setOsUser(AAFSSO.cons.readLine("OS User (%s): ", a.getOsUser())); + arti.setRenewDays(Integer.parseInt(AAFSSO.cons.readLine("Renew Days (%s):", a.getRenewDays()))); + arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification()))); + + } + if(artifacts.getArtifact().size()==0) { + AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine); + } else { + Future fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts); + if(fup.get(TIMEOUT)) { + trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine); + } else { + trans.error().printf("Call to AAF Certman failed, %s", + errMsg.toMsg(fup)); + } + } + } else { + trans.error().printf("Call to AAF Certman failed, %s %s, %s", + errMsg.toMsg(fread),mechID,machine); + } + } finally { + tt.done(); + } + } + + private static void deleteArtifact(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + String mechid = fqi(cmds); + String machine = machine(cmds); + + TimeTaken tt = trans.start("Delete Artifact", Env.REMOTE); + try { + Future future = aafcon.client(CM_VER) + .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" ); + + if(future.get(TIMEOUT)) { + trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine); + } else { + trans.error().printf("Call to AAF Certman failed, %s %s, %s", + errMsg.toMsg(future),mechid,machine); + } + } finally { + tt.done(); + } + } - + - private static boolean placeCerts(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - boolean rv = false; - String mechID = fqi(cmds); - String machine = machine(cmds); - String[] fqdns = Split.split(':', machine); - String key; - if(fqdns.length>1) { - key = fqdns[0]; - machine = fqdns[1]; - } else { - key = machine; - } - - TimeTaken tt = trans.start("Place Artifact", Env.REMOTE); - try { - Future acf = aafcon.client(CM_VER) - .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF); - if(acf.get(TIMEOUT)) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { - AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key); - } else { - for(Artifact a : acf.value.getArtifact()) { - String osID = System.getProperty("user.name"); - if(a.getOsUser().equals(osID)) { - CertificateRequest cr = new CertificateRequest(); - cr.setMechid(a.getMechid()); - cr.setSponsor(a.getSponsor()); - for(int i=0;i f = aafcon.client(CM_VER) - .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr); - if(f.get(TIMEOUT)) { - CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject(); - for(String type : a.getType()) { - PlaceArtifact pa = placeArtifact.get(type); - if(pa!=null) { - if(rv = pa.place(trans, capi, a,machine)) { - notifyPlaced(a,rv); - } - } - } - // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact - } else { - trans.error().log(errMsg.toMsg(f)); - } - } else { - trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box"); - } - } - } - } else { - trans.error().log(errMsg.toMsg(acf)); - } - } finally { - tt.done(); - } - return rv; - } - - private static void notifyPlaced(Artifact a, boolean rv) { - } + private static boolean placeCerts(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + boolean rv = false; + String mechID = fqi(cmds); + String machine = machine(cmds); + String[] fqdns = Split.split(':', machine); + String key; + if(fqdns.length>1) { + key = fqdns[0]; + machine = fqdns[1]; + } else { + key = machine; + } + + TimeTaken tt = trans.start("Place Artifact", Env.REMOTE); + try { + Future acf = aafcon.client(CM_VER) + .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF); + if(acf.get(TIMEOUT)) { + if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key); + } else { + for(Artifact a : acf.value.getArtifact()) { + String osID = System.getProperty("user.name"); + if(a.getOsUser().equals(osID)) { + CertificateRequest cr = new CertificateRequest(); + cr.setMechid(a.getMechid()); + cr.setSponsor(a.getSponsor()); + for(int i=0;i f = aafcon.client(CM_VER) + .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr); + if(f.get(TIMEOUT)) { + CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject(); + for(String type : a.getType()) { + PlaceArtifact pa = placeArtifact.get(type); + if(pa!=null) { + if(rv = pa.place(trans, capi, a,machine)) { + notifyPlaced(a,rv); + } + } + } + // Cover for the above multiple pass possibilities with some static Data, then clear per Artifact + } else { + trans.error().log(errMsg.toMsg(f)); + } + } else { + trans.error().log("You must be OS User \"" + a.getOsUser() +"\" to place Certificates on this box"); + } + } + } + } else { + trans.error().log(errMsg.toMsg(acf)); + } + } finally { + tt.done(); + } + return rv; + } + + private static void notifyPlaced(Artifact a, boolean rv) { + } - private static void showPass(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - String mechID = fqi(cmds); - String machine = machine(cmds); + private static void showPass(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + String mechID = fqi(cmds); + String machine = machine(cmds); - TimeTaken tt = trans.start("Show Password", Env.REMOTE); - try { - Future acf = aafcon.client(CM_VER) - .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(acf.get(TIMEOUT)) { - // Have to wait for JDK 1.7 source... - //switch(artifact.getType()) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { - AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine); - } else { - String id = aafcon.defID(); - boolean allowed; - for(Artifact a : acf.value.getArtifact()) { - allowed = id!=null && (id.equals(a.getSponsor()) || - (id.equals(a.getMechid()) - && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class))); - if(!allowed) { - Future pf = aafcon.client(CM_VER).read("/cert/may/" + - a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*"); - if(pf.get(TIMEOUT)) { - allowed = true; - } else { - trans.error().log(errMsg.toMsg(pf)); - } - } - if(allowed) { - File dir = new File(a.getDir()); - Properties props = new Properties(); - FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props")); - try { - props.load(fis); - fis.close(); - fis = new FileInputStream(new File(dir,a.getNs()+".chal")); - props.load(fis); - } finally { - fis.close(); - } - - File f = new File(dir,a.getNs()+".keyfile"); - if(f.exists()) { - Symm symm = Symm.obtain(f); - - for(Iterator> iter = props.entrySet().iterator(); iter.hasNext();) { - Entry en = iter.next(); - if(en.getValue().toString().startsWith("enc:")) { - System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString())); - } - } - } else { - trans.error().printf("%s.keyfile must exist to read passwords for %s on %s", - f.getAbsolutePath(),a.getMechid(), a.getMachine()); - } - } - } - } - } else { - trans.error().log(errMsg.toMsg(acf)); - } - } finally { - tt.done(); - } + TimeTaken tt = trans.start("Show Password", Env.REMOTE); + try { + Future acf = aafcon.client(CM_VER) + .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); + if(acf.get(TIMEOUT)) { + // Have to wait for JDK 1.7 source... + //switch(artifact.getType()) { + if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine); + } else { + String id = aafcon.defID(); + boolean allowed; + for(Artifact a : acf.value.getArtifact()) { + allowed = id!=null && (id.equals(a.getSponsor()) || + (id.equals(a.getMechid()) + && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class))); + if(!allowed) { + Future pf = aafcon.client(CM_VER).read("/cert/may/" + + a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*"); + if(pf.get(TIMEOUT)) { + allowed = true; + } else { + trans.error().log(errMsg.toMsg(pf)); + } + } + if(allowed) { + File dir = new File(a.getDir()); + Properties props = new Properties(); + FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props")); + try { + props.load(fis); + fis.close(); + fis = new FileInputStream(new File(dir,a.getNs()+".chal")); + props.load(fis); + } finally { + fis.close(); + } + + File f = new File(dir,a.getNs()+".keyfile"); + if(f.exists()) { + Symm symm = Symm.obtain(f); + + for(Iterator> iter = props.entrySet().iterator(); iter.hasNext();) { + Entry en = iter.next(); + if(en.getValue().toString().startsWith("enc:")) { + System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString())); + } + } + } else { + trans.error().printf("%s.keyfile must exist to read passwords for %s on %s", + f.getAbsolutePath(),a.getMechid(), a.getMachine()); + } + } + } + } + } else { + trans.error().log(errMsg.toMsg(acf)); + } + } finally { + tt.done(); + } - } - - private static void keypairGen(final Trans trans, final PropAccess access, final Deque cmds) throws IOException { - final String fqi = fqi(cmds); - final String ns = FQI.reverseDomain(fqi); - File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory - File f = new File(dir,ns+".key"); - - if(f.exists()) { - String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath()); - if(!"Y".equalsIgnoreCase(line)) { - System.out.println("Canceling..."); - return; - } - } - - KeyPair kp = Factory.generateKeyPair(trans); - ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate())); - System.out.printf("Wrote %s\n", f.getCanonicalFile()); + } + + private static void keypairGen(final Trans trans, final PropAccess access, final Deque cmds) throws IOException { + final String fqi = fqi(cmds); + final String ns = FQI.reverseDomain(fqi); + File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory + File f = new File(dir,ns+".key"); + + if(f.exists()) { + String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath()); + if(!"Y".equalsIgnoreCase(line)) { + System.out.println("Canceling..."); + return; + } + } + + KeyPair kp = Factory.generateKeyPair(trans); + ArtifactDir.write(f, Chmod.to400, Factory.toString(trans, kp.getPrivate())); + System.out.printf("Wrote %s\n", f.getCanonicalFile()); - f=new File(dir,ns+".pubkey"); - ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic())); - System.out.printf("Wrote %s\n", f.getCanonicalFile()); - } - - private static void config(Trans trans, PropAccess pa, AAFCon aafcon, Deque cmds) throws Exception { - final String fqi = fqi(cmds); - final String rootFile = FQI.reverseDomain(fqi); - final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, ".")); - if(dir.exists()) { - System.out.println("Writing to " + dir.getCanonicalFile()); - } else if(dir.mkdirs()) { - System.out.println("Created directory " + dir.getCanonicalFile()); - } else { - System.err.println("Unable to create or write to " + dir.getCanonicalPath()); - return; - } - - TimeTaken tt = trans.start("Get Configuration", Env.REMOTE); - try { - boolean ok=false; - File fProps = File.createTempFile(rootFile, ".tmp",dir); - File fSecureTempProps = File.createTempFile(rootFile, ".cred.tmp",dir); - File fSecureProps = new File(dir,rootFile+".cred.props"); - PrintStream psProps; + f=new File(dir,ns+".pubkey"); + ArtifactDir.write(f, Chmod.to644, Factory.toString(trans, kp.getPublic())); + System.out.printf("Wrote %s\n", f.getCanonicalFile()); + } + + private static void config(Trans trans, PropAccess pa, AAFCon aafcon, Deque cmds) throws Exception { + final String fqi = fqi(cmds); + final String rootFile = FQI.reverseDomain(fqi); + final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, ".")); + if(dir.exists()) { + System.out.println("Writing to " + dir.getCanonicalFile()); + } else if(dir.mkdirs()) { + System.out.println("Created directory " + dir.getCanonicalFile()); + } else { + System.err.println("Unable to create or write to " + dir.getCanonicalPath()); + return; + } + + TimeTaken tt = trans.start("Get Configuration", Env.REMOTE); + try { + boolean ok=false; + File fProps = File.createTempFile(rootFile, ".tmp",dir); + File fSecureTempProps = File.createTempFile(rootFile, ".cred.tmp",dir); + File fSecureProps = new File(dir,rootFile+".cred.props"); + PrintStream psProps; - File fLocProps = new File(dir,rootFile + ".location.props"); - if(!fLocProps.exists()) { - psProps = new PrintStream(new FileOutputStream(fLocProps)); - try { - psProps.println(HASHES); - psProps.print("# Configuration File generated on "); - psProps.println(new Date().toString()); - psProps.println(HASHES); - for(String tag : LOC_TAGS) { - psProps.print(tag); - psProps.print('='); - psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag)); - } - } finally { - psProps.close(); - } - } + File fLocProps = new File(dir,rootFile + ".location.props"); + if(!fLocProps.exists()) { + psProps = new PrintStream(new FileOutputStream(fLocProps)); + try { + psProps.println(HASHES); + psProps.print("# Configuration File generated on "); + psProps.println(new Date().toString()); + psProps.println(HASHES); + for(String tag : LOC_TAGS) { + psProps.print(tag); + psProps.print('='); + psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag)); + } + } finally { + psProps.close(); + } + } - psProps = new PrintStream(new FileOutputStream(fProps)); - try { - PrintStream psCredProps = new PrintStream(new FileOutputStream(fSecureTempProps)); - try { - psCredProps.println(HASHES); - psCredProps.print("# Configuration File generated on "); - psCredProps.println(new Date().toString()); - psCredProps.println(HASHES); + psProps = new PrintStream(new FileOutputStream(fProps)); + try { + PrintStream psCredProps = new PrintStream(new FileOutputStream(fSecureTempProps)); + try { + psCredProps.println(HASHES); + psCredProps.print("# Configuration File generated on "); + psCredProps.println(new Date().toString()); + psCredProps.println(HASHES); - psProps.println(HASHES); - psProps.print("# Configuration File generated on "); - psProps.println(new Date().toString()); - psProps.println(HASHES); - - psProps.print(Config.CADI_PROP_FILES); - psProps.print('='); - psProps.print(fSecureProps.getCanonicalPath()); - psProps.print(File.pathSeparatorChar); - psProps.println(fLocProps.getCanonicalPath()); - - File fkf = new File(dir,rootFile+".keyfile"); - if(!fkf.exists()) { - CmdLine.main(new String[] {"keygen",fkf.toString()}); - } - Symm filesymm = Symm.obtain(fkf); - Map normal = new TreeMap<>(); - Map creds = new TreeMap<>(); + psProps.println(HASHES); + psProps.print("# Configuration File generated on "); + psProps.println(new Date().toString()); + psProps.println(HASHES); + + psProps.print(Config.CADI_PROP_FILES); + psProps.print('='); + psProps.print(fSecureProps.getCanonicalPath()); + psProps.print(File.pathSeparatorChar); + psProps.println(fLocProps.getCanonicalPath()); + + File fkf = new File(dir,rootFile+".keyfile"); + if(!fkf.exists()) { + CmdLine.main(new String[] {"keygen",fkf.toString()}); + } + Symm filesymm = Symm.obtain(fkf); + Map normal = new TreeMap<>(); + Map creds = new TreeMap<>(); - directedPut(pa, filesymm, normal,creds, Config.CADI_KEYFILE, fkf.getCanonicalPath()); - directedPut(pa, filesymm, normal,creds, Config.AAF_APPID,fqi); - directedPut(pa, filesymm, normal,creds, Config.AAF_APPPASS,null); - directedPut(pa, filesymm, normal,creds, Config.AAF_URL, Defaults.AAF_URL); - + directedPut(pa, filesymm, normal,creds, Config.CADI_KEYFILE, fkf.getCanonicalPath()); + directedPut(pa, filesymm, normal,creds, Config.AAF_APPID,fqi); + directedPut(pa, filesymm, normal,creds, Config.AAF_APPPASS,null); + directedPut(pa, filesymm, normal,creds, Config.AAF_URL, Defaults.AAF_URL); + - String cts = pa.getProperty(Config.CADI_TRUSTSTORE); - if(cts!=null) { - File origTruststore = new File(cts); - if(!origTruststore.exists()) { - // Try same directory as cadi_prop_files - String cpf = pa.getProperty(Config.CADI_PROP_FILES); - if(cpf!=null) { - for(String f : Split.split(File.pathSeparatorChar, cpf)) { - File fcpf = new File(f); - if(fcpf.exists()) { - int lastSep = cts.lastIndexOf(File.pathSeparator); - origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts); - if(origTruststore.exists()) { - break; - } - } - } - if(!origTruststore.exists()) { - throw new CadiException(cts + " does not exist"); - } - } - - } - File newTruststore = new File(dir,origTruststore.getName()); - if(!newTruststore.exists()) { - Files.copy(origTruststore.toPath(), newTruststore.toPath()); - } - - directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE,newTruststore.getCanonicalPath()); - directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE_PASSWORD,null); - } - - if(aafcon!=null) { // get Properties from Remote AAF - final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "); + String cts = pa.getProperty(Config.CADI_TRUSTSTORE); + if(cts!=null) { + File origTruststore = new File(cts); + if(!origTruststore.exists()) { + // Try same directory as cadi_prop_files + String cpf = pa.getProperty(Config.CADI_PROP_FILES); + if(cpf!=null) { + for(String f : Split.split(File.pathSeparatorChar, cpf)) { + File fcpf = new File(f); + if(fcpf.exists()) { + int lastSep = cts.lastIndexOf(File.pathSeparator); + origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts); + if(origTruststore.exists()) { + break; + } + } + } + if(!origTruststore.exists()) { + throw new CadiException(cts + " does not exist"); + } + } + + } + File newTruststore = new File(dir,origTruststore.getName()); + if(!newTruststore.exists()) { + Files.copy(origTruststore.toPath(), newTruststore.toPath()); + } + + directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE,newTruststore.getCanonicalPath()); + directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE_PASSWORD,null); + } + + if(aafcon!=null) { // get Properties from Remote AAF + final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "); - Future acf = aafcon.client(new SingleEndpointLocator(locator)) - .read("/configure/"+fqi+"/aaf", configDF); - if(acf.get(TIMEOUT)) { - for(Props props : acf.value.getProps()) { - directedPut(pa, filesymm, normal,creds, props.getTag(),props.getValue()); - } - ok = true; - } else if(acf.code()==401){ - trans.error().log("Bad Password sent to AAF"); - } else { - trans.error().log(errMsg.toMsg(acf)); - } - } else { - String cpf = pa.getProperty(Config.CADI_PROP_FILES); - if(cpf!=null){ - for(String f : Split.split(File.pathSeparatorChar, cpf)) { - System.out.format("Reading %s\n",f); - FileInputStream fis = new FileInputStream(f); - try { - Properties props = new Properties(); - props.load(fis); - for(Entry prop : props.entrySet()) { - directedPut(pa, filesymm, normal,creds, prop.getKey().toString(),prop.getValue().toString()); - } - } finally { - fis.close(); - } - } - } - ok = true; - } - if(ok) { - for(Entry es : normal.entrySet()) { - psProps.print(es.getKey()); - psProps.print('='); - psProps.println(es.getValue()); - } - - for(Entry es : creds.entrySet()) { - psCredProps.print(es.getKey()); - psCredProps.print('='); - psCredProps.println(es.getValue()); - } - - File newFile = new File(dir,rootFile+".props"); - if(newFile.exists()) { - File backup = new File(dir,rootFile+".props.backup"); - newFile.renameTo(backup); - System.out.println("Backed up to " + backup.getCanonicalPath()); - } - fProps.renameTo(newFile); - System.out.println("Created " + newFile.getCanonicalPath()); - fProps = newFile; - - if(fSecureProps.exists()) { - File backup = new File(dir,fSecureProps.getName()+".backup"); - fSecureProps.renameTo(backup); - System.out.println("Backed up to " + backup.getCanonicalPath()); - } - fSecureTempProps.renameTo(fSecureProps); - System.out.println("Created " + fSecureProps.getCanonicalPath()); - fProps = newFile; - } else { - fProps.delete(); - fSecureTempProps.delete(); - } - } finally { - psCredProps.close(); - } - } finally { - psProps.close(); - } - } finally { - tt.done(); - } - } + Future acf = aafcon.client(new SingleEndpointLocator(locator)) + .read("/configure/"+fqi+"/aaf", configDF); + if(acf.get(TIMEOUT)) { + for(Props props : acf.value.getProps()) { + directedPut(pa, filesymm, normal,creds, props.getTag(),props.getValue()); + } + ok = true; + } else if(acf.code()==401){ + trans.error().log("Bad Password sent to AAF"); + } else { + trans.error().log(errMsg.toMsg(acf)); + } + } else { + String cpf = pa.getProperty(Config.CADI_PROP_FILES); + if(cpf!=null){ + for(String f : Split.split(File.pathSeparatorChar, cpf)) { + System.out.format("Reading %s\n",f); + FileInputStream fis = new FileInputStream(f); + try { + Properties props = new Properties(); + props.load(fis); + for(Entry prop : props.entrySet()) { + directedPut(pa, filesymm, normal,creds, prop.getKey().toString(),prop.getValue().toString()); + } + } finally { + fis.close(); + } + } + } + ok = true; + } + if(ok) { + for(Entry es : normal.entrySet()) { + psProps.print(es.getKey()); + psProps.print('='); + psProps.println(es.getValue()); + } + + for(Entry es : creds.entrySet()) { + psCredProps.print(es.getKey()); + psCredProps.print('='); + psCredProps.println(es.getValue()); + } + + File newFile = new File(dir,rootFile+".props"); + if(newFile.exists()) { + File backup = new File(dir,rootFile+".props.backup"); + newFile.renameTo(backup); + System.out.println("Backed up to " + backup.getCanonicalPath()); + } + fProps.renameTo(newFile); + System.out.println("Created " + newFile.getCanonicalPath()); + fProps = newFile; + + if(fSecureProps.exists()) { + File backup = new File(dir,fSecureProps.getName()+".backup"); + fSecureProps.renameTo(backup); + System.out.println("Backed up to " + backup.getCanonicalPath()); + } + fSecureTempProps.renameTo(fSecureProps); + System.out.println("Created " + fSecureProps.getCanonicalPath()); + fProps = newFile; + } else { + fProps.delete(); + fSecureTempProps.delete(); + } + } finally { + psCredProps.close(); + } + } finally { + psProps.close(); + } + } finally { + tt.done(); + } + } - private static List CRED_TAGS = Arrays.asList(new String[] { - Config.CADI_KEYFILE, - Config.AAF_APPID, Config.AAF_APPPASS, - Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD, - Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD, - Config.CADI_ALIAS, Config.CADI_X509_ISSUERS - }); + private static List CRED_TAGS = Arrays.asList(new String[] { + Config.CADI_KEYFILE, + Config.AAF_APPID, Config.AAF_APPPASS, + Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD, Config.CADI_KEY_PASSWORD, + Config.CADI_TRUSTSTORE,Config.CADI_TRUSTSTORE_PASSWORD, + Config.CADI_ALIAS, Config.CADI_X509_ISSUERS + }); - private static List LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE}); - - private static void directedPut(final PropAccess orig, final Symm symm, final Map main, final Map secured, final String tag, final String value) throws IOException { - if(!LOC_TAGS.contains(tag)) { // Location already covered - String val = value==null?orig.getProperty(tag):value; - if(tag.endsWith("_password")) { - if(val.length()>4) { - if(val.startsWith("enc:")) { - val = orig.decrypt(val, true); - } - val = "enc:" + symm.enpass(val); - } - } - if(CRED_TAGS.contains(tag)) { - secured.put(tag, val); - } else { - main.put(tag, val); - } - } - } + private static List LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE}); + + private static void directedPut(final PropAccess orig, final Symm symm, final Map main, final Map secured, final String tag, final String value) throws IOException { + if(!LOC_TAGS.contains(tag)) { // Location already covered + String val = value==null?orig.getProperty(tag):value; + if(tag.endsWith("_password")) { + if(val.length()>4) { + if(val.startsWith("enc:")) { + val = orig.decrypt(val, true); + } + val = "enc:" + symm.enpass(val); + } + } + if(CRED_TAGS.contains(tag)) { + secured.put(tag, val); + } else { + main.put(tag, val); + } + } + } - private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException { - System.out.println("Validating Configuration..."); - final AAFCon aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC(pa)); - aafcon.best(new Retryable() { - @Override - public Void code(Rcli client) throws CadiException, ConnectException, APIException { - Future fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF); - if(fc.get(aafcon.timeout)) { - System.out.print("Success connecting to "); - System.out.println(client.getURI()); - System.out.print(" Permissions for "); - System.out.println(aafcon.defID()); - for(Perm p : fc.value.getPerm()) { - System.out.print('\t'); - System.out.print(p.getType()); - System.out.print('|'); - System.out.print(p.getInstance()); - System.out.print('|'); - System.out.println(p.getAction()); - } - } else { - System.err.println("Error: " + fc.code() + ' ' + fc.body()); - } - return null; - } - }); - } + private static void validate(final PropAccess pa) throws LocatorException, CadiException, APIException { + System.out.println("Validating Configuration..."); + final AAFCon aafcon = new AAFConHttp(pa,Config.AAF_URL,new SecurityInfoC(pa)); + aafcon.best(new Retryable() { + @Override + public Void code(Rcli client) throws CadiException, ConnectException, APIException { + Future fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF); + if(fc.get(aafcon.timeout)) { + System.out.print("Success connecting to "); + System.out.println(client.getURI()); + System.out.print(" Permissions for "); + System.out.println(aafcon.defID()); + for(Perm p : fc.value.getPerm()) { + System.out.print('\t'); + System.out.print(p.getType()); + System.out.print('|'); + System.out.print(p.getInstance()); + System.out.print('|'); + System.out.println(p.getAction()); + } + } else { + System.err.println("Error: " + fc.code() + ' ' + fc.body()); + } + return null; + } + }); + } - /** - * Check returns Error Codes, so that Scripts can know what to do - * - * 0 - Check Complete, nothing to do - * 1 - General Error - * 2 - Error for specific Artifact - read check.msg - * 10 - Certificate Updated - check.msg is email content - * - * @param trans - * @param aafcon - * @param cmds - * @return - * @throws Exception - */ - private static int check(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { - int exitCode=1; - String mechID = fqi(cmds); - String machine = machine(cmds); - - TimeTaken tt = trans.start("Check Certificate", Env.REMOTE); - try { - - Future acf = aafcon.client(CM_VER) - .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(acf.get(TIMEOUT)) { - // Have to wait for JDK 1.7 source... - //switch(artifact.getType()) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { - AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine); - } else { - String id = aafcon.defID(); - GregorianCalendar now = new GregorianCalendar(); - for(Artifact a : acf.value.getArtifact()) { - if(id.equals(a.getMechid())) { - File dir = new File(a.getDir()); - Properties props = new Properties(); - FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props")); - try { - props.load(fis); - } finally { - fis.close(); - } - - String prop; - File f; - - if((prop=trans.getProperty(Config.CADI_KEYFILE))==null || - !(f=new File(prop)).exists()) { - trans.error().printf("Keyfile must exist to check Certificates for %s on %s", - a.getMechid(), a.getMachine()); - } else { - String ksf = trans.getProperty(Config.CADI_KEYSTORE); - String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD); - if(ksf==null || ksps == null) { - trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s", - Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine()); - } else { - KeyStore ks = KeyStore.getInstance("JKS"); - Symm symm = Symm.obtain(f); - - fis = new FileInputStream(ksf); - try { - ks.load(fis,symm.depass(ksps).toCharArray()); - } finally { - fis.close(); - } - X509Certificate cert = (X509Certificate)ks.getCertificate(mechID); - String msg = null; + /** + * Check returns Error Codes, so that Scripts can know what to do + * + * 0 - Check Complete, nothing to do + * 1 - General Error + * 2 - Error for specific Artifact - read check.msg + * 10 - Certificate Updated - check.msg is email content + * + * @param trans + * @param aafcon + * @param cmds + * @return + * @throws Exception + */ + private static int check(Trans trans, AAFCon aafcon, Deque cmds) throws Exception { + int exitCode=1; + String mechID = fqi(cmds); + String machine = machine(cmds); + + TimeTaken tt = trans.start("Check Certificate", Env.REMOTE); + try { + + Future acf = aafcon.client(CM_VER) + .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); + if(acf.get(TIMEOUT)) { + // Have to wait for JDK 1.7 source... + //switch(artifact.getType()) { + if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine); + } else { + String id = aafcon.defID(); + GregorianCalendar now = new GregorianCalendar(); + for(Artifact a : acf.value.getArtifact()) { + if(id.equals(a.getMechid())) { + File dir = new File(a.getDir()); + Properties props = new Properties(); + FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props")); + try { + props.load(fis); + } finally { + fis.close(); + } + + String prop; + File f; + + if((prop=trans.getProperty(Config.CADI_KEYFILE))==null || + !(f=new File(prop)).exists()) { + trans.error().printf("Keyfile must exist to check Certificates for %s on %s", + a.getMechid(), a.getMachine()); + } else { + String ksf = trans.getProperty(Config.CADI_KEYSTORE); + String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD); + if(ksf==null || ksps == null) { + trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s", + Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine()); + } else { + KeyStore ks = KeyStore.getInstance("JKS"); + Symm symm = Symm.obtain(f); + + fis = new FileInputStream(ksf); + try { + ks.load(fis,symm.depass(ksps).toCharArray()); + } finally { + fis.close(); + } + X509Certificate cert = (X509Certificate)ks.getCertificate(mechID); + String msg = null; - if(cert==null) { - msg = String.format("X509Certificate does not exist for %s on %s in %s", - a.getMechid(), a.getMachine(), ksf); - trans.error().log(msg); - exitCode = 2; - } else { - GregorianCalendar renew = new GregorianCalendar(); - renew.setTime(cert.getNotAfter()); - renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays()); - if(renew.after(now)) { - msg = String.format("X509Certificate for %s on %s has been checked on %s. It expires on %s; it will not be renewed until %s.\n", - a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew)); - trans.info().log(msg); - exitCode = 0; // OK - } else { - trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n", - a.getMechid(), a.getMachine(),cert.getNotAfter()); - cmds.offerLast(mechID); - cmds.offerLast(machine); - if(placeCerts(trans,aafcon,cmds)) { - msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n", - a.getMechid(), a.getMachine()); - exitCode = 10; // Refreshed - } else { - msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n", - a.getMechid(), a.getMachine()); - exitCode = 1; // Error Renewing - } - } - } - if(msg!=null) { - FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg"); - try { - fos.write(msg.getBytes()); - } finally { - fos.close(); - } - } - } - - } - } - } - } - } else { - trans.error().log(errMsg.toMsg(acf)); - exitCode=1; - } - } finally { - tt.done(); - } - return exitCode; - } + if(cert==null) { + msg = String.format("X509Certificate does not exist for %s on %s in %s", + a.getMechid(), a.getMachine(), ksf); + trans.error().log(msg); + exitCode = 2; + } else { + GregorianCalendar renew = new GregorianCalendar(); + renew.setTime(cert.getNotAfter()); + renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays()); + if(renew.after(now)) { + msg = String.format("X509Certificate for %s on %s has been checked on %s. It expires on %s; it will not be renewed until %s.\n", + a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew)); + trans.info().log(msg); + exitCode = 0; // OK + } else { + trans.info().printf("X509Certificate for %s on %s expiration, %s, needs Renewal.\n", + a.getMechid(), a.getMachine(),cert.getNotAfter()); + cmds.offerLast(mechID); + cmds.offerLast(machine); + if(placeCerts(trans,aafcon,cmds)) { + msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n", + a.getMechid(), a.getMachine()); + exitCode = 10; // Refreshed + } else { + msg = String.format("X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n", + a.getMechid(), a.getMachine()); + exitCode = 1; // Error Renewing + } + } + } + if(msg!=null) { + FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg"); + try { + fos.write(msg.getBytes()); + } finally { + fos.close(); + } + } + } + + } + } + } + } + } else { + trans.error().log(errMsg.toMsg(acf)); + exitCode=1; + } + } finally { + tt.done(); + } + return exitCode; + } } - - + + diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java index d553ceb1..b5353828 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java @@ -45,243 +45,243 @@ import certman.v1_0.CertInfo; public abstract class ArtifactDir implements PlaceArtifact { - protected static final String C_R = "\n"; - protected File dir; - private List encodeds = new ArrayList<>(); - - private Symm symm; - // This checks for multiple passes of Dir on the same objects. Run clear after done. - protected static Map processed = new HashMap<>(); + protected static final String C_R = "\n"; + protected File dir; + private List encodeds = new ArrayList<>(); + + private Symm symm; + // This checks for multiple passes of Dir on the same objects. Run clear after done. + protected static Map processed = new HashMap<>(); - /** - * Note: Derived Classes should ALWAYS call "super.place(cert,arti)" first, and - * then "placeProperties(arti)" just after they implement - */ - @Override - public final boolean place(Trans trans, CertInfo certInfo, Artifact arti, String machine) throws CadiException { - validate(arti); - - try { - // Obtain/setup directory as required - dir = new File(arti.getDir()); - if(processed.get("dir")==null) { - if(!dir.exists()) { - Chmod.to755.chmod(dir); - if(!dir.mkdirs()) { - throw new CadiException("Could not create " + dir); - } - } - - // Also place cm_url and Host Name - addProperty(Config.CM_URL,trans.getProperty(Config.CM_URL)); -// addProperty(Config.HOSTNAME,machine); -// addProperty(Config.AAF_ENV,certInfo.getEnv()); - // Obtain Issuers - boolean first = true; - StringBuilder issuers = new StringBuilder(); - for(String dn : certInfo.getCaIssuerDNs()) { - if(first) { - first=false; - } else { - issuers.append(':'); - } - issuers.append(dn); - } - addProperty(Config.CADI_X509_ISSUERS,issuers.toString()); - } - symm = (Symm)processed.get("symm"); - if(symm==null) { - // CADI Key Gen - File f = new File(dir,arti.getNs() + ".keyfile"); - if(!f.exists()) { - write(f,Chmod.to400,Symm.keygen()); - } - symm = Symm.obtain(f); + /** + * Note: Derived Classes should ALWAYS call "super.place(cert,arti)" first, and + * then "placeProperties(arti)" just after they implement + */ + @Override + public final boolean place(Trans trans, CertInfo certInfo, Artifact arti, String machine) throws CadiException { + validate(arti); + + try { + // Obtain/setup directory as required + dir = new File(arti.getDir()); + if(processed.get("dir")==null) { + if(!dir.exists()) { + Chmod.to755.chmod(dir); + if(!dir.mkdirs()) { + throw new CadiException("Could not create " + dir); + } + } + + // Also place cm_url and Host Name + addProperty(Config.CM_URL,trans.getProperty(Config.CM_URL)); +// addProperty(Config.HOSTNAME,machine); +// addProperty(Config.AAF_ENV,certInfo.getEnv()); + // Obtain Issuers + boolean first = true; + StringBuilder issuers = new StringBuilder(); + for(String dn : certInfo.getCaIssuerDNs()) { + if(first) { + first=false; + } else { + issuers.append(':'); + } + issuers.append(dn); + } + addProperty(Config.CADI_X509_ISSUERS,issuers.toString()); + } + symm = (Symm)processed.get("symm"); + if(symm==null) { + // CADI Key Gen + File f = new File(dir,arti.getNs() + ".keyfile"); + if(!f.exists()) { + write(f,Chmod.to400,Symm.keygen()); + } + symm = Symm.obtain(f); - addEncProperty("ChallengePassword", certInfo.getChallenge()); - - processed.put("symm",symm); - } + addEncProperty("ChallengePassword", certInfo.getChallenge()); + + processed.put("symm",symm); + } - _place(trans, certInfo,arti); - - placeProperties(arti); - - processed.put("dir",dir); + _place(trans, certInfo,arti); + + placeProperties(arti); + + processed.put("dir",dir); - } catch (Exception e) { - throw new CadiException(e); - } - return true; - } + } catch (Exception e) { + throw new CadiException(e); + } + return true; + } - /** - * Derived Classes implement this instead, so Dir can process first, and write any Properties last - * @param cert - * @param arti - * @return - * @throws CadiException - */ - protected abstract boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException; + /** + * Derived Classes implement this instead, so Dir can process first, and write any Properties last + * @param cert + * @param arti + * @return + * @throws CadiException + */ + protected abstract boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException; - protected void addProperty(String tag, String value) throws IOException { - StringBuilder sb = new StringBuilder(); - sb.append(tag); - sb.append('='); - sb.append(value); - encodeds.add(sb.toString()); - } + protected void addProperty(String tag, String value) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append(tag); + sb.append('='); + sb.append(value); + encodeds.add(sb.toString()); + } - protected void addEncProperty(String tag, String value) throws IOException { - StringBuilder sb = new StringBuilder(); - sb.append(tag); - sb.append('='); - sb.append("enc:"); - sb.append(symm.enpass(value)); - encodeds.add(sb.toString()); - } + protected void addEncProperty(String tag, String value) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append(tag); + sb.append('='); + sb.append("enc:"); + sb.append(symm.enpass(value)); + encodeds.add(sb.toString()); + } - public static void write(File f, Chmod c, String ... data) throws IOException { - f.setWritable(true,true); - - FileOutputStream fos = new FileOutputStream(f); - PrintStream ps = new PrintStream(fos); - try { - for(String s : data) { - ps.print(s); - } - } finally { - ps.close(); - c.chmod(f); - } - } + public static void write(File f, Chmod c, String ... data) throws IOException { + f.setWritable(true,true); + + FileOutputStream fos = new FileOutputStream(f); + PrintStream ps = new PrintStream(fos); + try { + for(String s : data) { + ps.print(s); + } + } finally { + ps.close(); + c.chmod(f); + } + } - public static void write(File f, Chmod c, byte[] bytes) throws IOException { - f.setWritable(true,true); - - FileOutputStream fos = new FileOutputStream(f); - try { - fos.write(bytes); - } finally { - fos.close(); - c.chmod(f); - } - } - - public static void write(File f, Chmod c, KeyStore ks, char[] pass ) throws IOException, CadiException { - f.setWritable(true,true); - - FileOutputStream fos = new FileOutputStream(f); - try { - ks.store(fos, pass); - } catch (Exception e) { - throw new CadiException(e); - } finally { - fos.close(); - c.chmod(f); - } - } + public static void write(File f, Chmod c, byte[] bytes) throws IOException { + f.setWritable(true,true); + + FileOutputStream fos = new FileOutputStream(f); + try { + fos.write(bytes); + } finally { + fos.close(); + c.chmod(f); + } + } + + public static void write(File f, Chmod c, KeyStore ks, char[] pass ) throws IOException, CadiException { + f.setWritable(true,true); + + FileOutputStream fos = new FileOutputStream(f); + try { + ks.store(fos, pass); + } catch (Exception e) { + throw new CadiException(e); + } finally { + fos.close(); + c.chmod(f); + } + } - private void validate(Artifact a) throws CadiException { - StringBuilder sb = new StringBuilder(); - if(a.getDir()==null) { - sb.append("File Artifacts require a path"); - } + private void validate(Artifact a) throws CadiException { + StringBuilder sb = new StringBuilder(); + if(a.getDir()==null) { + sb.append("File Artifacts require a path"); + } - if(a.getNs()==null) { - if(sb.length()>0) { - sb.append('\n'); - } - sb.append("File Artifacts require an AAF Namespace"); - } - - if(sb.length()>0) { - throw new CadiException(sb.toString()); - } - } + if(a.getNs()==null) { + if(sb.length()>0) { + sb.append('\n'); + } + sb.append("File Artifacts require an AAF Namespace"); + } + + if(sb.length()>0) { + throw new CadiException(sb.toString()); + } + } - private boolean placeProperties(Artifact arti) throws CadiException { - if(encodeds.size()==0) { - return true; - } - boolean first=processed.get("dir")==null; - try { - File f = new File(dir,arti.getNs()+".cred.props"); - if(f.exists()) { - if(first) { - File backup = File.createTempFile(f.getName()+'.', ".backup",dir); - f.renameTo(backup); - } else { - f.setWritable(true); - } - } - - // Append if not first - PrintWriter pw = new PrintWriter(new FileWriter(f,!first)); - try { - // Write a Header - if(first) { - for(int i=0;i<60;++i) { - pw.print('#'); - } - pw.println(); - pw.println("# Properties Generated by AT&T Certificate Manager"); - pw.print("# by "); - pw.println(System.getProperty("user.name")); - pw.print("# on "); - pw.println(Chrono.dateStamp()); - pw.println("# @copyright 2016, AT&T"); - for(int i=0;i<60;++i) { - pw.print('#'); - } - pw.println(); - for(String prop : encodeds) { - if( prop.startsWith("cm_") - || prop.startsWith(Config.HOSTNAME) - || prop.startsWith(Config.AAF_ENV)) { - pw.println(prop); - } - } - } - - for(String prop : encodeds) { - if(prop.startsWith("cadi")) { - pw.println(prop); - } - } - } finally { - pw.close(); - } - Chmod.to644.chmod(f); - - if(first) { - // Challenge - f = new File(dir,arti.getNs()+".chal"); - if(f.exists()) { - f.delete(); - } - pw = new PrintWriter(new FileWriter(f)); - try { - for(String prop : encodeds) { - if(prop.startsWith("Challenge")) { - pw.println(prop); - } - } - } finally { - pw.close(); - } - Chmod.to400.chmod(f); - } - } catch(Exception e) { - throw new CadiException(e); - } - return true; - } - - public static void clear() { - processed.clear(); - } + private boolean placeProperties(Artifact arti) throws CadiException { + if(encodeds.size()==0) { + return true; + } + boolean first=processed.get("dir")==null; + try { + File f = new File(dir,arti.getNs()+".cred.props"); + if(f.exists()) { + if(first) { + File backup = File.createTempFile(f.getName()+'.', ".backup",dir); + f.renameTo(backup); + } else { + f.setWritable(true); + } + } + + // Append if not first + PrintWriter pw = new PrintWriter(new FileWriter(f,!first)); + try { + // Write a Header + if(first) { + for(int i=0;i<60;++i) { + pw.print('#'); + } + pw.println(); + pw.println("# Properties Generated by AT&T Certificate Manager"); + pw.print("# by "); + pw.println(System.getProperty("user.name")); + pw.print("# on "); + pw.println(Chrono.dateStamp()); + pw.println("# @copyright 2016, AT&T"); + for(int i=0;i<60;++i) { + pw.print('#'); + } + pw.println(); + for(String prop : encodeds) { + if( prop.startsWith("cm_") + || prop.startsWith(Config.HOSTNAME) + || prop.startsWith(Config.AAF_ENV)) { + pw.println(prop); + } + } + } + + for(String prop : encodeds) { + if(prop.startsWith("cadi")) { + pw.println(prop); + } + } + } finally { + pw.close(); + } + Chmod.to644.chmod(f); + + if(first) { + // Challenge + f = new File(dir,arti.getNs()+".chal"); + if(f.exists()) { + f.delete(); + } + pw = new PrintWriter(new FileWriter(f)); + try { + for(String prop : encodeds) { + if(prop.startsWith("Challenge")) { + pw.println(prop); + } + } + } finally { + pw.close(); + } + Chmod.to400.chmod(f); + } + } catch(Exception e) { + throw new CadiException(e); + } + return true; + } + + public static void clear() { + processed.clear(); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/CertException.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/CertException.java index 4ea5e335..526673e3 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/CertException.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/CertException.java @@ -23,23 +23,23 @@ package org.onap.aaf.cadi.configure; public class CertException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1373028409048516401L; + /** + * + */ + private static final long serialVersionUID = 1373028409048516401L; - public CertException() { - } + public CertException() { + } - public CertException(String message) { - super(message); - } + public CertException(String message) { + super(message); + } - public CertException(Throwable cause) { - super(cause); - } + public CertException(Throwable cause) { + super(cause); + } - public CertException(String message, Throwable cause) { - super(message, cause); - } + public CertException(String message, Throwable cause) { + super(message, cause); + } } \ No newline at end of file diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java index 5bb99131..40f31706 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java @@ -70,435 +70,435 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.Trans; public class Factory { - private static final String PRIVATE_KEY_HEADER = "PRIVATE KEY"; - public static final String KEY_ALGO = "RSA"; - public static final String SIG_ALGO = "SHA256withRSA"; - - public static final int KEY_LENGTH = 2048; - private static final KeyPairGenerator keygen; - private static final KeyFactory keyFactory; - private static final CertificateFactory certificateFactory; - private static final SecureRandom random; - - - private static final Symm base64 = Symm.base64.copy(64); - - static { - random = new SecureRandom(); - KeyPairGenerator tempKeygen; - try { - tempKeygen = KeyPairGenerator.getInstance(KEY_ALGO);//,"BC"); - tempKeygen.initialize(KEY_LENGTH, random); - } catch (NoSuchAlgorithmException e) { - tempKeygen = null; - e.printStackTrace(System.err); - } - keygen = tempKeygen; - - KeyFactory tempKeyFactory; - try { - tempKeyFactory=KeyFactory.getInstance(KEY_ALGO);//,"BC" - } catch (NoSuchAlgorithmException e) { - tempKeyFactory = null; - e.printStackTrace(System.err); - }; - keyFactory = tempKeyFactory; - - CertificateFactory tempCertificateFactory; - try { - tempCertificateFactory = CertificateFactory.getInstance("X.509"); - } catch (CertificateException e) { - tempCertificateFactory = null; - e.printStackTrace(System.err); - } - certificateFactory = tempCertificateFactory; - - - } - - - public static KeyPair generateKeyPair(Trans trans) { - TimeTaken tt; - if(trans!=null) { - tt = trans.start("Generate KeyPair", Env.SUB); - } else { - tt = null; - } - try { - return keygen.generateKeyPair(); - } finally { - if(tt!=null) { - tt.done(); - } - } - } - - private static final String LINE_END = "-----\n"; - - protected static String textBuilder(String kind, byte[] bytes) throws IOException { - StringBuilder sb = new StringBuilder(); - sb.append("-----BEGIN "); - sb.append(kind); - sb.append(LINE_END); - - ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - base64.encode(bais, baos); - sb.append(new String(baos.toByteArray())); - - if(sb.charAt(sb.length()-1)!='\n') { - sb.append('\n'); - } - sb.append("-----END "); - sb.append(kind); - sb.append(LINE_END); - return sb.toString(); - } - - public static PrivateKey toPrivateKey(Trans trans, String pk) throws IOException, CertException { - byte[] bytes = decode(new StringReader(pk), null); - return toPrivateKey(trans, bytes); - } - - public static PrivateKey toPrivateKey(Trans trans, byte[] bytes) throws IOException, CertException { - TimeTaken tt=trans.start("Reconstitute Private Key", Env.SUB); - try { - return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(bytes)); - } catch (InvalidKeySpecException e) { - throw new CertException("Translating Private Key from PKCS8 KeySpec",e); - } finally { - tt.done(); - } - } - - public static PrivateKey toPrivateKey(Trans trans, File file) throws IOException, CertException { - TimeTaken tt = trans.start("Decode Private Key File", Env.SUB); - try { - Holder firstLine = new Holder(null); - return toPrivateKey(trans,decode(file,firstLine)); - }finally { - tt.done(); - } - } - - public static String toString(Trans trans, PrivateKey pk) throws IOException { -// PKCS8EncodedKeySpec pemContents = new PKCS8EncodedKeySpec(pk.getEncoded()); - trans.debug().log("Private Key to String"); - return textBuilder(PRIVATE_KEY_HEADER,pk.getEncoded()); - } - - public static PublicKey toPublicKey(Trans trans, String pk) throws IOException { - TimeTaken tt = trans.start("Reconstitute Public Key", Env.SUB); - try { - ByteArrayInputStream bais = new ByteArrayInputStream(pk.getBytes()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Symm.base64noSplit.decode(new StripperInputStream(bais), baos); - - return keyFactory.generatePublic(new X509EncodedKeySpec(baos.toByteArray())); - } catch (InvalidKeySpecException e) { - trans.error().log(e,"Translating Public Key from X509 KeySpec"); - return null; - } finally { - tt.done(); - } - } - - public static String toString(Trans trans, PublicKey pk) throws IOException { - trans.debug().log("Public Key to String"); - return textBuilder("PUBLIC KEY",pk.getEncoded()); - } - - public static Collection toX509Certificate(String x509) throws CertificateException { - return toX509Certificate(x509.getBytes()); - } - - public static Collection toX509Certificate(List x509s) throws CertificateException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - for(String x509 : x509s) { - baos.write(x509.getBytes()); - } - } catch (IOException e) { - throw new CertificateException(e); - } - return toX509Certificate(new ByteArrayInputStream(baos.toByteArray())); - } - - public static Collection toX509Certificate(byte[] x509) throws CertificateException { - return certificateFactory.generateCertificates(new ByteArrayInputStream(x509)); - } - - public static Collection toX509Certificate(Trans trans, File file) throws CertificateException, FileNotFoundException { - FileInputStream fis = new FileInputStream(file); - try { - try { - return toX509Certificate(fis); - } finally { - fis.close(); - } - } catch (IOException e) { - throw new CertificateException(e); - } - } - - public static Collection toX509Certificate(InputStream is) throws CertificateException { - return certificateFactory.generateCertificates(is); - } - - public static String toString(Trans trans, Certificate cert) throws IOException, CertException { - if(trans.debug().isLoggable()) { - StringBuilder sb = new StringBuilder("Certificate to String"); - if(cert instanceof X509Certificate) { - sb.append(" - "); - sb.append(((X509Certificate)cert).getSubjectDN()); - } - trans.debug().log(sb); - } - try { - if(cert==null) { - throw new CertException("Certificate not built"); - } - return textBuilder("CERTIFICATE",cert.getEncoded()); - } catch (CertificateEncodingException e) { - throw new CertException(e); - } - } - - public static Cipher pkCipher() throws NoSuchAlgorithmException, NoSuchPaddingException { - return Cipher.getInstance(KEY_ALGO); - } - - public static Cipher pkCipher(Key key, boolean encrypt) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { - Cipher cipher = Cipher.getInstance(KEY_ALGO); - cipher.init(encrypt?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE,key); - return cipher; - } - - public static byte[] strip(Reader rdr) throws IOException { - return strip(rdr,null); - } - - public static byte[] strip(Reader rdr, Holder hs) throws IOException { - BufferedReader br = new BufferedReader(rdr); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - String line; - boolean notStarted = true; - while((line=br.readLine())!=null) { - if(notStarted) { - if(line.startsWith("-----")) { - notStarted = false; - if(hs!=null) { - hs.set(line); - } - } else { - continue; - } - } - if(line.length()>0 && - !line.startsWith("-----") && - line.indexOf(':')<0) { // Header elements - baos.write(line.getBytes()); - } - } - return baos.toByteArray(); - } - - public static class StripperInputStream extends InputStream { - private Reader created; - private BufferedReader br; - private int idx; - private String line; - - public StripperInputStream(Reader rdr) { - if(rdr instanceof BufferedReader) { - br = (BufferedReader)rdr; - } else { - br = new BufferedReader(rdr); - } - created = null; - } - - public StripperInputStream(File file) throws FileNotFoundException { - this(new FileReader(file)); - created = br; - } - - public StripperInputStream(InputStream is) throws FileNotFoundException { - this(new InputStreamReader(is)); - created = br; - } - - @Override - public int read() throws IOException { - if(line==null || idx>=line.length()) { - while((line=br.readLine())!=null) { - if(line.length()>0 && - !line.startsWith("-----") && - line.indexOf(':')<0) { // Header elements - break; - } - } - - if(line==null) { - return -1; - } - idx = 0; - } - return line.charAt(idx++); - } - - /* (non-Javadoc) - * @see java.io.InputStream#close() - */ - @Override - public void close() throws IOException { - if(created!=null) { - created.close(); - } - } - } - - public static class Base64InputStream extends InputStream { - private InputStream created; - private InputStream is; - private byte trio[]; - private byte duo[]; - private int idx; - - - public Base64InputStream(File file) throws FileNotFoundException { - this(new FileInputStream(file)); - created = is; - } - - public Base64InputStream(InputStream is) throws FileNotFoundException { - this.is = is; - trio = new byte[3]; - idx = 4; - } - - @Override - public int read() throws IOException { - if(duo==null || idx>=duo.length) { - int read = is.read(trio); - if(read==-1) { - return -1; - } - duo = Symm.base64.decode(trio); - if(duo==null || duo.length==0) { - return -1; - } - idx=0; - } - - return duo[idx++]; - } - - /* (non-Javadoc) - * @see java.io.InputStream#close() - */ - @Override - public void close() throws IOException { - if(created!=null) { - created.close(); - } - } - } - - public static byte[] decode(byte[] bytes) throws IOException { - ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Symm.base64.decode(bais, baos); - return baos.toByteArray(); - } - - public static byte[] decode(File f, Holder hs) throws IOException { - FileReader fr = new FileReader(f); - try { - return Factory.decode(fr,hs); - } finally { - fr.close(); - } - } - - - public static byte[] decode(Reader rdr,Holder hs) throws IOException { - return decode(strip(rdr,hs)); - } - - - public static byte[] binary(File file) throws IOException { - DataInputStream dis = new DataInputStream(new FileInputStream(file)); - try { - byte[] bytes = new byte[(int)file.length()]; - dis.readFully(bytes); - return bytes; - } finally { - dis.close(); - } - } - - - public static byte[] sign(Trans trans, byte[] bytes, PrivateKey pk) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException { - TimeTaken tt = trans.start("Sign Data", Env.SUB); - try { - Signature sig = Signature.getInstance(SIG_ALGO); - sig.initSign(pk, random); - sig.update(bytes); - return sig.sign(); - } finally { - tt.done(); - } - } - - public static String toSignatureString(byte[] signed) throws IOException { - return textBuilder("SIGNATURE", signed); - } - - public static boolean verify(Trans trans, byte[] bytes, byte[] signature, PublicKey pk) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { - TimeTaken tt = trans.start("Verify Data", Env.SUB); - try { - Signature sig = Signature.getInstance(SIG_ALGO); - sig.initVerify(pk); - sig.update(bytes); - return sig.verify(signature); - } finally { - tt.done(); - } - } - - /** - * Get the Security Provider, or, if not exists yet, attempt to load - * - * @param providerType - * @param params - * @return - * @throws CertException - */ - public static synchronized Provider getSecurityProvider(String providerType, String[][] params) throws CertException { - Provider p = Security.getProvider(providerType); - if(p!=null) { - switch(providerType) { - case "PKCS12": - - break; - case "PKCS11": // PKCS11 only known to be supported by Sun - try { - Class clsSunPKCS11 = Class.forName("sun.security.pkcs11.SunPKCS11"); - Constructor cnst = clsSunPKCS11.getConstructor(String.class); - Object sunPKCS11 = cnst.newInstance(params[0][0]); - if (sunPKCS11==null) { - throw new CertException("SunPKCS11 Provider cannot be constructed for " + params[0][0]); - } - Security.addProvider((Provider)sunPKCS11); - } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new CertException(e); - } - break; - default: - throw new CertException(providerType + " is not a known Security Provider for your JDK."); - } - } - return p; - } + private static final String PRIVATE_KEY_HEADER = "PRIVATE KEY"; + public static final String KEY_ALGO = "RSA"; + public static final String SIG_ALGO = "SHA256withRSA"; + + public static final int KEY_LENGTH = 2048; + private static final KeyPairGenerator keygen; + private static final KeyFactory keyFactory; + private static final CertificateFactory certificateFactory; + private static final SecureRandom random; + + + private static final Symm base64 = Symm.base64.copy(64); + + static { + random = new SecureRandom(); + KeyPairGenerator tempKeygen; + try { + tempKeygen = KeyPairGenerator.getInstance(KEY_ALGO);//,"BC"); + tempKeygen.initialize(KEY_LENGTH, random); + } catch (NoSuchAlgorithmException e) { + tempKeygen = null; + e.printStackTrace(System.err); + } + keygen = tempKeygen; + + KeyFactory tempKeyFactory; + try { + tempKeyFactory=KeyFactory.getInstance(KEY_ALGO);//,"BC" + } catch (NoSuchAlgorithmException e) { + tempKeyFactory = null; + e.printStackTrace(System.err); + }; + keyFactory = tempKeyFactory; + + CertificateFactory tempCertificateFactory; + try { + tempCertificateFactory = CertificateFactory.getInstance("X.509"); + } catch (CertificateException e) { + tempCertificateFactory = null; + e.printStackTrace(System.err); + } + certificateFactory = tempCertificateFactory; + + + } + + + public static KeyPair generateKeyPair(Trans trans) { + TimeTaken tt; + if(trans!=null) { + tt = trans.start("Generate KeyPair", Env.SUB); + } else { + tt = null; + } + try { + return keygen.generateKeyPair(); + } finally { + if(tt!=null) { + tt.done(); + } + } + } + + private static final String LINE_END = "-----\n"; + + protected static String textBuilder(String kind, byte[] bytes) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append("-----BEGIN "); + sb.append(kind); + sb.append(LINE_END); + + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + base64.encode(bais, baos); + sb.append(new String(baos.toByteArray())); + + if(sb.charAt(sb.length()-1)!='\n') { + sb.append('\n'); + } + sb.append("-----END "); + sb.append(kind); + sb.append(LINE_END); + return sb.toString(); + } + + public static PrivateKey toPrivateKey(Trans trans, String pk) throws IOException, CertException { + byte[] bytes = decode(new StringReader(pk), null); + return toPrivateKey(trans, bytes); + } + + public static PrivateKey toPrivateKey(Trans trans, byte[] bytes) throws IOException, CertException { + TimeTaken tt=trans.start("Reconstitute Private Key", Env.SUB); + try { + return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(bytes)); + } catch (InvalidKeySpecException e) { + throw new CertException("Translating Private Key from PKCS8 KeySpec",e); + } finally { + tt.done(); + } + } + + public static PrivateKey toPrivateKey(Trans trans, File file) throws IOException, CertException { + TimeTaken tt = trans.start("Decode Private Key File", Env.SUB); + try { + Holder firstLine = new Holder(null); + return toPrivateKey(trans,decode(file,firstLine)); + }finally { + tt.done(); + } + } + + public static String toString(Trans trans, PrivateKey pk) throws IOException { +// PKCS8EncodedKeySpec pemContents = new PKCS8EncodedKeySpec(pk.getEncoded()); + trans.debug().log("Private Key to String"); + return textBuilder(PRIVATE_KEY_HEADER,pk.getEncoded()); + } + + public static PublicKey toPublicKey(Trans trans, String pk) throws IOException { + TimeTaken tt = trans.start("Reconstitute Public Key", Env.SUB); + try { + ByteArrayInputStream bais = new ByteArrayInputStream(pk.getBytes()); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Symm.base64noSplit.decode(new StripperInputStream(bais), baos); + + return keyFactory.generatePublic(new X509EncodedKeySpec(baos.toByteArray())); + } catch (InvalidKeySpecException e) { + trans.error().log(e,"Translating Public Key from X509 KeySpec"); + return null; + } finally { + tt.done(); + } + } + + public static String toString(Trans trans, PublicKey pk) throws IOException { + trans.debug().log("Public Key to String"); + return textBuilder("PUBLIC KEY",pk.getEncoded()); + } + + public static Collection toX509Certificate(String x509) throws CertificateException { + return toX509Certificate(x509.getBytes()); + } + + public static Collection toX509Certificate(List x509s) throws CertificateException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + for(String x509 : x509s) { + baos.write(x509.getBytes()); + } + } catch (IOException e) { + throw new CertificateException(e); + } + return toX509Certificate(new ByteArrayInputStream(baos.toByteArray())); + } + + public static Collection toX509Certificate(byte[] x509) throws CertificateException { + return certificateFactory.generateCertificates(new ByteArrayInputStream(x509)); + } + + public static Collection toX509Certificate(Trans trans, File file) throws CertificateException, FileNotFoundException { + FileInputStream fis = new FileInputStream(file); + try { + try { + return toX509Certificate(fis); + } finally { + fis.close(); + } + } catch (IOException e) { + throw new CertificateException(e); + } + } + + public static Collection toX509Certificate(InputStream is) throws CertificateException { + return certificateFactory.generateCertificates(is); + } + + public static String toString(Trans trans, Certificate cert) throws IOException, CertException { + if(trans.debug().isLoggable()) { + StringBuilder sb = new StringBuilder("Certificate to String"); + if(cert instanceof X509Certificate) { + sb.append(" - "); + sb.append(((X509Certificate)cert).getSubjectDN()); + } + trans.debug().log(sb); + } + try { + if(cert==null) { + throw new CertException("Certificate not built"); + } + return textBuilder("CERTIFICATE",cert.getEncoded()); + } catch (CertificateEncodingException e) { + throw new CertException(e); + } + } + + public static Cipher pkCipher() throws NoSuchAlgorithmException, NoSuchPaddingException { + return Cipher.getInstance(KEY_ALGO); + } + + public static Cipher pkCipher(Key key, boolean encrypt) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { + Cipher cipher = Cipher.getInstance(KEY_ALGO); + cipher.init(encrypt?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE,key); + return cipher; + } + + public static byte[] strip(Reader rdr) throws IOException { + return strip(rdr,null); + } + + public static byte[] strip(Reader rdr, Holder hs) throws IOException { + BufferedReader br = new BufferedReader(rdr); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + String line; + boolean notStarted = true; + while((line=br.readLine())!=null) { + if(notStarted) { + if(line.startsWith("-----")) { + notStarted = false; + if(hs!=null) { + hs.set(line); + } + } else { + continue; + } + } + if(line.length()>0 && + !line.startsWith("-----") && + line.indexOf(':')<0) { // Header elements + baos.write(line.getBytes()); + } + } + return baos.toByteArray(); + } + + public static class StripperInputStream extends InputStream { + private Reader created; + private BufferedReader br; + private int idx; + private String line; + + public StripperInputStream(Reader rdr) { + if(rdr instanceof BufferedReader) { + br = (BufferedReader)rdr; + } else { + br = new BufferedReader(rdr); + } + created = null; + } + + public StripperInputStream(File file) throws FileNotFoundException { + this(new FileReader(file)); + created = br; + } + + public StripperInputStream(InputStream is) throws FileNotFoundException { + this(new InputStreamReader(is)); + created = br; + } + + @Override + public int read() throws IOException { + if(line==null || idx>=line.length()) { + while((line=br.readLine())!=null) { + if(line.length()>0 && + !line.startsWith("-----") && + line.indexOf(':')<0) { // Header elements + break; + } + } + + if(line==null) { + return -1; + } + idx = 0; + } + return line.charAt(idx++); + } + + /* (non-Javadoc) + * @see java.io.InputStream#close() + */ + @Override + public void close() throws IOException { + if(created!=null) { + created.close(); + } + } + } + + public static class Base64InputStream extends InputStream { + private InputStream created; + private InputStream is; + private byte trio[]; + private byte duo[]; + private int idx; + + + public Base64InputStream(File file) throws FileNotFoundException { + this(new FileInputStream(file)); + created = is; + } + + public Base64InputStream(InputStream is) throws FileNotFoundException { + this.is = is; + trio = new byte[3]; + idx = 4; + } + + @Override + public int read() throws IOException { + if(duo==null || idx>=duo.length) { + int read = is.read(trio); + if(read==-1) { + return -1; + } + duo = Symm.base64.decode(trio); + if(duo==null || duo.length==0) { + return -1; + } + idx=0; + } + + return duo[idx++]; + } + + /* (non-Javadoc) + * @see java.io.InputStream#close() + */ + @Override + public void close() throws IOException { + if(created!=null) { + created.close(); + } + } + } + + public static byte[] decode(byte[] bytes) throws IOException { + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Symm.base64.decode(bais, baos); + return baos.toByteArray(); + } + + public static byte[] decode(File f, Holder hs) throws IOException { + FileReader fr = new FileReader(f); + try { + return Factory.decode(fr,hs); + } finally { + fr.close(); + } + } + + + public static byte[] decode(Reader rdr,Holder hs) throws IOException { + return decode(strip(rdr,hs)); + } + + + public static byte[] binary(File file) throws IOException { + DataInputStream dis = new DataInputStream(new FileInputStream(file)); + try { + byte[] bytes = new byte[(int)file.length()]; + dis.readFully(bytes); + return bytes; + } finally { + dis.close(); + } + } + + + public static byte[] sign(Trans trans, byte[] bytes, PrivateKey pk) throws IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException { + TimeTaken tt = trans.start("Sign Data", Env.SUB); + try { + Signature sig = Signature.getInstance(SIG_ALGO); + sig.initSign(pk, random); + sig.update(bytes); + return sig.sign(); + } finally { + tt.done(); + } + } + + public static String toSignatureString(byte[] signed) throws IOException { + return textBuilder("SIGNATURE", signed); + } + + public static boolean verify(Trans trans, byte[] bytes, byte[] signature, PublicKey pk) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { + TimeTaken tt = trans.start("Verify Data", Env.SUB); + try { + Signature sig = Signature.getInstance(SIG_ALGO); + sig.initVerify(pk); + sig.update(bytes); + return sig.verify(signature); + } finally { + tt.done(); + } + } + + /** + * Get the Security Provider, or, if not exists yet, attempt to load + * + * @param providerType + * @param params + * @return + * @throws CertException + */ + public static synchronized Provider getSecurityProvider(String providerType, String[][] params) throws CertException { + Provider p = Security.getProvider(providerType); + if(p!=null) { + switch(providerType) { + case "PKCS12": + + break; + case "PKCS11": // PKCS11 only known to be supported by Sun + try { + Class clsSunPKCS11 = Class.forName("sun.security.pkcs11.SunPKCS11"); + Constructor cnst = clsSunPKCS11.getConstructor(String.class); + Object sunPKCS11 = cnst.newInstance(params[0][0]); + if (sunPKCS11==null) { + throw new CertException("SunPKCS11 Provider cannot be constructed for " + params[0][0]); + } + Security.addProvider((Provider)sunPKCS11); + } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new CertException(e); + } + break; + default: + throw new CertException(providerType + " is not a known Security Provider for your JDK."); + } + } + return p; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifact.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifact.java index 4b200c04..2d7d3124 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifact.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifact.java @@ -28,5 +28,5 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.misc.env.Trans; public interface PlaceArtifact { - public boolean place(Trans trans, CertInfo cert, Artifact arti, String machine) throws CadiException; + public boolean place(Trans trans, CertInfo cert, Artifact arti, String machine) throws CadiException; } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInFiles.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInFiles.java index 25fe776c..93c5a12a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInFiles.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInFiles.java @@ -31,23 +31,23 @@ import certman.v1_0.Artifacts.Artifact; import certman.v1_0.CertInfo; public class PlaceArtifactInFiles extends ArtifactDir { - @Override - public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { - try { - // Setup Public Cert - File f = new File(dir,arti.getNs()+".crt"); - // In Version 1.0, App Cert is first - write(f,Chmod.to644,certInfo.getCerts().get(0),C_R); - - // Setup Private Key - f = new File(dir,arti.getNs()+".key"); - write(f,Chmod.to400,certInfo.getPrivatekey(),C_R); - - } catch (Exception e) { - throw new CadiException(e); - } - return true; - } + @Override + public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { + try { + // Setup Public Cert + File f = new File(dir,arti.getNs()+".crt"); + // In Version 1.0, App Cert is first + write(f,Chmod.to644,certInfo.getCerts().get(0),C_R); + + // Setup Private Key + f = new File(dir,arti.getNs()+".key"); + write(f,Chmod.to400,certInfo.getPrivatekey(),C_R); + + } catch (Exception e) { + throw new CadiException(e); + } + return true; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java index c5413919..e85b903f 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java @@ -42,109 +42,109 @@ import certman.v1_0.Artifacts.Artifact; import certman.v1_0.CertInfo; public class PlaceArtifactInKeystore extends ArtifactDir { - private String kst; + private String kst; - public PlaceArtifactInKeystore(String kst) { - this.kst = kst; - } + public PlaceArtifactInKeystore(String kst) { + this.kst = kst; + } - @Override - public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { - File fks = new File(dir,arti.getNs()+'.'+(kst==Agent.PKCS12?"p12":kst)); - try { - KeyStore jks = KeyStore.getInstance(kst); - if(fks.exists()) { - File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); - fks.renameTo(backup); - } + @Override + public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { + File fks = new File(dir,arti.getNs()+'.'+(kst==Agent.PKCS12?"p12":kst)); + try { + KeyStore jks = KeyStore.getInstance(kst); + if(fks.exists()) { + File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); + fks.renameTo(backup); + } - // Get the Cert(s)... Might include Trust store - Collection certColl = Factory.toX509Certificate(certInfo.getCerts()); - // find where the trusts end in 1.0 API - - X509Certificate x509; - List chainList = new ArrayList<>(); - Set caSet = new HashSet<>(); - for(Certificate c : certColl) { - x509 = (X509Certificate)c; - // Is a Root (self-signed, anyway) - if(x509.getSubjectDN().equals(x509.getIssuerDN())) { - caSet.add(x509); - } else { - chainList.add(x509); - } - } -// chainList.addAll(caSet); - //Collections.reverse(chainList); + // Get the Cert(s)... Might include Trust store + Collection certColl = Factory.toX509Certificate(certInfo.getCerts()); + // find where the trusts end in 1.0 API + + X509Certificate x509; + List chainList = new ArrayList<>(); + Set caSet = new HashSet<>(); + for(Certificate c : certColl) { + x509 = (X509Certificate)c; + // Is a Root (self-signed, anyway) + if(x509.getSubjectDN().equals(x509.getIssuerDN())) { + caSet.add(x509); + } else { + chainList.add(x509); + } + } +// chainList.addAll(caSet); + //Collections.reverse(chainList); - // Properties, etc - // Add CADI Keyfile Entry to Properties - addProperty(Config.CADI_KEYFILE,arti.getDir()+'/'+arti.getNs() + ".keyfile"); - // Set Keystore Password - addProperty(Config.CADI_KEYSTORE,fks.getAbsolutePath()); - String keystorePass = Symm.randomGen(Agent.PASS_SIZE); - addEncProperty(Config.CADI_KEYSTORE_PASSWORD,keystorePass); - char[] keystorePassArray = keystorePass.toCharArray(); - jks.load(null,keystorePassArray); // load in - - // Add Private Key/Cert Entry for App - // Note: Java SSL security classes, while having a separate key from keystore, - // is documented to not actually work. - // java.security.UnrecoverableKeyException: Cannot recover key - // You can create a custom Key Manager to make it work, but Practicality - // dictates that you live with the default, meaning, they are the same - String keyPass = keystorePass; //Symm.randomGen(CmAgent.PASS_SIZE); - PrivateKey pk = Factory.toPrivateKey(trans, certInfo.getPrivatekey()); - addEncProperty(Config.CADI_KEY_PASSWORD, keyPass); - addProperty(Config.CADI_ALIAS, arti.getMechid()); -// Set attribs = new HashSet<>(); -// if(kst.equals("pkcs12")) { -// // Friendly Name -// attribs.add(new PKCS12Attribute("1.2.840.113549.1.9.20", arti.getNs())); -// } -// - KeyStore.ProtectionParameter protParam = - new KeyStore.PasswordProtection(keyPass.toCharArray()); - - Certificate[] trustChain = new Certificate[chainList.size()]; - chainList.toArray(trustChain); - KeyStore.PrivateKeyEntry pkEntry = - new KeyStore.PrivateKeyEntry(pk, trustChain); - jks.setEntry(arti.getMechid(), - pkEntry, protParam); + // Properties, etc + // Add CADI Keyfile Entry to Properties + addProperty(Config.CADI_KEYFILE,arti.getDir()+'/'+arti.getNs() + ".keyfile"); + // Set Keystore Password + addProperty(Config.CADI_KEYSTORE,fks.getAbsolutePath()); + String keystorePass = Symm.randomGen(Agent.PASS_SIZE); + addEncProperty(Config.CADI_KEYSTORE_PASSWORD,keystorePass); + char[] keystorePassArray = keystorePass.toCharArray(); + jks.load(null,keystorePassArray); // load in + + // Add Private Key/Cert Entry for App + // Note: Java SSL security classes, while having a separate key from keystore, + // is documented to not actually work. + // java.security.UnrecoverableKeyException: Cannot recover key + // You can create a custom Key Manager to make it work, but Practicality + // dictates that you live with the default, meaning, they are the same + String keyPass = keystorePass; //Symm.randomGen(CmAgent.PASS_SIZE); + PrivateKey pk = Factory.toPrivateKey(trans, certInfo.getPrivatekey()); + addEncProperty(Config.CADI_KEY_PASSWORD, keyPass); + addProperty(Config.CADI_ALIAS, arti.getMechid()); +// Set attribs = new HashSet<>(); +// if(kst.equals("pkcs12")) { +// // Friendly Name +// attribs.add(new PKCS12Attribute("1.2.840.113549.1.9.20", arti.getNs())); +// } +// + KeyStore.ProtectionParameter protParam = + new KeyStore.PasswordProtection(keyPass.toCharArray()); + + Certificate[] trustChain = new Certificate[chainList.size()]; + chainList.toArray(trustChain); + KeyStore.PrivateKeyEntry pkEntry = + new KeyStore.PrivateKeyEntry(pk, trustChain); + jks.setEntry(arti.getMechid(), + pkEntry, protParam); - // Write out - write(fks,Chmod.to400,jks,keystorePassArray); - - // Change out to TrustStore - // NOTE: PKCS12 does NOT support Trusted Entries. Put in JKS Always - fks = new File(dir,arti.getNs()+".trust.jks"); - if(fks.exists()) { - File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); - fks.renameTo(backup); - } + // Write out + write(fks,Chmod.to400,jks,keystorePassArray); + + // Change out to TrustStore + // NOTE: PKCS12 does NOT support Trusted Entries. Put in JKS Always + fks = new File(dir,arti.getNs()+".trust.jks"); + if(fks.exists()) { + File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); + fks.renameTo(backup); + } - jks = KeyStore.getInstance(Agent.JKS); - - // Set Truststore Password - addProperty(Config.CADI_TRUSTSTORE,fks.getAbsolutePath()); - String trustStorePass = Symm.randomGen(Agent.PASS_SIZE); - addEncProperty(Config.CADI_TRUSTSTORE_PASSWORD,trustStorePass); - char[] truststorePassArray = trustStorePass.toCharArray(); - jks.load(null,truststorePassArray); // load in - - // Add Trusted Certificates, but PKCS12 doesn't support - Certificate[] trustCAs = new Certificate[caSet.size()]; - caSet.toArray(trustCAs); - for(int i=0; i0) { - trans.info().printf("Warning: %s" + lineSeparator, capi.getNotes()); - } - out.printf("Challenge: %s" + lineSeparator, capi.getChallenge()); - out.printf("PrivateKey:" + lineSeparator + "%s" + lineSeparator, capi.getPrivatekey()); - out.println("Certificate Chain:"); - for(String c : capi.getCerts()) { - out.println(c); - } - return true; - } + private PrintStream out; + + public PlaceArtifactOnStream(PrintStream printStream) { + out = printStream; + } + + @Override + public boolean place(Trans trans, CertInfo capi, Artifact a, String machine) { + String lineSeparator = System.lineSeparator(); + + if(capi.getNotes()!=null && capi.getNotes().length()>0) { + trans.info().printf("Warning: %s" + lineSeparator, capi.getNotes()); + } + out.printf("Challenge: %s" + lineSeparator, capi.getChallenge()); + out.printf("PrivateKey:" + lineSeparator + "%s" + lineSeparator, capi.getPrivatekey()); + out.println("Certificate Chain:"); + for(String c : capi.getCerts()) { + out.println(c); + } + return true; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java index 84161b50..2393c4c8 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java @@ -33,124 +33,124 @@ import certman.v1_0.Artifacts.Artifact; import certman.v1_0.CertInfo; public class PlaceArtifactScripts extends ArtifactDir { - @Override - public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { - try { - // Setup check.sh script - String filename = arti.getNs()+".check.sh"; - File f1 = new File(dir,filename); - String email = arti.getNotification() + '\n'; - if(email.startsWith("mailto:")) { - email=email.substring(7); - } else { - email=arti.getOsUser() + '\n'; - } - - StringBuilder classpath = new StringBuilder(); - boolean first = true; - for(String pth : Split.split(File.pathSeparatorChar, System.getProperty("java.class.path"))) { - if(first) { - first=false; - } else { - classpath.append(File.pathSeparatorChar); - } - File f = new File(pth); - classpath.append(f.getCanonicalPath().replaceAll("[0-9]+\\.[0-9]+\\.[0-9]+","*")); - } - - write(f1,Chmod.to644, - "#!/bin/bash " + f1.getCanonicalPath()+'\n', - "# Certificate Manager Check Script\n", - "# Check on Certificate, and renew if needed.\n", - "# Generated by Certificate Manager " + Chrono.timeStamp()+'\n', - "DIR="+arti.getDir()+'\n', - "APP="+arti.getNs()+'\n', - "EMAIL="+email, - "CP=\""+classpath.toString()+"\"\n", - checkScript - ); - - // Setup check.sh script - File f2 = new File(dir,arti.getNs()+".crontab.sh"); - write(f2,Chmod.to644, - "#!/bin/bash " + f2.getCanonicalPath()+'\n', - "# Certificate Manager Crontab Loading Script\n", - "# Add/Update a Crontab entry, that adds a check on Certificate Manager generated Certificate nightly.\n", - "# Generated by Certificate Manager " + Chrono.timeStamp()+'\n', - "TFILE=\"/tmp/cmcron$$.temp\"\n", - "DIR=\""+arti.getDir()+"\"\n", - "CF=\""+arti.getNs()+" Certificate Check Script\"\n", - "SCRIPT=\""+f1.getCanonicalPath()+"\"\n", - cronScript - ); + @Override + public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { + try { + // Setup check.sh script + String filename = arti.getNs()+".check.sh"; + File f1 = new File(dir,filename); + String email = arti.getNotification() + '\n'; + if(email.startsWith("mailto:")) { + email=email.substring(7); + } else { + email=arti.getOsUser() + '\n'; + } + + StringBuilder classpath = new StringBuilder(); + boolean first = true; + for(String pth : Split.split(File.pathSeparatorChar, System.getProperty("java.class.path"))) { + if(first) { + first=false; + } else { + classpath.append(File.pathSeparatorChar); + } + File f = new File(pth); + classpath.append(f.getCanonicalPath().replaceAll("[0-9]+\\.[0-9]+\\.[0-9]+","*")); + } + + write(f1,Chmod.to644, + "#!/bin/bash " + f1.getCanonicalPath()+'\n', + "# Certificate Manager Check Script\n", + "# Check on Certificate, and renew if needed.\n", + "# Generated by Certificate Manager " + Chrono.timeStamp()+'\n', + "DIR="+arti.getDir()+'\n', + "APP="+arti.getNs()+'\n', + "EMAIL="+email, + "CP=\""+classpath.toString()+"\"\n", + checkScript + ); + + // Setup check.sh script + File f2 = new File(dir,arti.getNs()+".crontab.sh"); + write(f2,Chmod.to644, + "#!/bin/bash " + f2.getCanonicalPath()+'\n', + "# Certificate Manager Crontab Loading Script\n", + "# Add/Update a Crontab entry, that adds a check on Certificate Manager generated Certificate nightly.\n", + "# Generated by Certificate Manager " + Chrono.timeStamp()+'\n', + "TFILE=\"/tmp/cmcron$$.temp\"\n", + "DIR=\""+arti.getDir()+"\"\n", + "CF=\""+arti.getNs()+" Certificate Check Script\"\n", + "SCRIPT=\""+f1.getCanonicalPath()+"\"\n", + cronScript + ); - } catch (Exception e) { - throw new CadiException(e); - } - return true; - } - - /** - * Note: java.home gets Absolute Path of Java, where we probably want soft links from - * JAVA_HOME - * @return - */ - private final static String javaHome() { - String rc = System.getenv("JAVA_HOME"); - return rc==null?System.getProperty("java.home"):rc; - } - private final static String checkScript = - "> $DIR/$APP.msg\n\n" + - "function mailit {\n" + - " if [ -e /bin/mail ]; then\n" + - " MAILER=/bin/mail\n" + - " elif [ -e /usr/bin/mail ]; then \n" + - " MAILER=/usr/bin/mail\n" + - " else \n" + - " MAILER=\"\"\n" + - " fi\n" + - " if [ \"$MAILER\" = \"\" ]; then\n" + - " printf \"$*\"\n" + - " else \n" + - " printf \"$*\" | $MAILER -s \"AAF Certman Notification for `uname -n`\" $EMAIL\n"+ - " fi\n" + - "}\n\n" + - javaHome() + "/bin/" +"java -cp $CP " + - Agent.class.getName() + - " cadi_prop_files=$DIR/$APP.props check 2> $DIR/$APP.STDERR > $DIR/$APP.STDOUT\n" + - "case \"$?\" in\n" + - " 0)\n" + - " # Note: Validation will be mailed only the first day after any modification\n" + - " if [ \"`find $DIR -mtime 0 -name $APP.check.sh`\" != \"\" ] ; then\n" + - " mailit `echo \"Certficate Validated:\\n\\n\" | cat - $DIR/$APP.msg`\n" + - " else\n" + - " cat $DIR/$APP.msg\n" + - " fi\n" + - " ;;\n" + - " 1) mailit \"Error with Certificate Check:\\\\n\\\\nCheck logs $DIR/$APP.STDOUT and $DIR/$APP.STDERR on `uname -n`\"\n" + - " ;;\n" + - " 2) mailit `echo \"Certificate Check Error\\\\n\\\\n\" | cat - $DIR/$APP.msg`\n" + - " ;;\n" + - " 10) mailit `echo \"Certificate Replaced\\\\n\\\\n\" | cat - $DIR/$APP.msg`\n" + - " if [ -e $DIR/$APP.restart.sh ]; then\n" + - " # Note: it is THIS SCRIPT'S RESPONSIBILITY to notify upon success or failure as necessary!!\n" + - " /bin/sh $DIR/$APP.restart.sh\n" + - " fi\n" + - " ;;\n" + - " *) mailit `echo \"Unknown Error code for CM Agent\\\\n\\\\n\" | cat - $DIR/$APP.msg`\n" + - " ;;\n" + - " esac\n\n" + - " # Note: make sure to cover this sripts' exit Code\n"; - - private final static String cronScript = - "crontab -l | sed -n \"/#### BEGIN $CF/,/END $CF ####/!p\" > $TFILE\n" + - "# Note: Randomize Minutes (0-60) and hours (1-4)\n" + - "echo \"#### BEGIN $CF ####\" >> $TFILE\n" + - "echo \"$(( $RANDOM % 60)) $(( $(( $RANDOM % 3 )) + 1 )) * * * /bin/bash $SCRIPT " + - ">> $DIR/cronlog 2>&1 \" >> $TFILE\n" + - "echo \"#### END $CF ####\" >> $TFILE\n" + - "crontab $TFILE\n" + - "rm $TFILE\n"; + } catch (Exception e) { + throw new CadiException(e); + } + return true; + } + + /** + * Note: java.home gets Absolute Path of Java, where we probably want soft links from + * JAVA_HOME + * @return + */ + private final static String javaHome() { + String rc = System.getenv("JAVA_HOME"); + return rc==null?System.getProperty("java.home"):rc; + } + private final static String checkScript = + "> $DIR/$APP.msg\n\n" + + "function mailit {\n" + + " if [ -e /bin/mail ]; then\n" + + " MAILER=/bin/mail\n" + + " elif [ -e /usr/bin/mail ]; then \n" + + " MAILER=/usr/bin/mail\n" + + " else \n" + + " MAILER=\"\"\n" + + " fi\n" + + " if [ \"$MAILER\" = \"\" ]; then\n" + + " printf \"$*\"\n" + + " else \n" + + " printf \"$*\" | $MAILER -s \"AAF Certman Notification for `uname -n`\" $EMAIL\n"+ + " fi\n" + + "}\n\n" + + javaHome() + "/bin/" +"java -cp $CP " + + Agent.class.getName() + + " cadi_prop_files=$DIR/$APP.props check 2> $DIR/$APP.STDERR > $DIR/$APP.STDOUT\n" + + "case \"$?\" in\n" + + " 0)\n" + + " # Note: Validation will be mailed only the first day after any modification\n" + + " if [ \"`find $DIR -mtime 0 -name $APP.check.sh`\" != \"\" ] ; then\n" + + " mailit `echo \"Certficate Validated:\\n\\n\" | cat - $DIR/$APP.msg`\n" + + " else\n" + + " cat $DIR/$APP.msg\n" + + " fi\n" + + " ;;\n" + + " 1) mailit \"Error with Certificate Check:\\\\n\\\\nCheck logs $DIR/$APP.STDOUT and $DIR/$APP.STDERR on `uname -n`\"\n" + + " ;;\n" + + " 2) mailit `echo \"Certificate Check Error\\\\n\\\\n\" | cat - $DIR/$APP.msg`\n" + + " ;;\n" + + " 10) mailit `echo \"Certificate Replaced\\\\n\\\\n\" | cat - $DIR/$APP.msg`\n" + + " if [ -e $DIR/$APP.restart.sh ]; then\n" + + " # Note: it is THIS SCRIPT'S RESPONSIBILITY to notify upon success or failure as necessary!!\n" + + " /bin/sh $DIR/$APP.restart.sh\n" + + " fi\n" + + " ;;\n" + + " *) mailit `echo \"Unknown Error code for CM Agent\\\\n\\\\n\" | cat - $DIR/$APP.msg`\n" + + " ;;\n" + + " esac\n\n" + + " # Note: make sure to cover this sripts' exit Code\n"; + + private final static String cronScript = + "crontab -l | sed -n \"/#### BEGIN $CF/,/END $CF ####/!p\" > $TFILE\n" + + "# Note: Randomize Minutes (0-60) and hours (1-4)\n" + + "echo \"#### BEGIN $CF ####\" >> $TFILE\n" + + "echo \"$(( $RANDOM % 60)) $(( $(( $RANDOM % 3 )) + 1 )) * * * /bin/bash $SCRIPT " + + ">> $DIR/cronlog 2>&1 \" >> $TFILE\n" + + "echo \"#### END $CF ####\" >> $TFILE\n" + + "crontab $TFILE\n" + + "rm $TFILE\n"; } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java index 16bd8669..38890681 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java @@ -28,59 +28,59 @@ import java.util.UUID; import org.onap.aaf.cadi.Hash; public class AAFToken { - private static final int CAPACITY = (Long.SIZE*2+Byte.SIZE*3)/8; - private static final SecureRandom sr = new SecureRandom(); + private static final int CAPACITY = (Long.SIZE*2+Byte.SIZE*3)/8; + private static final SecureRandom sr = new SecureRandom(); - public static final String toToken(UUID uuid) { - long lsb = uuid.getLeastSignificantBits(); - long msb = uuid.getMostSignificantBits(); - int sum=35; // AAF - for(int i=0;i>i) & 0xFF); - } - for(int i=0;i>i) & 0xFF))<<0xB); - } - sum+=(sr.nextInt()&0xEFC00000); // this is just to not leave zeros laying around + public static final String toToken(UUID uuid) { + long lsb = uuid.getLeastSignificantBits(); + long msb = uuid.getMostSignificantBits(); + int sum=35; // AAF + for(int i=0;i>i) & 0xFF); + } + for(int i=0;i>i) & 0xFF))<<0xB); + } + sum+=(sr.nextInt()&0xEFC00000); // this is just to not leave zeros laying around - ByteBuffer bb = ByteBuffer.allocate(CAPACITY); - bb.put((byte)sum); - bb.putLong(msb); - bb.put((byte)(sum>>8)); - bb.putLong(lsb); - bb.put((byte)(sum>>16)); - return Hash.toHexNo0x(bb.array()); - } + ByteBuffer bb = ByteBuffer.allocate(CAPACITY); + bb.put((byte)sum); + bb.putLong(msb); + bb.put((byte)(sum>>8)); + bb.putLong(lsb); + bb.put((byte)(sum>>16)); + return Hash.toHexNo0x(bb.array()); + } - public static final UUID fromToken(String token) { - byte[] bytes = Hash.fromHexNo0x(token); - if(bytes==null) { - return null; - } - ByteBuffer bb = ByteBuffer.wrap(bytes); - if(bb.capacity()!=CAPACITY ) { - return null; // not a CADI Token - } - byte b1 = bb.get(); - long msb = bb.getLong(); - byte b2 = bb.get(); - long lsb = bb.getLong(); - byte b3 = (byte)(0x3F&bb.get()); - int sum=35; - - for(int i=0;i>i) & 0xFF); - } - for(int i=0;i>i) & 0xFF))<<0xB); - } + public static final UUID fromToken(String token) { + byte[] bytes = Hash.fromHexNo0x(token); + if(bytes==null) { + return null; + } + ByteBuffer bb = ByteBuffer.wrap(bytes); + if(bb.capacity()!=CAPACITY ) { + return null; // not a CADI Token + } + byte b1 = bb.get(); + long msb = bb.getLong(); + byte b2 = bb.get(); + long lsb = bb.getLong(); + byte b3 = (byte)(0x3F&bb.get()); + int sum=35; + + for(int i=0;i>i) & 0xFF); + } + for(int i=0;i>i) & 0xFF))<<0xB); + } - if(b1!=((byte)sum) || - b2!=((byte)(sum>>8)) || - b3!=((byte)((sum>>16)))) { - return null; // not a CADI Token - } - return new UUID(msb, lsb); - } - + if(b1!=((byte)sum) || + b2!=((byte)(sum>>8)) || + b3!=((byte)((sum>>16)))) { + return null; // not a CADI Token + } + return new UUID(msb, lsb); + } + } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java index fb844518..26a8a69d 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java @@ -34,101 +34,101 @@ import org.onap.aaf.misc.env.util.Pool; import org.onap.aaf.misc.env.util.Pool.Creator; public abstract class AbsOTafLur { - protected static final String ERROR_GETTING_TOKEN_CLIENT = "Error getting TokenClient"; - protected static final String REQUIRED_FOR_OAUTH2 = " is required for OAuth Access"; + protected static final String ERROR_GETTING_TOKEN_CLIENT = "Error getting TokenClient"; + protected static final String REQUIRED_FOR_OAUTH2 = " is required for OAuth Access"; - protected final TokenMgr tkMgr; - protected final PropAccess access; - protected final String client_id; - protected static Pool tokenClientPool; - - protected AbsOTafLur(final PropAccess access, final String token_url, final String introspect_url) throws CadiException { - this.access = access; - String ci; - if((ci = access.getProperty(Config.AAF_APPID,null))==null) { - if((ci = access.getProperty(Config.CADI_ALIAS,null))==null) { - throw new CadiException(Config.AAF_APPID + REQUIRED_FOR_OAUTH2); - } - } - client_id = ci; + protected final TokenMgr tkMgr; + protected final PropAccess access; + protected final String client_id; + protected static Pool tokenClientPool; + + protected AbsOTafLur(final PropAccess access, final String token_url, final String introspect_url) throws CadiException { + this.access = access; + String ci; + if((ci = access.getProperty(Config.AAF_APPID,null))==null) { + if((ci = access.getProperty(Config.CADI_ALIAS,null))==null) { + throw new CadiException(Config.AAF_APPID + REQUIRED_FOR_OAUTH2); + } + } + client_id = ci; - synchronized(access) { - if(tokenClientPool==null) { - tokenClientPool = new Pool(new TCCreator(access)); - } - try { - tkMgr = TokenMgr.getInstance(access, token_url, introspect_url); - } catch (APIException e) { - throw new CadiException("Unable to create TokenManager",e); - } - } - } + synchronized(access) { + if(tokenClientPool==null) { + tokenClientPool = new Pool(new TCCreator(access)); + } + try { + tkMgr = TokenMgr.getInstance(access, token_url, introspect_url); + } catch (APIException e) { + throw new CadiException("Unable to create TokenManager",e); + } + } + } - private class TCCreator implements Creator { - private TokenClientFactory tcf; - private final int timeout; - private final String url,enc_secret; - - public TCCreator(PropAccess access) throws CadiException { - try { - tcf = TokenClientFactory.instance(access); - } catch (APIException | GeneralSecurityException | IOException e1) { - throw new CadiException(e1); - } - - if((url = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null))==null) { - throw new CadiException(Config.AAF_OAUTH2_TOKEN_URL + REQUIRED_FOR_OAUTH2); - } - - try { - timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); - } catch (NumberFormatException e) { - throw new CadiException("Bad format for " + Config.AAF_CONN_TIMEOUT, e); - } - if((enc_secret= access.getProperty(Config.AAF_APPPASS,null))==null) { - throw new CadiException(Config.AAF_APPPASS + REQUIRED_FOR_OAUTH2); - } - } - - @Override - public TokenClient create() throws APIException { - try { - TokenClient tc = tcf.newClient(url, timeout); - tc.client_creds(client_id, access.decrypt(enc_secret, true)); - return tc; - } catch (CadiException | LocatorException | IOException e) { - throw new APIException(e); - } - } + private class TCCreator implements Creator { + private TokenClientFactory tcf; + private final int timeout; + private final String url,enc_secret; + + public TCCreator(PropAccess access) throws CadiException { + try { + tcf = TokenClientFactory.instance(access); + } catch (APIException | GeneralSecurityException | IOException e1) { + throw new CadiException(e1); + } + + if((url = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null))==null) { + throw new CadiException(Config.AAF_OAUTH2_TOKEN_URL + REQUIRED_FOR_OAUTH2); + } + + try { + timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); + } catch (NumberFormatException e) { + throw new CadiException("Bad format for " + Config.AAF_CONN_TIMEOUT, e); + } + if((enc_secret= access.getProperty(Config.AAF_APPPASS,null))==null) { + throw new CadiException(Config.AAF_APPPASS + REQUIRED_FOR_OAUTH2); + } + } + + @Override + public TokenClient create() throws APIException { + try { + TokenClient tc = tcf.newClient(url, timeout); + tc.client_creds(client_id, access.decrypt(enc_secret, true)); + return tc; + } catch (CadiException | LocatorException | IOException e) { + throw new APIException(e); + } + } - @Override - public void destroy(TokenClient t) { - } + @Override + public void destroy(TokenClient t) { + } - @Override - public boolean isValid(TokenClient t) { - return t!=null && t.client_id()!=null; - } + @Override + public boolean isValid(TokenClient t) { + return t!=null && t.client_id()!=null; + } - @Override - public void reuse(TokenClient t) { - } - }; + @Override + public void reuse(TokenClient t) { + } + }; - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#destroy() - */ - public void destroy() { - tkMgr.close(); - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#clear(java.security.Principal, java.lang.StringBuilder) - */ - public void clear(Principal p, StringBuilder report) { - tkMgr.clear(p, report); - } - + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#destroy() + */ + public void destroy() { + tkMgr.close(); + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#clear(java.security.Principal, java.lang.StringBuilder) + */ + public void clear(Principal p, StringBuilder report) { + tkMgr.clear(p, report); + } + - + } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java index dc6fe390..100b58ec 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java @@ -36,69 +36,69 @@ import org.onap.aaf.cadi.util.FQI; import org.onap.aaf.misc.env.APIException; public class HRenewingTokenSS extends HAuthorizationHeader { - private TokenClientFactory tcf; - private final TokenClient tc; - private final String[] scopes; - private final String tokenURL; - - public HRenewingTokenSS(final PropAccess access, final String tokenURL, final String ... nss) throws CadiException, IOException, GeneralSecurityException { - this(access,SecurityInfoC.instance(access, HttpURLConnection.class),tokenURL,nss); - } - - public HRenewingTokenSS(final PropAccess access, final SecurityInfoC si, final String tokenURL, final String ... nss) throws CadiException, IOException, GeneralSecurityException { - super(si,null,null/*Note: HeadValue overloaded */); - this.tokenURL = tokenURL; - try { - tcf = TokenClientFactory.instance(access); - tc = tcf.newClient(tokenURL); - tc.client_creds(access); - setUser(tc.client_id()); - String defaultNS = FQI.reverseDomain(tc.client_id()); - if(nss.length>0) { - boolean hasDefault = false; - for(String ns : nss) { - if(ns.equals(defaultNS)) { - hasDefault = true; - } - } - if(hasDefault) { - scopes=nss; - } else { - String[] nssPlus = new String[nss.length+1]; - nssPlus[0]=defaultNS; - System.arraycopy(nss, 0, nssPlus, 1, nss.length); - scopes = nssPlus; - } - } else { - scopes = new String[] {defaultNS}; - } + private TokenClientFactory tcf; + private final TokenClient tc; + private final String[] scopes; + private final String tokenURL; + + public HRenewingTokenSS(final PropAccess access, final String tokenURL, final String ... nss) throws CadiException, IOException, GeneralSecurityException { + this(access,SecurityInfoC.instance(access, HttpURLConnection.class),tokenURL,nss); + } + + public HRenewingTokenSS(final PropAccess access, final SecurityInfoC si, final String tokenURL, final String ... nss) throws CadiException, IOException, GeneralSecurityException { + super(si,null,null/*Note: HeadValue overloaded */); + this.tokenURL = tokenURL; + try { + tcf = TokenClientFactory.instance(access); + tc = tcf.newClient(tokenURL); + tc.client_creds(access); + setUser(tc.client_id()); + String defaultNS = FQI.reverseDomain(tc.client_id()); + if(nss.length>0) { + boolean hasDefault = false; + for(String ns : nss) { + if(ns.equals(defaultNS)) { + hasDefault = true; + } + } + if(hasDefault) { + scopes=nss; + } else { + String[] nssPlus = new String[nss.length+1]; + nssPlus[0]=defaultNS; + System.arraycopy(nss, 0, nssPlus, 1, nss.length); + scopes = nssPlus; + } + } else { + scopes = new String[] {defaultNS}; + } - } catch (GeneralSecurityException | IOException | LocatorException | APIException e) { - throw new CadiException(e); - } - } + } catch (GeneralSecurityException | IOException | LocatorException | APIException e) { + throw new CadiException(e); + } + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.client.AbsAuthentication#headValue() - */ - @Override - protected String headValue() throws IOException { - Result token; - try { - token = tc.getToken(Kind.OAUTH,scopes); - if(token.isOK()) { - return "Bearer " + token.value.getAccessToken(); - } else { - throw new IOException("Token cannot be obtained: " + token.code + '-' + token.error); - } - } catch (IOException e) { - throw e; - } catch (LocatorException | CadiException | APIException e) { - throw new IOException(e); - } - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.client.AbsAuthentication#headValue() + */ + @Override + protected String headValue() throws IOException { + Result token; + try { + token = tc.getToken(Kind.OAUTH,scopes); + if(token.isOK()) { + return "Bearer " + token.value.getAccessToken(); + } else { + throw new IOException("Token cannot be obtained: " + token.code + '-' + token.error); + } + } catch (IOException e) { + throw e; + } catch (LocatorException | CadiException | APIException e) { + throw new IOException(e); + } + } - public String tokenURL() { - return tokenURL; - } + public String tokenURL() { + return tokenURL; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java index 3d5f7d9a..b4b4b1e3 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java @@ -41,42 +41,42 @@ import org.onap.aaf.cadi.taf.TafResp.RESP; import org.onap.aaf.misc.env.APIException; public class OAuth2HttpTaf implements HttpTaf { - final private Access access; - final private TokenMgr tmgr; + final private Access access; + final private TokenMgr tmgr; - public OAuth2HttpTaf(final Access access, final TokenMgr tmgr) { - this.tmgr = tmgr; - this.access = access; - } - - @Override - public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { - String authz = req.getHeader("Authorization"); - if(authz != null && authz.length()>7 && authz.startsWith("Bearer ")) { - if(!req.isSecure()) { - access.log(Level.WARN,"WARNING! OAuth has been used over an insecure channel"); - } - try { - String tkn = authz.substring(7); - Result rp = tmgr.toPrincipal(tkn,Hash.hashSHA256(tkn.getBytes())); - if(rp.isOK()) { - return new OAuth2HttpTafResp(access,rp.value,rp.value.getName()+" authenticated by Bearer Token",RESP.IS_AUTHENTICATED,resp,false); - } else { - return new OAuth2HttpTafResp(access,null,rp.error,RESP.FAIL,resp,true); - } - } catch (APIException | CadiException | LocatorException e) { - return new OAuth2HttpTafResp(access,null,"Bearer Token invalid",RESP.FAIL,resp,true); - } catch (NoSuchAlgorithmException e) { - return new OAuth2HttpTafResp(access,null,"Security Algorithm not available",RESP.FAIL,resp,true); - } - } - return new OAuth2HttpTafResp(access,null,"No OAuth2 ",RESP.TRY_ANOTHER_TAF,resp,true); - } + public OAuth2HttpTaf(final Access access, final TokenMgr tmgr) { + this.tmgr = tmgr; + this.access = access; + } + + @Override + public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { + String authz = req.getHeader("Authorization"); + if(authz != null && authz.length()>7 && authz.startsWith("Bearer ")) { + if(!req.isSecure()) { + access.log(Level.WARN,"WARNING! OAuth has been used over an insecure channel"); + } + try { + String tkn = authz.substring(7); + Result rp = tmgr.toPrincipal(tkn,Hash.hashSHA256(tkn.getBytes())); + if(rp.isOK()) { + return new OAuth2HttpTafResp(access,rp.value,rp.value.getName()+" authenticated by Bearer Token",RESP.IS_AUTHENTICATED,resp,false); + } else { + return new OAuth2HttpTafResp(access,null,rp.error,RESP.FAIL,resp,true); + } + } catch (APIException | CadiException | LocatorException e) { + return new OAuth2HttpTafResp(access,null,"Bearer Token invalid",RESP.FAIL,resp,true); + } catch (NoSuchAlgorithmException e) { + return new OAuth2HttpTafResp(access,null,"Security Algorithm not available",RESP.FAIL,resp,true); + } + } + return new OAuth2HttpTafResp(access,null,"No OAuth2 ",RESP.TRY_ANOTHER_TAF,resp,true); + } - @Override - public Resp revalidate(CachedPrincipal prin,Object state) { - //TODO!!!! - return null; - } + @Override + public Resp revalidate(CachedPrincipal prin,Object state) { + //TODO!!!! + return null; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTafResp.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTafResp.java index 9292e75e..4fa58700 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTafResp.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTafResp.java @@ -31,36 +31,36 @@ import org.onap.aaf.cadi.taf.AbsTafResp; import org.onap.aaf.cadi.taf.TafResp; public class OAuth2HttpTafResp extends AbsTafResp implements TafResp { - private static final String tafName = OAuth2HttpTaf.class.getSimpleName(); - private HttpServletResponse httpResp; - private RESP status; - private final boolean wasFailed; - - public OAuth2HttpTafResp(Access access, OAuth2Principal principal, String desc, RESP status, HttpServletResponse resp, boolean wasFailed) { - super(access,tafName, principal, desc); - httpResp = resp; - this.status = status; - this.wasFailed = wasFailed; - } + private static final String tafName = OAuth2HttpTaf.class.getSimpleName(); + private HttpServletResponse httpResp; + private RESP status; + private final boolean wasFailed; + + public OAuth2HttpTafResp(Access access, OAuth2Principal principal, String desc, RESP status, HttpServletResponse resp, boolean wasFailed) { + super(access,tafName, principal, desc); + httpResp = resp; + this.status = status; + this.wasFailed = wasFailed; + } - public OAuth2HttpTafResp(Access access, TrustPrincipal principal, String desc, RESP status,HttpServletResponse resp) { - super(access,tafName, principal, desc); - httpResp = resp; - this.status = status; - wasFailed = true; // if Trust Principal added, must be good - } + public OAuth2HttpTafResp(Access access, TrustPrincipal principal, String desc, RESP status,HttpServletResponse resp) { + super(access,tafName, principal, desc); + httpResp = resp; + this.status = status; + wasFailed = true; // if Trust Principal added, must be good + } - public RESP authenticate() throws IOException { - httpResp.setStatus(401); // Unauthorized - return RESP.HTTP_REDIRECT_INVOKED; - } + public RESP authenticate() throws IOException { + httpResp.setStatus(401); // Unauthorized + return RESP.HTTP_REDIRECT_INVOKED; + } - public RESP isAuthenticated() { - return status; - } + public RESP isAuthenticated() { + return status; + } - public boolean isFailedAttempt() { - return wasFailed; - } + public boolean isFailedAttempt() { + return wasFailed; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java index b3fe2947..5f4009d5 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java @@ -32,79 +32,79 @@ import org.onap.aaf.cadi.principal.BearerPrincipal; import org.onap.aaf.misc.env.util.Split; public class OAuth2Lur implements Lur { - private TokenMgr tm; + private TokenMgr tm; - public OAuth2Lur(TokenMgr tm) { - this.tm = tm; - } - - @Override - public Permission createPerm(String p) { - String[] params = Split.split('|', p); - switch(params.length) { - case 3: - return new AAFPermission(null,params[0],params[1],params[2]); - case 4: - return new AAFPermission(params[0],params[1],params[2],params[3]); - default: - return new LocalPermission(p); - } - } + public OAuth2Lur(TokenMgr tm) { + this.tm = tm; + } + + @Override + public Permission createPerm(String p) { + String[] params = Split.split('|', p); + switch(params.length) { + case 3: + return new AAFPermission(null,params[0],params[1],params[2]); + case 4: + return new AAFPermission(params[0],params[1],params[2],params[3]); + default: + return new LocalPermission(p); + } + } - @Override - public boolean fish(Principal bait, Permission ... pond) { - boolean rv = false; - - if(bait instanceof OAuth2Principal) { - OAuth2Principal oap = (OAuth2Principal)bait; - for (Permission p : pond ) { - AAFPermission apond = (AAFPermission)p; - - TokenPerm tp = oap.tokenPerm(); - if(tp==null) { - } else { - for(Permission perm : tp.perms()) { - if(perm.match(apond)) { - return true; - } - } - } - } - } - return rv; - } + @Override + public boolean fish(Principal bait, Permission ... pond) { + boolean rv = false; + + if(bait instanceof OAuth2Principal) { + OAuth2Principal oap = (OAuth2Principal)bait; + for (Permission p : pond ) { + AAFPermission apond = (AAFPermission)p; + + TokenPerm tp = oap.tokenPerm(); + if(tp==null) { + } else { + for(Permission perm : tp.perms()) { + if(perm.match(apond)) { + return true; + } + } + } + } + } + return rv; + } - @Override - public void fishAll(Principal bait, List permissions) { - OAuth2Principal oap = (OAuth2Principal)bait; - TokenPerm tp = oap.tokenPerm(); - if(tp!=null) { - for(AAFPermission p : tp.perms()) { - permissions.add(p); - } - } - } + @Override + public void fishAll(Principal bait, List permissions) { + OAuth2Principal oap = (OAuth2Principal)bait; + TokenPerm tp = oap.tokenPerm(); + if(tp!=null) { + for(AAFPermission p : tp.perms()) { + permissions.add(p); + } + } + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } - @Override - public boolean handlesExclusively(Permission ... pond) { - return false; - } + @Override + public boolean handlesExclusively(Permission ... pond) { + return false; + } - @Override - public boolean handles(Principal p) { - if(p!=null && p instanceof BearerPrincipal) { - return ((BearerPrincipal)p).getBearer()!=null; - } - return false; - } + @Override + public boolean handles(Principal p) { + if(p!=null && p instanceof BearerPrincipal) { + return ((BearerPrincipal)p).getBearer()!=null; + } + return false; + } - @Override - public void clear(Principal p, StringBuilder report) { - tm.clear(p,report); - } + @Override + public void clear(Principal p, StringBuilder report) { + tm.clear(p,report); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Principal.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Principal.java index 90d59635..86475d53 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Principal.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Principal.java @@ -24,31 +24,31 @@ package org.onap.aaf.cadi.oauth; import org.onap.aaf.cadi.principal.TaggedPrincipal; public class OAuth2Principal extends TaggedPrincipal { - private TokenPerm tp; -// private byte[] hash; // hashed cred for disk validation - - public OAuth2Principal(TokenPerm tp, byte[] hash) { - this.tp = tp; -// this.hash = hash; - } - - @Override - public String getName() { - return tp.getUsername(); - } - - public TokenPerm tokenPerm() { - return tp; - } + private TokenPerm tp; +// private byte[] hash; // hashed cred for disk validation + + public OAuth2Principal(TokenPerm tp, byte[] hash) { + this.tp = tp; +// this.hash = hash; + } + + @Override + public String getName() { + return tp.getUsername(); + } + + public TokenPerm tokenPerm() { + return tp; + } - @Override - public String tag() { - return "OAuth"; - } + @Override + public String tag() { + return "OAuth"; + } - @Override - public String personalName() { - return tp.getUsername(); - } - + @Override + public String personalName() { + return tp.getUsername(); + } + } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TimedToken.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TimedToken.java index d4f343f9..38accc7a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TimedToken.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TimedToken.java @@ -42,91 +42,91 @@ import aafoauth.v2_0.Token; */ // Package on purpose public class TimedToken extends Token implements Persistable { - private Persisting cacheable; // no double inheritance... + private Persisting cacheable; // no double inheritance... -// public TimedToken(Token t, byte[] hash) { -// this(t,(System.currentTimeMillis()/1000)+t.getExpiresIn(),hash,null); -// } +// public TimedToken(Token t, byte[] hash) { +// this(t,(System.currentTimeMillis()/1000)+t.getExpiresIn(),hash,null); +// } // - public TimedToken(Persist p, Token t, byte[] hash, Path path){ - this(p,t,t.getExpiresIn()+(System.currentTimeMillis()/1000),hash, path); - } - - public TimedToken(Persist p, Token t, long expires_secsFrom1970, byte[] hash, Path path) { - cacheable = new Persisting(p, t,expires_secsFrom1970, hash, path); - accessToken=t.getAccessToken(); - expiresIn=t.getExpiresIn(); - refreshToken=t.getRefreshToken(); - scope = t.getScope(); - state = t.getState(); - tokenType = t.getTokenType(); - } - - - @Override - public Token get() { - return cacheable.get(); - } - - @Override - public boolean checkSyncTime() { - return cacheable.checkSyncTime(); - } - - @Override - public boolean checkReloadable() { - return cacheable.checkReloadable(); - } - - @Override - public boolean hasBeenTouched() { - return cacheable.hasBeenTouched(); - } - - @Override - public long expires() { - return cacheable.expires(); - } - - @Override - public boolean expired() { - return cacheable.expired(); - } - - @Override - public boolean match(byte[] hashIn) { - return cacheable.match(hashIn); - } - - @Override - public byte[] getHash() { - return cacheable.getHash(); - } - - @Override - public void inc() { - cacheable.inc(); - } - - @Override - public int count() { - return cacheable.count(); - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.oauth.Persistable#clearCount() - */ - @Override - public void clearCount() { - cacheable.clearCount(); - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.persist.Persistable#path() - */ - @Override - public Path path() { - return cacheable.path(); - } + public TimedToken(Persist p, Token t, byte[] hash, Path path){ + this(p,t,t.getExpiresIn()+(System.currentTimeMillis()/1000),hash, path); + } + + public TimedToken(Persist p, Token t, long expires_secsFrom1970, byte[] hash, Path path) { + cacheable = new Persisting(p, t,expires_secsFrom1970, hash, path); + accessToken=t.getAccessToken(); + expiresIn=t.getExpiresIn(); + refreshToken=t.getRefreshToken(); + scope = t.getScope(); + state = t.getState(); + tokenType = t.getTokenType(); + } + + + @Override + public Token get() { + return cacheable.get(); + } + + @Override + public boolean checkSyncTime() { + return cacheable.checkSyncTime(); + } + + @Override + public boolean checkReloadable() { + return cacheable.checkReloadable(); + } + + @Override + public boolean hasBeenTouched() { + return cacheable.hasBeenTouched(); + } + + @Override + public long expires() { + return cacheable.expires(); + } + + @Override + public boolean expired() { + return cacheable.expired(); + } + + @Override + public boolean match(byte[] hashIn) { + return cacheable.match(hashIn); + } + + @Override + public byte[] getHash() { + return cacheable.getHash(); + } + + @Override + public void inc() { + cacheable.inc(); + } + + @Override + public int count() { + return cacheable.count(); + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.oauth.Persistable#clearCount() + */ + @Override + public void clearCount() { + cacheable.clearCount(); + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.persist.Persistable#path() + */ + @Override + public Path path() { + return cacheable.path(); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java index e0d6bf0e..3b4e074a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java @@ -51,446 +51,446 @@ import aafoauth.v2_0.Introspect; import aafoauth.v2_0.Token; public class TokenClient { - private static final String UTF_8 = "UTF-8"; + private static final String UTF_8 = "UTF-8"; - public enum AUTHN_METHOD {client_credentials,password,payload,basic_auth,certificate,refresh_token, none} + public enum AUTHN_METHOD {client_credentials,password,payload,basic_auth,certificate,refresh_token, none} - private final TokenClientFactory factory; - private final AAFCon tkCon; - private static RosettaDF tokenDF; - protected static RosettaDF introspectDF; + private final TokenClientFactory factory; + private final AAFCon tkCon; + private static RosettaDF tokenDF; + protected static RosettaDF introspectDF; - private int timeout; - private String client_id, username; - private byte[] enc_client_secret, enc_password; + private int timeout; + private String client_id, username; + private byte[] enc_client_secret, enc_password; - private GetSetter ss; - private AUTHN_METHOD authn_method; - private byte[] hash; - private final char okind; - private String default_scope; + private GetSetter ss; + private AUTHN_METHOD authn_method; + private byte[] hash; + private final char okind; + private String default_scope; - // Package on Purpose - TokenClient(char okind, final TokenClientFactory tcf, final AAFCon tkCon, final int timeout, AUTHN_METHOD am) throws CadiException, APIException { - this.okind = okind; - factory = tcf; - this.tkCon = tkCon; - this.timeout = timeout; - ss = null; - authn_method = am; - synchronized(tcf) { - if(introspectDF==null) { - tokenDF = tkCon.env().newDataFactory(Token.class); - introspectDF = tkCon.env().newDataFactory(Introspect.class); - } - } + // Package on Purpose + TokenClient(char okind, final TokenClientFactory tcf, final AAFCon tkCon, final int timeout, AUTHN_METHOD am) throws CadiException, APIException { + this.okind = okind; + factory = tcf; + this.tkCon = tkCon; + this.timeout = timeout; + ss = null; + authn_method = am; + synchronized(tcf) { + if(introspectDF==null) { + tokenDF = tkCon.env().newDataFactory(Token.class); + introspectDF = tkCon.env().newDataFactory(Introspect.class); + } + } - } + } - public void client_id(String client_id) { - this.client_id = client_id; - default_scope = FQI.reverseDomain(client_id); - } - - public String client_id() { - return client_id; - } - - /** - * This scope based on client_id... the App configured for call - * @return - */ - public String defaultScope() { - return default_scope; - } + public void client_id(String client_id) { + this.client_id = client_id; + default_scope = FQI.reverseDomain(client_id); + } + + public String client_id() { + return client_id; + } + + /** + * This scope based on client_id... the App configured for call + * @return + */ + public String defaultScope() { + return default_scope; + } - public void client_creds(Access access) throws CadiException { - if(okind=='A') { - String alias = access.getProperty(Config.CADI_ALIAS, null); - if(alias == null) { - client_creds(access.getProperty(Config.AAF_APPID, null),access.getProperty(Config.AAF_APPPASS, null)); - } else { - client_creds(alias,null); - } - } else { - client_creds(access.getProperty(Config.AAF_ALT_CLIENT_ID, null),access.getProperty(Config.AAF_ALT_CLIENT_SECRET, null)); - } - } + public void client_creds(Access access) throws CadiException { + if(okind=='A') { + String alias = access.getProperty(Config.CADI_ALIAS, null); + if(alias == null) { + client_creds(access.getProperty(Config.AAF_APPID, null),access.getProperty(Config.AAF_APPPASS, null)); + } else { + client_creds(alias,null); + } + } else { + client_creds(access.getProperty(Config.AAF_ALT_CLIENT_ID, null),access.getProperty(Config.AAF_ALT_CLIENT_SECRET, null)); + } + } - /** - * Note: OAuth2 provides for normal Authentication parameters when getting tokens. Basic Auth is one such valid - * way to get Credentials. However, support is up to the OAuth2 Implementation - * - * This method is for setting an App's creds (client) to another App. - * - * @param client_id - * @param client_secret - * @throws IOException - */ - public void client_creds(final String client_id, final String client_secret) throws CadiException { - if(client_id==null) { - throw new CadiException("client_creds:client_id is null"); - } - this.client_id = client_id; - default_scope = FQI.reverseDomain(client_id); + /** + * Note: OAuth2 provides for normal Authentication parameters when getting tokens. Basic Auth is one such valid + * way to get Credentials. However, support is up to the OAuth2 Implementation + * + * This method is for setting an App's creds (client) to another App. + * + * @param client_id + * @param client_secret + * @throws IOException + */ + public void client_creds(final String client_id, final String client_secret) throws CadiException { + if(client_id==null) { + throw new CadiException("client_creds:client_id is null"); + } + this.client_id = client_id; + default_scope = FQI.reverseDomain(client_id); - if(client_secret!=null) { - try { - if(client_secret.startsWith("enc:")) { - final String temp = factory.access.decrypt(client_secret, false); // this is a more powerful, but non-thread-safe encryption - hash = Hash.hashSHA256(temp.getBytes()); - this.enc_client_secret = factory.symm.encode(temp.getBytes()); - ss = new GetSetter() { - @Override - public SecuritySetter get(AAFCon con) throws CadiException { - return con.basicAuth(client_id, temp);// Base class encrypts password - } - }; - } else { - byte[] temp = client_secret.getBytes(); - hash = Hash.hashSHA256(temp); - this.enc_client_secret = factory.symm.encode(temp); - ss = new GetSetter() { - @Override - public SecuritySetter get(AAFCon con) throws CadiException { - return con.basicAuth(client_id, client_secret);// Base class encrypts password - } - }; - } - authn_method = AUTHN_METHOD.client_credentials; - } catch(IOException | NoSuchAlgorithmException e) { - throw new CadiException(e); - } - } else { - ss = new GetSetter() { - @Override - public SecuritySetter get(AAFCon con) throws CadiException { - try { - return con.x509Alias(client_id);// no password, assume Cert - } catch (APIException e) { - throw new CadiException(e); - } - } - }; - authn_method = AUTHN_METHOD.client_credentials; - } - } - - public void username(String username) { - this.username = username; - } + if(client_secret!=null) { + try { + if(client_secret.startsWith("enc:")) { + final String temp = factory.access.decrypt(client_secret, false); // this is a more powerful, but non-thread-safe encryption + hash = Hash.hashSHA256(temp.getBytes()); + this.enc_client_secret = factory.symm.encode(temp.getBytes()); + ss = new GetSetter() { + @Override + public SecuritySetter get(AAFCon con) throws CadiException { + return con.basicAuth(client_id, temp);// Base class encrypts password + } + }; + } else { + byte[] temp = client_secret.getBytes(); + hash = Hash.hashSHA256(temp); + this.enc_client_secret = factory.symm.encode(temp); + ss = new GetSetter() { + @Override + public SecuritySetter get(AAFCon con) throws CadiException { + return con.basicAuth(client_id, client_secret);// Base class encrypts password + } + }; + } + authn_method = AUTHN_METHOD.client_credentials; + } catch(IOException | NoSuchAlgorithmException e) { + throw new CadiException(e); + } + } else { + ss = new GetSetter() { + @Override + public SecuritySetter get(AAFCon con) throws CadiException { + try { + return con.x509Alias(client_id);// no password, assume Cert + } catch (APIException e) { + throw new CadiException(e); + } + } + }; + authn_method = AUTHN_METHOD.client_credentials; + } + } + + public void username(String username) { + this.username = username; + } - /** - * Note: OAuth2 provides for normal Authentication parameters when getting tokens. Basic Auth is one such valid - * way to get Credentials. However, support is up to the OAuth2 Implementation - * - * This method is for setting the End-User's Creds - * - * @param client_id - * @param client_secret - * @throws IOException - */ - public void password(final String user, final String password) throws CadiException { - this.username = user; - if(password!=null) { - try { - if(password.startsWith("enc:")) { - final String temp = factory.access.decrypt(password, false); // this is a more powerful, but non-thread-safe encryption - hash = Hash.hashSHA256(temp.getBytes()); - this.enc_password = factory.symm.encode(temp.getBytes()); - ss = new GetSetter() { - @Override - public SecuritySetter get(AAFCon con) throws CadiException { - return con.basicAuth(user, temp);// Base class encrypts password - } - }; - } else { - byte[] temp = password.getBytes(); - hash = Hash.hashSHA256(temp); - this.enc_password = factory.symm.encode(temp); - ss = new GetSetter() { - @Override - public SecuritySetter get(AAFCon con) throws CadiException { - return con.basicAuth(user, password);// Base class encrypts password - } - }; - } - authn_method = AUTHN_METHOD.password; - } catch (IOException | NoSuchAlgorithmException e) { - throw new CadiException(e); - } - } - } - - public void clearEndUser() { - username = null; - enc_password = null; - if(client_id!=null && enc_client_secret!=null) { - authn_method = AUTHN_METHOD.client_credentials; - } else { - authn_method = AUTHN_METHOD.password; - } - } + /** + * Note: OAuth2 provides for normal Authentication parameters when getting tokens. Basic Auth is one such valid + * way to get Credentials. However, support is up to the OAuth2 Implementation + * + * This method is for setting the End-User's Creds + * + * @param client_id + * @param client_secret + * @throws IOException + */ + public void password(final String user, final String password) throws CadiException { + this.username = user; + if(password!=null) { + try { + if(password.startsWith("enc:")) { + final String temp = factory.access.decrypt(password, false); // this is a more powerful, but non-thread-safe encryption + hash = Hash.hashSHA256(temp.getBytes()); + this.enc_password = factory.symm.encode(temp.getBytes()); + ss = new GetSetter() { + @Override + public SecuritySetter get(AAFCon con) throws CadiException { + return con.basicAuth(user, temp);// Base class encrypts password + } + }; + } else { + byte[] temp = password.getBytes(); + hash = Hash.hashSHA256(temp); + this.enc_password = factory.symm.encode(temp); + ss = new GetSetter() { + @Override + public SecuritySetter get(AAFCon con) throws CadiException { + return con.basicAuth(user, password);// Base class encrypts password + } + }; + } + authn_method = AUTHN_METHOD.password; + } catch (IOException | NoSuchAlgorithmException e) { + throw new CadiException(e); + } + } + } + + public void clearEndUser() { + username = null; + enc_password = null; + if(client_id!=null && enc_client_secret!=null) { + authn_method = AUTHN_METHOD.client_credentials; + } else { + authn_method = AUTHN_METHOD.password; + } + } - public Result getToken(final String ... scopes) throws LocatorException, CadiException, APIException { - return getToken(Kind.OAUTH,scopes); - } + public Result getToken(final String ... scopes) throws LocatorException, CadiException, APIException { + return getToken(Kind.OAUTH,scopes); + } - public void clearToken(final String ... scopes) throws CadiException { - clearToken(Kind.OAUTH,scopes); - } + public void clearToken(final String ... scopes) throws CadiException { + clearToken(Kind.OAUTH,scopes); + } - public void clearToken(final char kind, final String ... scopes) throws CadiException { - final String scope = addScope(scopes); - char c; - if(kind==Kind.OAUTH) { - c = okind; - } else { - c = kind; - } - final String key = TokenClientFactory.getKey(c,client_id,username,hash,scope); - factory.delete(key); - } - /** - * Get AuthToken - * @throws APIException - * @throws CadiException - * @throws LocatorException - */ - public Result getToken(final char kind, final String ... scopes) throws LocatorException, CadiException, APIException { - final String scope = addScope(scopes); - char c; - if(kind==Kind.OAUTH) { - c = okind; - } else { - c = kind; - } - final String key = TokenClientFactory.getKey(c,client_id,username,hash,scope); - if(ss==null) { - throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); - } - - Result rtt = factory.get(key,hash,new Loader() { - @Override - public Result load(final String key) throws APIException, CadiException, LocatorException { - final List params = new ArrayList<>(); - params.add(scope); - addSecurity(params,authn_method); - - final String paramsa[] = new String[params.size()]; - params.toArray(paramsa); - Result rt = tkCon.best(new Retryable>() { - @Override - public Result code(Rcli client) throws CadiException, ConnectException, APIException { - // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test - Future f = client.postForm(null,tokenDF,paramsa); - if(f.get(timeout)) { - return Result.ok(f.code(),f.value); - } else { - return Result.err(f.code(), f.body()); - } - } - }); - - if(rt.isOK()) { - try { - return Result.ok(rt.code,factory.putTimedToken(key,rt.value, hash)); - } catch (IOException e) { - // TODO What to do here? - e.printStackTrace(); - return Result.err(999,e.getMessage()); - } - } else { - return Result.err(rt); - } - } - }); - if(rtt.isOK()) { // not validated for Expired - TimedToken tt = rtt.value; - if(tt.expired()) { - rtt = refreshToken(tt); - if(rtt.isOK()) { - tkCon.access.printf(Level.INFO, "Refreshed token %s to %s",tt.getAccessToken(),rtt.value.getAccessToken()); - return Result.ok(200,rtt.value); - } else { - tkCon.access.printf(Level.INFO, "Expired token %s cannot be renewed %d %s",tt.getAccessToken(),rtt.code,rtt.error); - factory.delete(key); - tt=null; - } - } else { - return Result.ok(200,tt); - } - } else { - Result.err(rtt); - } - return Result.err(404,"Not Found"); - } - - public Result refreshToken(Token token) throws APIException, LocatorException, CadiException { - if(ss==null) { - throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); - } - final List params = new ArrayList<>(); - params.add("refresh_token="+token.getRefreshToken()); - addSecurity(params,AUTHN_METHOD.refresh_token); - final String scope="scope="+token.getScope().replace(' ', '+'); - params.add(scope); - - final String paramsa[] = new String[params.size()]; - params.toArray(paramsa); - Result rt = tkCon.best(new Retryable>() { - @Override - public Result code(Rcli client) throws CadiException, ConnectException, APIException { - // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test - Future f = client.postForm(null,tokenDF,paramsa); - if(f.get(timeout)) { - return Result.ok(f.code(),f.value); - } else { - return Result.err(f.code(), f.body()); - } - } - }); - String key = TokenClientFactory.getKey(okind,client_id, username, hash, scope); - if(rt.isOK()) { - try { - return Result.ok(200,factory.putTimedToken(key, rt.value, hash)); - } catch (IOException e) { - //TODO what to do here? - return Result.err(999, e.getMessage()); - } - } else if(rt.code==404) { - factory.deleteFromDisk(key); - } - return Result.err(rt); - } + public void clearToken(final char kind, final String ... scopes) throws CadiException { + final String scope = addScope(scopes); + char c; + if(kind==Kind.OAUTH) { + c = okind; + } else { + c = kind; + } + final String key = TokenClientFactory.getKey(c,client_id,username,hash,scope); + factory.delete(key); + } + /** + * Get AuthToken + * @throws APIException + * @throws CadiException + * @throws LocatorException + */ + public Result getToken(final char kind, final String ... scopes) throws LocatorException, CadiException, APIException { + final String scope = addScope(scopes); + char c; + if(kind==Kind.OAUTH) { + c = okind; + } else { + c = kind; + } + final String key = TokenClientFactory.getKey(c,client_id,username,hash,scope); + if(ss==null) { + throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); + } + + Result rtt = factory.get(key,hash,new Loader() { + @Override + public Result load(final String key) throws APIException, CadiException, LocatorException { + final List params = new ArrayList<>(); + params.add(scope); + addSecurity(params,authn_method); + + final String paramsa[] = new String[params.size()]; + params.toArray(paramsa); + Result rt = tkCon.best(new Retryable>() { + @Override + public Result code(Rcli client) throws CadiException, ConnectException, APIException { + // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test + Future f = client.postForm(null,tokenDF,paramsa); + if(f.get(timeout)) { + return Result.ok(f.code(),f.value); + } else { + return Result.err(f.code(), f.body()); + } + } + }); + + if(rt.isOK()) { + try { + return Result.ok(rt.code,factory.putTimedToken(key,rt.value, hash)); + } catch (IOException e) { + // TODO What to do here? + e.printStackTrace(); + return Result.err(999,e.getMessage()); + } + } else { + return Result.err(rt); + } + } + }); + if(rtt.isOK()) { // not validated for Expired + TimedToken tt = rtt.value; + if(tt.expired()) { + rtt = refreshToken(tt); + if(rtt.isOK()) { + tkCon.access.printf(Level.INFO, "Refreshed token %s to %s",tt.getAccessToken(),rtt.value.getAccessToken()); + return Result.ok(200,rtt.value); + } else { + tkCon.access.printf(Level.INFO, "Expired token %s cannot be renewed %d %s",tt.getAccessToken(),rtt.code,rtt.error); + factory.delete(key); + tt=null; + } + } else { + return Result.ok(200,tt); + } + } else { + Result.err(rtt); + } + return Result.err(404,"Not Found"); + } + + public Result refreshToken(Token token) throws APIException, LocatorException, CadiException { + if(ss==null) { + throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); + } + final List params = new ArrayList<>(); + params.add("refresh_token="+token.getRefreshToken()); + addSecurity(params,AUTHN_METHOD.refresh_token); + final String scope="scope="+token.getScope().replace(' ', '+'); + params.add(scope); + + final String paramsa[] = new String[params.size()]; + params.toArray(paramsa); + Result rt = tkCon.best(new Retryable>() { + @Override + public Result code(Rcli client) throws CadiException, ConnectException, APIException { + // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test + Future f = client.postForm(null,tokenDF,paramsa); + if(f.get(timeout)) { + return Result.ok(f.code(),f.value); + } else { + return Result.err(f.code(), f.body()); + } + } + }); + String key = TokenClientFactory.getKey(okind,client_id, username, hash, scope); + if(rt.isOK()) { + try { + return Result.ok(200,factory.putTimedToken(key, rt.value, hash)); + } catch (IOException e) { + //TODO what to do here? + return Result.err(999, e.getMessage()); + } + } else if(rt.code==404) { + factory.deleteFromDisk(key); + } + return Result.err(rt); + } - public Result introspect(final String token) throws APIException, LocatorException, CadiException { - if(ss==null) { - throw new APIException("client_creds(...) must be set before introspecting Access Tokens"); - } + public Result introspect(final String token) throws APIException, LocatorException, CadiException { + if(ss==null) { + throw new APIException("client_creds(...) must be set before introspecting Access Tokens"); + } - return tkCon.best(new Retryable>() { - @Override - public Result code(Rcli client) throws CadiException, ConnectException, APIException { - final List params = new ArrayList<>(); - params.add("token="+token); - addSecurity(params,AUTHN_METHOD.client_credentials); - final String paramsa[] = new String[params.size()]; - params.toArray(paramsa); - // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test - Future f = client.postForm(null,introspectDF,paramsa); - if(f.get(timeout)) { - return Result.ok(f.code(),f.value); - } else { - return Result.err(f.code(), f.body()); - } - } - } - ); - } - - private String addScope(String[] scopes) { - String rv = null; - StringBuilder scope=null; - boolean first = true; - for(String s : scopes) { - if(first) { - scope = new StringBuilder(); - scope.append("scope="); - first=false; - } else { - scope.append('+'); - } - scope.append(s); - } - if(scope!=null) { - rv=scope.toString(); - } - return rv; - } + return tkCon.best(new Retryable>() { + @Override + public Result code(Rcli client) throws CadiException, ConnectException, APIException { + final List params = new ArrayList<>(); + params.add("token="+token); + addSecurity(params,AUTHN_METHOD.client_credentials); + final String paramsa[] = new String[params.size()]; + params.toArray(paramsa); + // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test + Future f = client.postForm(null,introspectDF,paramsa); + if(f.get(timeout)) { + return Result.ok(f.code(),f.value); + } else { + return Result.err(f.code(), f.body()); + } + } + } + ); + } + + private String addScope(String[] scopes) { + String rv = null; + StringBuilder scope=null; + boolean first = true; + for(String s : scopes) { + if(first) { + scope = new StringBuilder(); + scope.append("scope="); + first=false; + } else { + scope.append('+'); + } + scope.append(s); + } + if(scope!=null) { + rv=scope.toString(); + } + return rv; + } - private void addSecurity(List params, AUTHN_METHOD authn) throws APIException { - // Set GrantType... different than Credentials - switch(authn) { - case client_credentials: - params.add("grant_type=client_credentials"); - break; - case password: - params.add("grant_type=password"); - break; - case refresh_token: - params.add("grant_type=refresh_token"); - break; - case none: - break; - default: - // Nothing to do - break; - } - - // Set Credentials appropriate - switch(authn_method) { - case client_credentials: - if(client_id!=null) { - params.add("client_id="+client_id); - } - - if(enc_client_secret!=null) { - try { - params.add("client_secret="+URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); - } catch (IOException e) { - throw new APIException("Error Decrypting Password",e); - } - } - - if(username!=null) { - params.add("username="+username); - } + private void addSecurity(List params, AUTHN_METHOD authn) throws APIException { + // Set GrantType... different than Credentials + switch(authn) { + case client_credentials: + params.add("grant_type=client_credentials"); + break; + case password: + params.add("grant_type=password"); + break; + case refresh_token: + params.add("grant_type=refresh_token"); + break; + case none: + break; + default: + // Nothing to do + break; + } + + // Set Credentials appropriate + switch(authn_method) { + case client_credentials: + if(client_id!=null) { + params.add("client_id="+client_id); + } + + if(enc_client_secret!=null) { + try { + params.add("client_secret="+URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); + } catch (IOException e) { + throw new APIException("Error Decrypting Password",e); + } + } + + if(username!=null) { + params.add("username="+username); + } - break; - case refresh_token: - if(client_id!=null) { - params.add("client_id="+client_id); - } - - if(enc_client_secret!=null) { - try { - params.add("client_secret="+URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); - } catch (IOException e) { - throw new APIException("Error Decrypting Password",e); - } - } - break; + break; + case refresh_token: + if(client_id!=null) { + params.add("client_id="+client_id); + } + + if(enc_client_secret!=null) { + try { + params.add("client_secret="+URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); + } catch (IOException e) { + throw new APIException("Error Decrypting Password",e); + } + } + break; - case password: - if(client_id!=null) { - params.add("client_id="+client_id); - } - - if(enc_client_secret!=null) { - try { - params.add("client_secret="+ URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); - } catch (IOException e) { - throw new APIException("Error Decrypting Password",e); - } - } - if(username!=null) { - params.add("username="+username); - } - - if(enc_password!=null) { - try { - params.add("password="+ URLEncoder.encode(new String(factory.symm.decode(enc_password)),UTF_8)); - } catch (IOException e) { - throw new APIException("Error Decrypting Password",e); - } - } - - break; - default: - // Nothing to do - break; - } - } + case password: + if(client_id!=null) { + params.add("client_id="+client_id); + } + + if(enc_client_secret!=null) { + try { + params.add("client_secret="+ URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); + } catch (IOException e) { + throw new APIException("Error Decrypting Password",e); + } + } + if(username!=null) { + params.add("username="+username); + } + + if(enc_password!=null) { + try { + params.add("password="+ URLEncoder.encode(new String(factory.symm.decode(enc_password)),UTF_8)); + } catch (IOException e) { + throw new APIException("Error Decrypting Password",e); + } + } + + break; + default: + // Nothing to do + break; + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java index e235b681..8a7118c7 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java @@ -54,132 +54,132 @@ import org.onap.aaf.misc.rosetta.env.RosettaEnv; import aafoauth.v2_0.Token; public class TokenClientFactory extends Persist { - private static TokenClientFactory instance; - private Map aafcons = new ConcurrentHashMap<>(); - private SecurityInfoC hsi; - // Package on purpose - final Symm symm; + private static TokenClientFactory instance; + private Map aafcons = new ConcurrentHashMap<>(); + private SecurityInfoC hsi; + // Package on purpose + final Symm symm; - private TokenClientFactory(Access pa) throws APIException, GeneralSecurityException, IOException, CadiException { - super(pa, new RosettaEnv(pa.getProperties()),Token.class,"outgoing"); - - if(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null)==null) { - access.getProperties().put(Config.AAF_OAUTH2_TOKEN_URL, Defaults.OAUTH2_TOKEN_URL); // Default to AAF - } - if(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,null)==null) { - access.getProperties().put(Config.AAF_OAUTH2_INTROSPECT_URL, Defaults.OAUTH2_INTROSPECT_URL); // Default to AAF); - } + private TokenClientFactory(Access pa) throws APIException, GeneralSecurityException, IOException, CadiException { + super(pa, new RosettaEnv(pa.getProperties()),Token.class,"outgoing"); + + if(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null)==null) { + access.getProperties().put(Config.AAF_OAUTH2_TOKEN_URL, Defaults.OAUTH2_TOKEN_URL); // Default to AAF + } + if(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,null)==null) { + access.getProperties().put(Config.AAF_OAUTH2_INTROSPECT_URL, Defaults.OAUTH2_INTROSPECT_URL); // Default to AAF); + } - symm = Symm.encrypt.obtain(); - hsi = SecurityInfoC.instance(access, HttpURLConnection.class); - } - - public synchronized static final TokenClientFactory instance(Access access) throws APIException, GeneralSecurityException, IOException, CadiException { - if(instance==null) { - instance = new TokenClientFactory(access); - } - return instance; - } - - /** - * Pickup Timeout from Properties - * - * @param tagOrURL - * @return - * @throws CadiException - * @throws LocatorException - * @throws APIException - */ - public TokenClient newClient(final String tagOrURL) throws CadiException, LocatorException, APIException { - return newClient(tagOrURL,Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF))); - } - - public TokenClient newClient(final String tagOrURL, final int timeout) throws CadiException, LocatorException, APIException { - AAFConHttp ach; - if(tagOrURL==null) { - throw new CadiException("parameter tagOrURL cannot be null."); - } else { - ach = aafcons.get(tagOrURL); - if(ach==null) { - aafcons.put(tagOrURL, ach=new AAFConHttp(access,tagOrURL)); - } - } - char okind; - if( Config.AAF_OAUTH2_TOKEN_URL.equals(tagOrURL) || - Config.AAF_OAUTH2_INTROSPECT_URL.equals(tagOrURL) || - tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL, null)) || - tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL, null)) - ) { - okind = Kind.AAF_OAUTH; - } else { - okind = Kind.OAUTH; - } - TokenClient tci = new TokenClient( - okind, - this, - ach, - timeout, - AUTHN_METHOD.none); - tci.client_creds(access); - return tci; - } - - public TzClient newTzClient(final String locatorURL) throws CadiException, LocatorException { - try { - return new TzHClient(access,hsi,bestLocator(locatorURL)); - } catch (URISyntaxException e) { - throw new LocatorException(e); - } - } + symm = Symm.encrypt.obtain(); + hsi = SecurityInfoC.instance(access, HttpURLConnection.class); + } + + public synchronized static final TokenClientFactory instance(Access access) throws APIException, GeneralSecurityException, IOException, CadiException { + if(instance==null) { + instance = new TokenClientFactory(access); + } + return instance; + } + + /** + * Pickup Timeout from Properties + * + * @param tagOrURL + * @return + * @throws CadiException + * @throws LocatorException + * @throws APIException + */ + public TokenClient newClient(final String tagOrURL) throws CadiException, LocatorException, APIException { + return newClient(tagOrURL,Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF))); + } + + public TokenClient newClient(final String tagOrURL, final int timeout) throws CadiException, LocatorException, APIException { + AAFConHttp ach; + if(tagOrURL==null) { + throw new CadiException("parameter tagOrURL cannot be null."); + } else { + ach = aafcons.get(tagOrURL); + if(ach==null) { + aafcons.put(tagOrURL, ach=new AAFConHttp(access,tagOrURL)); + } + } + char okind; + if( Config.AAF_OAUTH2_TOKEN_URL.equals(tagOrURL) || + Config.AAF_OAUTH2_INTROSPECT_URL.equals(tagOrURL) || + tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL, null)) || + tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL, null)) + ) { + okind = Kind.AAF_OAUTH; + } else { + okind = Kind.OAUTH; + } + TokenClient tci = new TokenClient( + okind, + this, + ach, + timeout, + AUTHN_METHOD.none); + tci.client_creds(access); + return tci; + } + + public TzClient newTzClient(final String locatorURL) throws CadiException, LocatorException { + try { + return new TzHClient(access,hsi,bestLocator(locatorURL)); + } catch (URISyntaxException e) { + throw new LocatorException(e); + } + } - static String getKey(char tokenSource,String client_id, String username, byte[] hash, String scope) throws CadiException { - try { - StringBuilder sb = new StringBuilder(client_id); - sb.append('_'); - if(username!=null) { - sb.append(username); - } - sb.append('_'); - sb.append(tokenSource); - byte[] tohash=scope.getBytes(); - if(hash!=null && hash.length>0) { - byte temp[] = new byte[hash.length+tohash.length]; - System.arraycopy(tohash, 0, temp, 0, tohash.length); - System.arraycopy(hash, 0, temp, tohash.length, hash.length); - tohash = temp; - } - if(scope!=null && scope.length()>0) { - sb.append(Hash.toHexNo0x(Hash.hashSHA256(tohash))); - } - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - throw new CadiException(e); - } - } + static String getKey(char tokenSource,String client_id, String username, byte[] hash, String scope) throws CadiException { + try { + StringBuilder sb = new StringBuilder(client_id); + sb.append('_'); + if(username!=null) { + sb.append(username); + } + sb.append('_'); + sb.append(tokenSource); + byte[] tohash=scope.getBytes(); + if(hash!=null && hash.length>0) { + byte temp[] = new byte[hash.length+tohash.length]; + System.arraycopy(tohash, 0, temp, 0, tohash.length); + System.arraycopy(hash, 0, temp, tohash.length, hash.length); + tohash = temp; + } + if(scope!=null && scope.length()>0) { + sb.append(Hash.toHexNo0x(Hash.hashSHA256(tohash))); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + throw new CadiException(e); + } + } - @Override - protected TimedToken newCacheable(Token t, long expires, byte[] hash, Path path) throws IOException { - return new TimedToken(this,t,expires,hash,path); - } + @Override + protected TimedToken newCacheable(Token t, long expires, byte[] hash, Path path) throws IOException { + return new TimedToken(this,t,expires,hash,path); + } - public TimedToken putTimedToken(String key, Token token, byte[] hash) throws IOException, CadiException { - TimedToken tt = new TimedToken(this,token,token.getExpiresIn()+(System.currentTimeMillis()/1000),hash,getPath(key)); - put(key,tt); - return tt; - } - - private static final Pattern locatePattern = Pattern.compile("https://.*/locate/.*"); - public Locator bestLocator(final String locatorURL ) throws LocatorException, URISyntaxException { - if(locatorURL==null) { - throw new LocatorException("Cannot have a null locatorURL in bestLocator"); - } - if(locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) { - return new AAFLocator(hsi,new URI(locatorURL)); - } else if(locatorURL.indexOf(',')>0) { // multiple URLs is a Property Locator - return new PropertyLocator(locatorURL); - } else { - return new SingleEndpointLocator(locatorURL); - } - // Note: Removed DME2Locator... If DME2 client is needed, use DME2Clients - } + public TimedToken putTimedToken(String key, Token token, byte[] hash) throws IOException, CadiException { + TimedToken tt = new TimedToken(this,token,token.getExpiresIn()+(System.currentTimeMillis()/1000),hash,getPath(key)); + put(key,tt); + return tt; + } + + private static final Pattern locatePattern = Pattern.compile("https://.*/locate/.*"); + public Locator bestLocator(final String locatorURL ) throws LocatorException, URISyntaxException { + if(locatorURL==null) { + throw new LocatorException("Cannot have a null locatorURL in bestLocator"); + } + if(locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) { + return new AAFLocator(hsi,new URI(locatorURL)); + } else if(locatorURL.indexOf(',')>0) { // multiple URLs is a Property Locator + return new PropertyLocator(locatorURL); + } else { + return new SingleEndpointLocator(locatorURL); + } + // Note: Removed DME2Locator... If DME2 client is needed, use DME2Clients + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java index 4e781bfa..147621fc 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java @@ -44,150 +44,150 @@ import aaf.v2_0.Perms; import aafoauth.v2_0.Introspect; public class TokenMgr extends Persist { - protected static Map tpmap = new ConcurrentHashMap<>(); - protected static Map tmmap = new HashMap<>(); // synchronized in getInstance - protected static Map currentToken = new HashMap<>(); // synchronized in getTP - public static RosettaDF permsDF; - public static RosettaDF introspectDF; + protected static Map tpmap = new ConcurrentHashMap<>(); + protected static Map tmmap = new HashMap<>(); // synchronized in getInstance + protected static Map currentToken = new HashMap<>(); // synchronized in getTP + public static RosettaDF permsDF; + public static RosettaDF introspectDF; - private final TokenPermLoader tpLoader; - - private TokenMgr(PropAccess access, String tokenURL, String introspectURL) throws APIException, CadiException { - super(access,new RosettaEnv(access.getProperties()),Introspect.class,"introspect"); - synchronized(access) { - if(permsDF==null) { - permsDF = env.newDataFactory(Perms.class); - introspectDF = env.newDataFactory(Introspect.class); - } - } - if("dbToken".equals(tokenURL) && "dbIntrospect".equals(introspectURL)) { - tpLoader = new TokenPermLoader() { // null Loader - @Override - public Result load(String accessToken, byte[] cred) - throws APIException, CadiException, LocatorException { - return Result.err(404, "DBLoader"); - } - }; - } else { - RemoteTokenPermLoader rtpl = new RemoteTokenPermLoader(tokenURL, introspectURL); // default is remote - String i = access.getProperty(Config.AAF_APPID,null); - String p = access.getProperty(Config.AAF_APPPASS, null); - if(i==null || p==null) { - throw new CadiException(Config.AAF_APPID + " and " + Config.AAF_APPPASS + " must be set to initialize TokenMgr"); - } - rtpl.introCL.client_creds(i,p); - tpLoader = rtpl; - } - } + private final TokenPermLoader tpLoader; + + private TokenMgr(PropAccess access, String tokenURL, String introspectURL) throws APIException, CadiException { + super(access,new RosettaEnv(access.getProperties()),Introspect.class,"introspect"); + synchronized(access) { + if(permsDF==null) { + permsDF = env.newDataFactory(Perms.class); + introspectDF = env.newDataFactory(Introspect.class); + } + } + if("dbToken".equals(tokenURL) && "dbIntrospect".equals(introspectURL)) { + tpLoader = new TokenPermLoader() { // null Loader + @Override + public Result load(String accessToken, byte[] cred) + throws APIException, CadiException, LocatorException { + return Result.err(404, "DBLoader"); + } + }; + } else { + RemoteTokenPermLoader rtpl = new RemoteTokenPermLoader(tokenURL, introspectURL); // default is remote + String i = access.getProperty(Config.AAF_APPID,null); + String p = access.getProperty(Config.AAF_APPPASS, null); + if(i==null || p==null) { + throw new CadiException(Config.AAF_APPID + " and " + Config.AAF_APPPASS + " must be set to initialize TokenMgr"); + } + rtpl.introCL.client_creds(i,p); + tpLoader = rtpl; + } + } - private TokenMgr(PropAccess access, TokenPermLoader tpl) throws APIException, CadiException { - super(access,new RosettaEnv(access.getProperties()),Introspect.class,"incoming"); - synchronized(access) { - if(permsDF==null) { - permsDF = env.newDataFactory(Perms.class); - introspectDF = env.newDataFactory(Introspect.class); - } - } - tpLoader = tpl; - } + private TokenMgr(PropAccess access, TokenPermLoader tpl) throws APIException, CadiException { + super(access,new RosettaEnv(access.getProperties()),Introspect.class,"incoming"); + synchronized(access) { + if(permsDF==null) { + permsDF = env.newDataFactory(Perms.class); + introspectDF = env.newDataFactory(Introspect.class); + } + } + tpLoader = tpl; + } - public static synchronized TokenMgr getInstance(final PropAccess access, final String tokenURL, final String introspectURL) throws APIException, CadiException { - String key; - TokenMgr tm = tmmap.get(key=tokenURL+'/'+introspectURL); - if(tm==null) { - tmmap.put(key, tm=new TokenMgr(access,tokenURL,introspectURL)); - } - return tm; - } - - public Result toPrincipal(final String accessToken, final byte[] hash) throws APIException, CadiException, LocatorException { - Result tp = get(accessToken, hash, new Loader() { - @Override - public Result load(String key) throws APIException, CadiException, LocatorException { - try { - return tpLoader.load(accessToken,hash); - } catch (APIException | LocatorException e) { - throw new CadiException(e); - } - } - }); - if(tp.isOK()) { - return Result.ok(200, new OAuth2Principal(tp.value,hash)); - } else { - return Result.err(tp); - } - } - - public Result get(final String accessToken, final byte[] hash) throws APIException, CadiException, LocatorException { - return get(accessToken,hash,new Loader() { - @Override - public Result load(String key) throws APIException, CadiException, LocatorException { - return tpLoader.load(key,hash); - } - - }); -// return tpLoader.load(accessToken,hash); - } + public static synchronized TokenMgr getInstance(final PropAccess access, final String tokenURL, final String introspectURL) throws APIException, CadiException { + String key; + TokenMgr tm = tmmap.get(key=tokenURL+'/'+introspectURL); + if(tm==null) { + tmmap.put(key, tm=new TokenMgr(access,tokenURL,introspectURL)); + } + return tm; + } + + public Result toPrincipal(final String accessToken, final byte[] hash) throws APIException, CadiException, LocatorException { + Result tp = get(accessToken, hash, new Loader() { + @Override + public Result load(String key) throws APIException, CadiException, LocatorException { + try { + return tpLoader.load(accessToken,hash); + } catch (APIException | LocatorException e) { + throw new CadiException(e); + } + } + }); + if(tp.isOK()) { + return Result.ok(200, new OAuth2Principal(tp.value,hash)); + } else { + return Result.err(tp); + } + } + + public Result get(final String accessToken, final byte[] hash) throws APIException, CadiException, LocatorException { + return get(accessToken,hash,new Loader() { + @Override + public Result load(String key) throws APIException, CadiException, LocatorException { + return tpLoader.load(key,hash); + } + + }); +// return tpLoader.load(accessToken,hash); + } - public interface TokenPermLoader{ - public Result load(final String accessToken, final byte[] cred) throws APIException, CadiException, LocatorException; - } - - private class RemoteTokenPermLoader implements TokenPermLoader { - private TokenClientFactory tcf; - private TokenClient tokenCL, introCL; + public interface TokenPermLoader{ + public Result load(final String accessToken, final byte[] cred) throws APIException, CadiException, LocatorException; + } + + private class RemoteTokenPermLoader implements TokenPermLoader { + private TokenClientFactory tcf; + private TokenClient tokenCL, introCL; - public RemoteTokenPermLoader(final String tokenURL, final String introspectURL) throws APIException, CadiException { - try { - tcf = TokenClientFactory.instance(access); - int timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); - tokenCL = tcf.newClient(tokenURL, - timeout); - if(introspectURL.equals(tokenURL)) { - introCL = tokenCL; - } else { - introCL = tcf.newClient(introspectURL, - timeout); - } + public RemoteTokenPermLoader(final String tokenURL, final String introspectURL) throws APIException, CadiException { + try { + tcf = TokenClientFactory.instance(access); + int timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); + tokenCL = tcf.newClient(tokenURL, + timeout); + if(introspectURL.equals(tokenURL)) { + introCL = tokenCL; + } else { + introCL = tcf.newClient(introspectURL, + timeout); + } - } catch (GeneralSecurityException | IOException | NumberFormatException | LocatorException e) { - throw new CadiException(e); - } - } - - public Result load(final String accessToken, final byte[] cred) throws APIException, CadiException, LocatorException { - long start = System.currentTimeMillis(); - try { - Result ri = introCL.introspect(accessToken); - if(ri.isOK()) { - return Result.ok(ri.code, new TokenPerm(TokenMgr.this,permsDF,ri.value,cred,getPath(accessToken))); - } else { - return Result.err(ri); - } - } finally { - access.printf(Level.INFO, "Token loaded in %d ms",System.currentTimeMillis()-start); - } - } - } + } catch (GeneralSecurityException | IOException | NumberFormatException | LocatorException e) { + throw new CadiException(e); + } + } + + public Result load(final String accessToken, final byte[] cred) throws APIException, CadiException, LocatorException { + long start = System.currentTimeMillis(); + try { + Result ri = introCL.introspect(accessToken); + if(ri.isOK()) { + return Result.ok(ri.code, new TokenPerm(TokenMgr.this,permsDF,ri.value,cred,getPath(accessToken))); + } else { + return Result.err(ri); + } + } finally { + access.printf(Level.INFO, "Token loaded in %d ms",System.currentTimeMillis()-start); + } + } + } - public void clear(Principal p, StringBuilder report) { - TokenPerm tp = tpmap.remove(p.getName()); - if(tp==null) { - report.append("Nothing to clear"); - } else { - report.append("Cleared "); - report.append(p.getName()); - } - } + public void clear(Principal p, StringBuilder report) { + TokenPerm tp = tpmap.remove(p.getName()); + if(tp==null) { + report.append("Nothing to clear"); + } else { + report.append("Cleared "); + report.append(p.getName()); + } + } - @Override - protected TokenPerm newCacheable(Introspect i, long expires, byte[] hash, Path path) throws APIException { - // Note: Introspect drives the Expiration... ignoring expires. - return new TokenPerm(this,permsDF,i,hash,path); - } + @Override + protected TokenPerm newCacheable(Introspect i, long expires, byte[] hash, Path path) throws APIException { + // Note: Introspect drives the Expiration... ignoring expires. + return new TokenPerm(this,permsDF,i,hash,path); + } - public TokenPerm putIntrospect(Introspect intro, byte[] cred) throws APIException { - return newCacheable(intro, intro.getExp(), cred, getPath(intro.getAccessToken())); - } + public TokenPerm putIntrospect(Introspect intro, byte[] cred) throws APIException { + return newCacheable(intro, intro.getExp(), cred, getPath(intro.getAccessToken())); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java index bb33bc76..daac8f43 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java @@ -42,133 +42,133 @@ import aaf.v2_0.Perms; import aafoauth.v2_0.Introspect; public class TokenPerm extends Persisting{ - private static final List NULL_PERMS = new ArrayList<>(); - private Introspect introspect; - private List perms; - private String scopes; - public TokenPerm(Persist p, RosettaDF permsDF, Introspect ti, byte[] hash, Path path) throws APIException { - super(p,ti,ti.getExp(),hash,path); // ti.getExp() is seconds after Jan 1, 1970 ) - this.introspect = ti; - if(ti.getContent()==null || ti.getContent().length()==0) { - perms = NULL_PERMS; - } else { - LoadPermissions lp; - try { - lp = new LoadPermissions(new StringReader(ti.getContent())); - perms = lp.perms; - } catch (ParseException e) { - throw new APIException("Error parsing Content",e); - } - } - scopes = ti.getScope(); - } - - public List perms() { - return perms; - } - - public String getClientId() { - return introspect.getClientId(); - } - - public String getUsername() { - return introspect.getUsername(); - } - - public String getToken() { - return introspect.getAccessToken(); - } - - public synchronized String getScopes() { - return scopes; - } + private static final List NULL_PERMS = new ArrayList<>(); + private Introspect introspect; + private List perms; + private String scopes; + public TokenPerm(Persist p, RosettaDF permsDF, Introspect ti, byte[] hash, Path path) throws APIException { + super(p,ti,ti.getExp(),hash,path); // ti.getExp() is seconds after Jan 1, 1970 ) + this.introspect = ti; + if(ti.getContent()==null || ti.getContent().length()==0) { + perms = NULL_PERMS; + } else { + LoadPermissions lp; + try { + lp = new LoadPermissions(new StringReader(ti.getContent())); + perms = lp.perms; + } catch (ParseException e) { + throw new APIException("Error parsing Content",e); + } + } + scopes = ti.getScope(); + } + + public List perms() { + return perms; + } + + public String getClientId() { + return introspect.getClientId(); + } + + public String getUsername() { + return introspect.getUsername(); + } + + public String getToken() { + return introspect.getAccessToken(); + } + + public synchronized String getScopes() { + return scopes; + } - public Introspect getIntrospect() { - return introspect; - } - - // Direct Parse Perms into List - public static class LoadPermissions { - public List perms; + public Introspect getIntrospect() { + return introspect; + } + + // Direct Parse Perms into List + public static class LoadPermissions { + public List perms; - public LoadPermissions(Reader r) throws ParseException { - PermInfo pi = new PermInfo(); - InJson ij = new InJson(); - Parsed pd = ij.newParsed(); - boolean inPerms = false, inPerm = false; - while((pd = ij.parse(r,pd.reuse())).valid()) { - switch(pd.event) { - case Parse.START_DOC: - perms = new ArrayList<>(); - break; - case Parse.START_ARRAY: - inPerms = "perm".equals(pd.name); - break; - case '{': - if(inPerms) { - inPerm=true; - pi.clear(); - } - break; - case ',': - if(inPerm) { - pi.eval(pd); - } - break; - case '}': - if(inPerms) { - if(inPerm) { - pi.eval(pd); - AAFPermission perm = pi.create(); - if(perm!=null) { - perms.add(perm); - } - } - inPerm=false; - } - break; - case Parse.END_ARRAY: - if(inPerms) { - inPerms=false; - } - break; - case Parse.END_DOC: - break; - } - } - } - } - - // Gathering object for parsing objects, then creating AAF Permission - private static class PermInfo { - public String ns,type,instance,action; - public void clear() { - ns=type=instance=action=null; - } - public void eval(Parsed pd) { - if(pd.hasName()) { - switch(pd.name) { - case "ns": - ns=pd.sb.toString(); - break; - case "type": - type=pd.sb.toString(); - break; - case "instance": - instance=pd.sb.toString(); - break; - case "action": - action=pd.sb.toString(); - break; - } - } - } - public AAFPermission create() { - if(type!=null && instance!=null && action !=null) { - return new AAFPermission(ns,type, instance, action); - } else { - return null; - } - } - } + public LoadPermissions(Reader r) throws ParseException { + PermInfo pi = new PermInfo(); + InJson ij = new InJson(); + Parsed pd = ij.newParsed(); + boolean inPerms = false, inPerm = false; + while((pd = ij.parse(r,pd.reuse())).valid()) { + switch(pd.event) { + case Parse.START_DOC: + perms = new ArrayList<>(); + break; + case Parse.START_ARRAY: + inPerms = "perm".equals(pd.name); + break; + case '{': + if(inPerms) { + inPerm=true; + pi.clear(); + } + break; + case ',': + if(inPerm) { + pi.eval(pd); + } + break; + case '}': + if(inPerms) { + if(inPerm) { + pi.eval(pd); + AAFPermission perm = pi.create(); + if(perm!=null) { + perms.add(perm); + } + } + inPerm=false; + } + break; + case Parse.END_ARRAY: + if(inPerms) { + inPerms=false; + } + break; + case Parse.END_DOC: + break; + } + } + } + } + + // Gathering object for parsing objects, then creating AAF Permission + private static class PermInfo { + public String ns,type,instance,action; + public void clear() { + ns=type=instance=action=null; + } + public void eval(Parsed pd) { + if(pd.hasName()) { + switch(pd.name) { + case "ns": + ns=pd.sb.toString(); + break; + case "type": + type=pd.sb.toString(); + break; + case "instance": + instance=pd.sb.toString(); + break; + case "action": + action=pd.sb.toString(); + break; + } + } + } + public AAFPermission create() { + if(type!=null && instance!=null && action !=null) { + return new AAFPermission(ns,type, instance, action); + } else { + return null; + } + } + } } \ No newline at end of file diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzClient.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzClient.java index a14c0f8e..1ebbe877 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzClient.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzClient.java @@ -35,6 +35,6 @@ import org.onap.aaf.misc.env.APIException; * */ public abstract class TzClient { - public abstract void setToken(final String client_id, final TimedToken token) throws IOException; - public abstract RET best(Retryable rcode) throws CadiException, LocatorException, APIException; + public abstract void setToken(final String client_id, final TimedToken token) throws IOException; + public abstract RET best(Retryable rcode) throws CadiException, LocatorException, APIException; } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java index c565fa84..77348390 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java @@ -45,38 +45,38 @@ import org.onap.aaf.misc.env.APIException; * */ public class TzHClient extends TzClient { - private HMangr hman; - public SecurityInfoC si; - private TimedToken token; - private SecuritySetter tokenSS; + private HMangr hman; + public SecurityInfoC si; + private TimedToken token; + private SecuritySetter tokenSS; - public TzHClient(Access access, String tagOrURL) throws CadiException, LocatorException { - try { - si = SecurityInfoC.instance(access, HttpURLConnection.class); - hman = new HMangr(access, new AAFLocator(si,new URI(access.getProperty(tagOrURL, tagOrURL)))); - } catch (URISyntaxException e) { - throw new CadiException(e); - } - } - public TzHClient(Access access, SecurityInfoC hsi, Locator loc) throws LocatorException { - si = hsi; - hman = new HMangr(access, loc); - } - - public void setToken(final String client_id, TimedToken token) throws IOException { - this.token = token; - tokenSS = new HTokenSS(si, client_id, token.getAccessToken()); - } + public TzHClient(Access access, String tagOrURL) throws CadiException, LocatorException { + try { + si = SecurityInfoC.instance(access, HttpURLConnection.class); + hman = new HMangr(access, new AAFLocator(si,new URI(access.getProperty(tagOrURL, tagOrURL)))); + } catch (URISyntaxException e) { + throw new CadiException(e); + } + } + public TzHClient(Access access, SecurityInfoC hsi, Locator loc) throws LocatorException { + si = hsi; + hman = new HMangr(access, loc); + } + + public void setToken(final String client_id, TimedToken token) throws IOException { + this.token = token; + tokenSS = new HTokenSS(si, client_id, token.getAccessToken()); + } - public RET best (Retryable retryable) throws CadiException, LocatorException, APIException { - if(token == null || tokenSS==null) { - throw new CadiException("OAuth2 Token has not been set"); - } - if(token.expired()) { - //TODO Refresh? - throw new CadiException("Expired Token"); - } else { - return hman.best(tokenSS, retryable); - } - } + public RET best (Retryable retryable) throws CadiException, LocatorException, APIException { + if(token == null || tokenSS==null) { + throw new CadiException("OAuth2 Token has not been set"); + } + if(token.expired()) { + //TODO Refresh? + throw new CadiException("Expired Token"); + } else { + return hman.best(tokenSS, retryable); + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java index ff0c246b..688f30b1 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java @@ -68,129 +68,129 @@ import org.onap.aaf.misc.env.util.Pool.Pooled; * */ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { - private final String realm; - private final CredVal rbac; - - - public OBasicHttpTaf(final PropAccess access, final CredVal rbac, final String realm, final String token_url, final String introspect_url) throws CadiException { - super(access, token_url,introspect_url); - this.rbac = rbac; - this.realm = realm; - } - - /** - * Note: BasicHttp works for either Carbon Based (Humans) or Silicon Based (machine) Lifeforms. - * @see Taf - */ - public TafResp validate(Taf.LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { - // See if Request implements BasicCred (aka CadiWrap or other), and if User/Pass has already been set separately - final String user; - String password=null; - byte[] cred=null; - if(req instanceof BasicCred) { - BasicCred bc = (BasicCred)req; - user = bc.getUser(); - cred = bc.getCred(); - } else { - String authz = req.getHeader("Authorization"); - if(authz != null && authz.startsWith("Basic ")) { - if(!req.isSecure()) { - access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); - } - try { - String temp = Symm.base64noSplit.decode(authz.substring(6)); - int colon = temp.lastIndexOf(':'); - if(colon>0) { - user = temp.substring(0,colon); - password = temp.substring(colon+1); - } else { - access.printf(Level.AUDIT,"Malformed BasicAuth entry ip=%s, entry=%s",req.getRemoteAddr(), - access.encrypt(temp)); - return new BasicHttpTafResp(access,null,"Malformed BasicAuth entry",RESP.FAIL,resp,realm,false); - } - if(!rbac.validate(user,Type.PASSWORD,password.getBytes(),req)) { - return new BasicHttpTafResp(access,null,buildMsg(null,req,"user/pass combo invalid for ",user,"from",req.getRemoteAddr()), - RESP.TRY_AUTHENTICATING,resp,realm,true); - } - } catch (IOException e) { - access.log(e, ERROR_GETTING_TOKEN_CLIENT); - return new BasicHttpTafResp(access,null,ERROR_GETTING_TOKEN_CLIENT,RESP.FAIL,resp,realm,false); - } - } else { - return new BasicHttpTafResp(access,null,"Not a Basic Auth",RESP.TRY_ANOTHER_TAF,resp,realm,false); - } - } + private final String realm; + private final CredVal rbac; + + + public OBasicHttpTaf(final PropAccess access, final CredVal rbac, final String realm, final String token_url, final String introspect_url) throws CadiException { + super(access, token_url,introspect_url); + this.rbac = rbac; + this.realm = realm; + } + + /** + * Note: BasicHttp works for either Carbon Based (Humans) or Silicon Based (machine) Lifeforms. + * @see Taf + */ + public TafResp validate(Taf.LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { + // See if Request implements BasicCred (aka CadiWrap or other), and if User/Pass has already been set separately + final String user; + String password=null; + byte[] cred=null; + if(req instanceof BasicCred) { + BasicCred bc = (BasicCred)req; + user = bc.getUser(); + cred = bc.getCred(); + } else { + String authz = req.getHeader("Authorization"); + if(authz != null && authz.startsWith("Basic ")) { + if(!req.isSecure()) { + access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); + } + try { + String temp = Symm.base64noSplit.decode(authz.substring(6)); + int colon = temp.lastIndexOf(':'); + if(colon>0) { + user = temp.substring(0,colon); + password = temp.substring(colon+1); + } else { + access.printf(Level.AUDIT,"Malformed BasicAuth entry ip=%s, entry=%s",req.getRemoteAddr(), + access.encrypt(temp)); + return new BasicHttpTafResp(access,null,"Malformed BasicAuth entry",RESP.FAIL,resp,realm,false); + } + if(!rbac.validate(user,Type.PASSWORD,password.getBytes(),req)) { + return new BasicHttpTafResp(access,null,buildMsg(null,req,"user/pass combo invalid for ",user,"from",req.getRemoteAddr()), + RESP.TRY_AUTHENTICATING,resp,realm,true); + } + } catch (IOException e) { + access.log(e, ERROR_GETTING_TOKEN_CLIENT); + return new BasicHttpTafResp(access,null,ERROR_GETTING_TOKEN_CLIENT,RESP.FAIL,resp,realm,false); + } + } else { + return new BasicHttpTafResp(access,null,"Not a Basic Auth",RESP.TRY_ANOTHER_TAF,resp,realm,false); + } + } - try { - if(password==null && cred!=null) { - password = new String(cred); - cred = Hash.hashSHA256(cred); - } else if(password!=null && cred==null) { - cred = Hash.hashSHA256(password.getBytes()); - } - Pooled pclient = tokenClientPool.get(); - try { - pclient.content.password(user, password); - String scope=FQI.reverseDomain(client_id); - Result rtt = pclient.content.getToken('B',scope); - if(rtt.isOK()) { - if(rtt.value.expired()) { - return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: Token Expired",RESP.FAIL,resp,realm,true); - } else { - TimedToken tt = rtt.value; - Result prin = tkMgr.toPrincipal(tt.getAccessToken(), cred); - if(prin.isOK()) { - return new BasicHttpTafResp(access,prin.value,"BasicAuth/OAuth Token Authentication",RESP.IS_AUTHENTICATED,resp,realm,true); - } else { - return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: " + prin.code + ' ' + prin.error,RESP.FAIL,resp,realm,true); - } - } - } else { - return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: " + rtt.code + ' ' + rtt.error,RESP.FAIL,resp,realm,true); - } - } finally { - pclient.done(); - } - } catch (APIException | CadiException | LocatorException | NoSuchAlgorithmException e) { - access.log(e, ERROR_GETTING_TOKEN_CLIENT); - return new BasicHttpTafResp(access,null,ERROR_GETTING_TOKEN_CLIENT,RESP.TRY_ANOTHER_TAF,resp,realm,false); - } - } - - protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { - StringBuilder sb = new StringBuilder(); - if(pr!=null) { - sb.append("user="); - sb.append(pr.getName()); - sb.append(','); - } - sb.append("ip="); - sb.append(req.getRemoteAddr()); - sb.append(",port="); - sb.append(req.getRemotePort()); - if(msg.length>0) { - sb.append(",msg=\""); - for(Object s : msg) { - sb.append(s.toString()); - } - sb.append('"'); - } - return sb.toString(); - } + try { + if(password==null && cred!=null) { + password = new String(cred); + cred = Hash.hashSHA256(cred); + } else if(password!=null && cred==null) { + cred = Hash.hashSHA256(password.getBytes()); + } + Pooled pclient = tokenClientPool.get(); + try { + pclient.content.password(user, password); + String scope=FQI.reverseDomain(client_id); + Result rtt = pclient.content.getToken('B',scope); + if(rtt.isOK()) { + if(rtt.value.expired()) { + return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: Token Expired",RESP.FAIL,resp,realm,true); + } else { + TimedToken tt = rtt.value; + Result prin = tkMgr.toPrincipal(tt.getAccessToken(), cred); + if(prin.isOK()) { + return new BasicHttpTafResp(access,prin.value,"BasicAuth/OAuth Token Authentication",RESP.IS_AUTHENTICATED,resp,realm,true); + } else { + return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: " + prin.code + ' ' + prin.error,RESP.FAIL,resp,realm,true); + } + } + } else { + return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: " + rtt.code + ' ' + rtt.error,RESP.FAIL,resp,realm,true); + } + } finally { + pclient.done(); + } + } catch (APIException | CadiException | LocatorException | NoSuchAlgorithmException e) { + access.log(e, ERROR_GETTING_TOKEN_CLIENT); + return new BasicHttpTafResp(access,null,ERROR_GETTING_TOKEN_CLIENT,RESP.TRY_ANOTHER_TAF,resp,realm,false); + } + } + + protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { + StringBuilder sb = new StringBuilder(); + if(pr!=null) { + sb.append("user="); + sb.append(pr.getName()); + sb.append(','); + } + sb.append("ip="); + sb.append(req.getRemoteAddr()); + sb.append(",port="); + sb.append(req.getRemotePort()); + if(msg.length>0) { + sb.append(",msg=\""); + for(Object s : msg) { + sb.append(s.toString()); + } + sb.append('"'); + } + return sb.toString(); + } - @Override - public Resp revalidate(CachedPrincipal prin, Object state) { -// if(prin instanceof BasicPrincipal) { -// BasicPrincipal ba = (BasicPrincipal)prin; -// if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { -// return Resp.UNVALIDATED; -// } -// return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; -// } - return Resp.NOT_MINE; - } - - public String toString() { - return "Basic Auth enabled on realm: " + realm; - } + @Override + public Resp revalidate(CachedPrincipal prin, Object state) { +// if(prin instanceof BasicPrincipal) { +// BasicPrincipal ba = (BasicPrincipal)prin; +// if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { +// return Resp.UNVALIDATED; +// } +// return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; +// } + return Resp.NOT_MINE; + } + + public String toString() { + return "Basic Auth enabled on realm: " + realm; + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java index 73c6c113..c67f986e 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java @@ -46,132 +46,132 @@ import org.onap.aaf.misc.env.util.Pool.Pooled; import org.onap.aaf.misc.env.util.Split; public class OLur extends AbsOTafLur implements Lur { - public OLur(PropAccess access, final String token_url, final String introspect_url) throws APIException, CadiException { - super(access, token_url, introspect_url); - } + public OLur(PropAccess access, final String token_url, final String introspect_url) throws APIException, CadiException { + super(access, token_url, introspect_url); + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#fish(java.security.Principal, org.onap.aaf.cadi.Permission) - */ - @Override - public boolean fish(Principal bait, Permission ... pond) { - TokenPerm tp; - if(bait instanceof OAuth2Principal) { - OAuth2Principal oa2p = (OAuth2Principal)bait; - tp = oa2p.tokenPerm(); - } else { - tp=null; - } - if(tp==null) { - // if no Token Perm preset, get - try { - Pooled tcp = tokenClientPool.get(); - try { - TokenClient tc = tcp.content; - tc.username(bait.getName()); - Set scopeSet = new HashSet<>(); - scopeSet.add(tc.defaultScope()); - AAFPermission ap; - for (Permission p : pond) { - if(p instanceof AAFPermission) { - ap = (AAFPermission)p; - scopeSet.add(ap.getNS()); - } - } - String[] scopes = new String[scopeSet.size()]; - scopeSet.toArray(scopes); - - Result rtt = tc.getToken(Kind.getKind(bait),scopes); - if(rtt.isOK()) { - Result rtp = tkMgr.get(rtt.value.getAccessToken(), bait.getName().getBytes()); - if(rtp.isOK()) { - tp = rtp.value; - } - } - } finally { - tcp.done(); - } - } catch (APIException | LocatorException | CadiException e) { - access.log(e, "Unable to Get a Token"); - } - } - - boolean rv = false; - if(tp!=null) { - if(tkMgr.access.willLog(Level.DEBUG)) { - StringBuilder sb = new StringBuilder("AAF Permissions for user "); - sb.append(bait.getName()); - sb.append(", from token "); - sb.append(tp.get().getAccessToken()); - for (AAFPermission p : tp.perms()) { - sb.append("\n\t["); - sb.append(p.getNS()); - sb.append(']'); - sb.append(p.getType()); - sb.append('|'); - sb.append(p.getInstance()); - sb.append('|'); - sb.append(p.getAction()); - } - sb.append('\n'); - access.log(Level.DEBUG, sb); - } - for (Permission p : pond) { - if(rv) { - break; - } - for (AAFPermission perm : tp.perms()) { - if (rv=perm.match(p)) { - break; - } - } - } - } - return rv; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#fish(java.security.Principal, org.onap.aaf.cadi.Permission) + */ + @Override + public boolean fish(Principal bait, Permission ... pond) { + TokenPerm tp; + if(bait instanceof OAuth2Principal) { + OAuth2Principal oa2p = (OAuth2Principal)bait; + tp = oa2p.tokenPerm(); + } else { + tp=null; + } + if(tp==null) { + // if no Token Perm preset, get + try { + Pooled tcp = tokenClientPool.get(); + try { + TokenClient tc = tcp.content; + tc.username(bait.getName()); + Set scopeSet = new HashSet<>(); + scopeSet.add(tc.defaultScope()); + AAFPermission ap; + for (Permission p : pond) { + if(p instanceof AAFPermission) { + ap = (AAFPermission)p; + scopeSet.add(ap.getNS()); + } + } + String[] scopes = new String[scopeSet.size()]; + scopeSet.toArray(scopes); + + Result rtt = tc.getToken(Kind.getKind(bait),scopes); + if(rtt.isOK()) { + Result rtp = tkMgr.get(rtt.value.getAccessToken(), bait.getName().getBytes()); + if(rtp.isOK()) { + tp = rtp.value; + } + } + } finally { + tcp.done(); + } + } catch (APIException | LocatorException | CadiException e) { + access.log(e, "Unable to Get a Token"); + } + } + + boolean rv = false; + if(tp!=null) { + if(tkMgr.access.willLog(Level.DEBUG)) { + StringBuilder sb = new StringBuilder("AAF Permissions for user "); + sb.append(bait.getName()); + sb.append(", from token "); + sb.append(tp.get().getAccessToken()); + for (AAFPermission p : tp.perms()) { + sb.append("\n\t["); + sb.append(p.getNS()); + sb.append(']'); + sb.append(p.getType()); + sb.append('|'); + sb.append(p.getInstance()); + sb.append('|'); + sb.append(p.getAction()); + } + sb.append('\n'); + access.log(Level.DEBUG, sb); + } + for (Permission p : pond) { + if(rv) { + break; + } + for (AAFPermission perm : tp.perms()) { + if (rv=perm.match(p)) { + break; + } + } + } + } + return rv; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#fishAll(java.security.Principal, java.util.List) - */ - @Override - public void fishAll(Principal bait, List permissions) { - if(bait instanceof OAuth2Principal) { - for (AAFPermission p : ((OAuth2Principal)bait).tokenPerm().perms()) { - permissions.add(p); - } - } - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#fishAll(java.security.Principal, java.util.List) + */ + @Override + public void fishAll(Principal bait, List permissions) { + if(bait instanceof OAuth2Principal) { + for (AAFPermission p : ((OAuth2Principal)bait).tokenPerm().perms()) { + permissions.add(p); + } + } + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#handlesExclusively(org.onap.aaf.cadi.Permission) - */ - @Override - public boolean handlesExclusively(Permission ... pond) { - return false; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#handlesExclusively(org.onap.aaf.cadi.Permission) + */ + @Override + public boolean handlesExclusively(Permission ... pond) { + return false; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#handles(java.security.Principal) - */ - @Override - public boolean handles(Principal principal) { - return principal instanceof OAuth2Principal; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#handles(java.security.Principal) + */ + @Override + public boolean handles(Principal principal) { + return principal instanceof OAuth2Principal; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) - */ - @Override - public Permission createPerm(final String p) { - String[] s = Split.split('|',p); - switch(s.length) { - case 3: - return new AAFPermission(null, s[0],s[1],s[2]); - case 4: - return new AAFPermission(s[0],s[1],s[2],s[3]); - default: - return new LocalPermission(p); - } - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) + */ + @Override + public Permission createPerm(final String p) { + String[] s = Split.split('|',p); + switch(s.length) { + case 3: + return new AAFPermission(null, s[0],s[1],s[2]); + case 4: + return new AAFPermission(s[0],s[1],s[2],s[3]); + default: + return new LocalPermission(p); + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java index 11acbe91..d87ee780 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java @@ -48,254 +48,254 @@ import org.onap.aaf.misc.rosetta.env.RosettaDF; import org.onap.aaf.misc.rosetta.env.RosettaEnv; public abstract class Persist> extends PersistFile { - private static final long ONE_DAY = 86400000L; - private static final long CLEAN_CHECK = 2*60*1000L; // check every 2 mins - private static Timer clean; + private static final long ONE_DAY = 86400000L; + private static final long CLEAN_CHECK = 2*60*1000L; // check every 2 mins + private static Timer clean; - // store all the directories to review - // No Concurrent HashSet, or at least, it is all implemented with HashMap in older versions - private static Queue> allPersists = new ConcurrentLinkedQueue>(); - - private Map tmap; - protected RosettaEnv env; - private RosettaDF df; + // store all the directories to review + // No Concurrent HashSet, or at least, it is all implemented with HashMap in older versions + private static Queue> allPersists = new ConcurrentLinkedQueue>(); + + private Map tmap; + protected RosettaEnv env; + private RosettaDF df; - - public Persist(Access access, RosettaEnv env, Class cls, String sub_dir) throws CadiException, APIException { - super(access, sub_dir); - this.env = env; - df = env.newDataFactory(cls); - tmap = new ConcurrentHashMap<>(); - synchronized(Persist.class) { - if(clean==null) { - clean = new Timer(true); - clean.schedule(new Clean(access), 20000, CLEAN_CHECK); - } - } - allPersists.add(this); - } - - public void close() { - allPersists.remove(this); - } - - protected abstract CT newCacheable(T t, long expires_secsFrom1970, byte[] hash, Path path) throws APIException, IOException; + + public Persist(Access access, RosettaEnv env, Class cls, String sub_dir) throws CadiException, APIException { + super(access, sub_dir); + this.env = env; + df = env.newDataFactory(cls); + tmap = new ConcurrentHashMap<>(); + synchronized(Persist.class) { + if(clean==null) { + clean = new Timer(true); + clean.schedule(new Clean(access), 20000, CLEAN_CHECK); + } + } + allPersists.add(this); + } + + public void close() { + allPersists.remove(this); + } + + protected abstract CT newCacheable(T t, long expires_secsFrom1970, byte[] hash, Path path) throws APIException, IOException; - public RosettaDF getDF() { - return df; - } - public Result get(final String key, final byte[] hash, Loader rl) throws CadiException, APIException, LocatorException { - if(key==null) { - return null; - } - Holder hp = new Holder(null); - CT ct = tmap.get(key); - // Make sure cached Item is synced with Disk, but only even Minute to save Disk hits - if(ct!=null && ct.checkSyncTime()) { // check File Time only every SYNC Period (2 min) - if(ct.hasBeenTouched()) { - tmap.remove(key); - ct = null; - access.log(Level.DEBUG,"File for",key,"has been touched, removing memory entry"); - } - } + public RosettaDF getDF() { + return df; + } + public Result get(final String key, final byte[] hash, Loader rl) throws CadiException, APIException, LocatorException { + if(key==null) { + return null; + } + Holder hp = new Holder(null); + CT ct = tmap.get(key); + // Make sure cached Item is synced with Disk, but only even Minute to save Disk hits + if(ct!=null && ct.checkSyncTime()) { // check File Time only every SYNC Period (2 min) + if(ct.hasBeenTouched()) { + tmap.remove(key); + ct = null; + access.log(Level.DEBUG,"File for",key,"has been touched, removing memory entry"); + } + } - // If not currently in memory, check with Disk (which might have been updated by other processes) - if(ct==null) { - Holder hl = new Holder(0L); - T t; - if((t = readDisk(df, hash, key, hp, hl))!=null) { - try { - if((ct = newCacheable(t,hl.get(),hash,hp.get()))!=null) { - tmap.put(key, ct); - } - access.log(Level.DEBUG,"Read Token from",key); - } catch (IOException e) { - access.log(e,"Reading Token from",key); - } - } // if not read, then ct still==null - - // If not in memory, or on disk, get from Remote... IF reloadable (meaning, isn't hitting too often, etc). - if(ct==null || ct.checkReloadable()) { - // Load from external (if makes sense) - Result rtp = rl.load(key); - if(rtp.isOK()) { - ct = rtp.value; - try { - Path p = getPath(key); - writeDisk(df, ct.get(),ct.getHash(),p,ct.expires()); - access.log(Level.DEBUG, "Writing token",key); - } catch(CadiException e) { - throw e; - } catch (Exception e) { - throw new CadiException(e); - } - } else { - return Result.err(rtp); - } - } - - if(ct!=null) { - tmap.put(key, ct); - } - } else { - access.log(Level.DEBUG,"Found token in memory",key); - } - // ct can only be not-null here - ct.inc(); - return Result.ok(200,ct); - } + // If not currently in memory, check with Disk (which might have been updated by other processes) + if(ct==null) { + Holder hl = new Holder(0L); + T t; + if((t = readDisk(df, hash, key, hp, hl))!=null) { + try { + if((ct = newCacheable(t,hl.get(),hash,hp.get()))!=null) { + tmap.put(key, ct); + } + access.log(Level.DEBUG,"Read Token from",key); + } catch (IOException e) { + access.log(e,"Reading Token from",key); + } + } // if not read, then ct still==null + + // If not in memory, or on disk, get from Remote... IF reloadable (meaning, isn't hitting too often, etc). + if(ct==null || ct.checkReloadable()) { + // Load from external (if makes sense) + Result rtp = rl.load(key); + if(rtp.isOK()) { + ct = rtp.value; + try { + Path p = getPath(key); + writeDisk(df, ct.get(),ct.getHash(),p,ct.expires()); + access.log(Level.DEBUG, "Writing token",key); + } catch(CadiException e) { + throw e; + } catch (Exception e) { + throw new CadiException(e); + } + } else { + return Result.err(rtp); + } + } + + if(ct!=null) { + tmap.put(key, ct); + } + } else { + access.log(Level.DEBUG,"Found token in memory",key); + } + // ct can only be not-null here + ct.inc(); + return Result.ok(200,ct); + } - public void put(String key, CT ct) throws CadiException { - writeDisk(df, ct.get(), ct.getHash(), key, ct.expires()); - tmap.put(key,ct); - } - - public void delete(String key) { - tmap.remove(key); - deleteFromDisk(key); - } + public void put(String key, CT ct) throws CadiException { + writeDisk(df, ct.get(), ct.getHash(), key, ct.expires()); + tmap.put(key,ct); + } + + public void delete(String key) { + tmap.remove(key); + deleteFromDisk(key); + } - public interface Loader { - Result load(String key) throws APIException, CadiException, LocatorException; - } + public interface Loader { + Result load(String key) throws APIException, CadiException, LocatorException; + } - /** - * Clean will examine resources, and remove those that have expired. - * - * If "highs" have been exceeded, then we'll expire 10% more the next time. This will adjust after each run - * without checking contents more than once, making a good average "high" in the minimum speed. - * - * @author Jonathan - * - */ - private static final class Clean extends TimerTask { - private final Access access; - private long hourly; - - public Clean(Access access) { - this.access = access; - hourly=0; - } - - private static class Metrics { - public int mexists = 0, dexists=0; - public int mremoved = 0, dremoved=0; - } - - public void run() { - final long now = System.currentTimeMillis(); - final long dayFromNow = now + ONE_DAY; - final Metrics metrics = new Metrics(); - for(final Persist persist : allPersists) { - // Clear memory - if(access.willLog(Level.DEBUG)) { - access.log(Level.DEBUG, "Persist: Cleaning memory cache for",persist.tokenPath.toAbsolutePath()); - } - for(Entry es : persist.tmap.entrySet()) { - ++metrics.mexists; - Persistable p = (Persistable)es.getValue(); - if(p.checkSyncTime()) { - if(p.count()==0) { - ++metrics.mremoved; - persist.tmap.remove(es.getKey()); - access.printf(Level.DEBUG, "Persist: removed cached item %s from memory\n", es.getKey()); - } else { - p.clearCount(); - } - } else if(Files.exists(p.path())) { - - } - } - // Clear disk - try { - final StringBuilder sb = new StringBuilder(); - Files.walkFileTree(persist.tokenPath, new FileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - sb.setLength(0); - sb.append("Persist: Cleaning files from "); - sb.append(dir.toAbsolutePath()); - return FileVisitResult.CONTINUE; - } + /** + * Clean will examine resources, and remove those that have expired. + * + * If "highs" have been exceeded, then we'll expire 10% more the next time. This will adjust after each run + * without checking contents more than once, making a good average "high" in the minimum speed. + * + * @author Jonathan + * + */ + private static final class Clean extends TimerTask { + private final Access access; + private long hourly; + + public Clean(Access access) { + this.access = access; + hourly=0; + } + + private static class Metrics { + public int mexists = 0, dexists=0; + public int mremoved = 0, dremoved=0; + } + + public void run() { + final long now = System.currentTimeMillis(); + final long dayFromNow = now + ONE_DAY; + final Metrics metrics = new Metrics(); + for(final Persist persist : allPersists) { + // Clear memory + if(access.willLog(Level.DEBUG)) { + access.log(Level.DEBUG, "Persist: Cleaning memory cache for",persist.tokenPath.toAbsolutePath()); + } + for(Entry es : persist.tmap.entrySet()) { + ++metrics.mexists; + Persistable p = (Persistable)es.getValue(); + if(p.checkSyncTime()) { + if(p.count()==0) { + ++metrics.mremoved; + persist.tmap.remove(es.getKey()); + access.printf(Level.DEBUG, "Persist: removed cached item %s from memory\n", es.getKey()); + } else { + p.clearCount(); + } + } else if(Files.exists(p.path())) { + + } + } + // Clear disk + try { + final StringBuilder sb = new StringBuilder(); + Files.walkFileTree(persist.tokenPath, new FileVisitor() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + sb.setLength(0); + sb.append("Persist: Cleaning files from "); + sb.append(dir.toAbsolutePath()); + return FileVisitResult.CONTINUE; + } - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if(attrs.isRegularFile()) { - ++metrics.dexists; - try { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if(attrs.isRegularFile()) { + ++metrics.dexists; + try { - long exp = persist.readExpiration(file)*1000; // readExpiration is seconds from 1970 - if(now > exp) { // cover for bad token - sb.append("\n\tFile "); - sb.append(file.getFileName()); - sb.append(" expired "); - sb.append(Chrono.dateTime(new Date(exp))); - persist.deleteFromDisk(file); - ++metrics.dremoved; - } else if(exp > dayFromNow) { - sb.append("\n\tFile "); - sb.append(file.toString()); - sb.append(" data corrupted."); - persist.deleteFromDisk(file); - ++metrics.dremoved; - } - } catch (CadiException e) { - sb.append("\n\tError reading File "); - sb.append(file.toString()); - sb.append(". "); - sb.append(e.getMessage()); - ++metrics.dremoved; - } - - } - return FileVisitResult.CONTINUE; - } + long exp = persist.readExpiration(file)*1000; // readExpiration is seconds from 1970 + if(now > exp) { // cover for bad token + sb.append("\n\tFile "); + sb.append(file.getFileName()); + sb.append(" expired "); + sb.append(Chrono.dateTime(new Date(exp))); + persist.deleteFromDisk(file); + ++metrics.dremoved; + } else if(exp > dayFromNow) { + sb.append("\n\tFile "); + sb.append(file.toString()); + sb.append(" data corrupted."); + persist.deleteFromDisk(file); + ++metrics.dremoved; + } + } catch (CadiException e) { + sb.append("\n\tError reading File "); + sb.append(file.toString()); + sb.append(". "); + sb.append(e.getMessage()); + ++metrics.dremoved; + } + + } + return FileVisitResult.CONTINUE; + } - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { - access.log(Level.ERROR,"Error visiting file %s (%s)\n",file.toString(),exc.getMessage()); - return FileVisitResult.CONTINUE; - } + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + access.log(Level.ERROR,"Error visiting file %s (%s)\n",file.toString(),exc.getMessage()); + return FileVisitResult.CONTINUE; + } - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - access.log(Level.DEBUG, sb); - return FileVisitResult.CONTINUE; - } - - }); - } catch (IOException e) { - access.log(e, "Exception while cleaning Persistance"); - } - - } - - // We want to print some activity of Persistence Check at least hourly, even if no activity has occurred, but not litter the log if nothing is happening - boolean go=false; - Level level=Level.WARN; - if(access.willLog(Level.INFO)) { - go = true; - level=Level.INFO; - } else if(access.willLog(Level.WARN)) { - go = metrics.mremoved>0 || metrics.dremoved>0 || --hourly <= 0; - } - - if(go) { - access.printf(level, "Persist Cache: removed %d of %d items from memory and %d of %d from disk", - metrics.mremoved, metrics.mexists, metrics.dremoved, metrics.dexists); - hourly = 3600000/CLEAN_CHECK; - } - } - } + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + access.log(Level.DEBUG, sb); + return FileVisitResult.CONTINUE; + } + + }); + } catch (IOException e) { + access.log(e, "Exception while cleaning Persistance"); + } + + } + + // We want to print some activity of Persistence Check at least hourly, even if no activity has occurred, but not litter the log if nothing is happening + boolean go=false; + Level level=Level.WARN; + if(access.willLog(Level.INFO)) { + go = true; + level=Level.INFO; + } else if(access.willLog(Level.WARN)) { + go = metrics.mremoved>0 || metrics.dremoved>0 || --hourly <= 0; + } + + if(go) { + access.printf(level, "Persist Cache: removed %d of %d items from memory and %d of %d from disk", + metrics.mremoved, metrics.mexists, metrics.dremoved, metrics.dexists); + hourly = 3600000/CLEAN_CHECK; + } + } + } - /* (non-Javadoc) - * @see java.lang.Object#finalize() - */ - @Override - protected void finalize() throws Throwable { - close(); // can call twice. - } + /* (non-Javadoc) + * @see java.lang.Object#finalize() + */ + @Override + protected void finalize() throws Throwable { + close(); // can call twice. + } - + } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java index 8fd2c986..7aab519d 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java @@ -50,206 +50,206 @@ import org.onap.aaf.misc.rosetta.env.RosettaDF; public class PersistFile { - private static final String HASH_NO_MATCH = "Hash does not match in Persistence"; - private static final Object LOCK = new Object(); - - protected static Symm symm; - public Access access; - protected final Path tokenPath; - protected final String tokenDir; - private static final boolean isWindows = System.getProperty("os.name").startsWith("Windows"); - - public PersistFile(Access access, String sub_dir) throws CadiException, APIException { - this.access = access; - tokenPath = Paths.get(access.getProperty(Config.CADI_TOKEN_DIR,"tokens"), sub_dir); - try { - if(!Files.exists(tokenPath)) { - if(isWindows) { - // Sorry Windows users, you need to secure your own paths - Files.createDirectories(tokenPath); - } else { - Set spfp = PosixFilePermissions.fromString("rwxr-x---"); - Files.createDirectories(tokenPath,PosixFilePermissions.asFileAttribute(spfp)); - } - } - tokenDir=tokenPath.toRealPath().toString(); - } catch (IOException e) { - throw new CadiException(e); - } - synchronized(LOCK) { - if(symm==null) { - symm = Symm.obtain(access); - } - } - } + private static final String HASH_NO_MATCH = "Hash does not match in Persistence"; + private static final Object LOCK = new Object(); + + protected static Symm symm; + public Access access; + protected final Path tokenPath; + protected final String tokenDir; + private static final boolean isWindows = System.getProperty("os.name").startsWith("Windows"); + + public PersistFile(Access access, String sub_dir) throws CadiException, APIException { + this.access = access; + tokenPath = Paths.get(access.getProperty(Config.CADI_TOKEN_DIR,"tokens"), sub_dir); + try { + if(!Files.exists(tokenPath)) { + if(isWindows) { + // Sorry Windows users, you need to secure your own paths + Files.createDirectories(tokenPath); + } else { + Set spfp = PosixFilePermissions.fromString("rwxr-x---"); + Files.createDirectories(tokenPath,PosixFilePermissions.asFileAttribute(spfp)); + } + } + tokenDir=tokenPath.toRealPath().toString(); + } catch (IOException e) { + throw new CadiException(e); + } + synchronized(LOCK) { + if(symm==null) { + symm = Symm.obtain(access); + } + } + } - public Path writeDisk(final RosettaDF df, final T t, final byte[] cred, final String filename, final long expires) throws CadiException { - return writeDisk(df,t,cred,Paths.get(tokenDir,filename),expires); - } + public Path writeDisk(final RosettaDF df, final T t, final byte[] cred, final String filename, final long expires) throws CadiException { + return writeDisk(df,t,cred,Paths.get(tokenDir,filename),expires); + } - public Path writeDisk(final RosettaDF df, final T t, final byte[] cred, final Path target, final long expires) throws CadiException { - // Make sure File is completely written before making accessible on disk... avoid corruption. - try { - Path tpath = Files.createTempFile(tokenPath,target.getFileName().toString(), ".tmp"); - final OutputStream dos = Files.newOutputStream(tpath, StandardOpenOption.CREATE,StandardOpenOption.WRITE); - try { - // Write Expires so that we can read unencrypted. - for(int i=0;i>i)&0xFF)); - } + public Path writeDisk(final RosettaDF df, final T t, final byte[] cred, final Path target, final long expires) throws CadiException { + // Make sure File is completely written before making accessible on disk... avoid corruption. + try { + Path tpath = Files.createTempFile(tokenPath,target.getFileName().toString(), ".tmp"); + final OutputStream dos = Files.newOutputStream(tpath, StandardOpenOption.CREATE,StandardOpenOption.WRITE); + try { + // Write Expires so that we can read unencrypted. + for(int i=0;i>i)&0xFF)); + } - symm.exec(new Symm.SyncExec() { - @Override - public Void exec(Encryption enc) throws Exception { - CipherOutputStream os = enc.outputStream(dos, true); - try { - int size = cred==null?0:cred.length; - for(int i=0;i>i)&0xFF)); - } - if(cred!=null) { - os.write(cred); - } - df.newData().load(t).to(os); - } finally { - // Note: Someone on the Web noticed that using a DataOutputStream would not full close out without a flush first, - // leaving files open. - try { - os.flush(); - } catch (IOException e) { - access.log(Level.INFO, "Note: Caught Exeption while flushing CipherStream. Handled."); - } - try { - os.close(); - } catch (IOException e) { - access.log(Level.INFO, "Note: Caught Exeption while closing CipherStream. Handled."); - } - } - return null; - } - }); - } catch(Exception e) { - throw new CadiException(e); - } finally { - dos.close(); - } - return Files.move(tpath, target, StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - throw new CadiException(e); - } + symm.exec(new Symm.SyncExec() { + @Override + public Void exec(Encryption enc) throws Exception { + CipherOutputStream os = enc.outputStream(dos, true); + try { + int size = cred==null?0:cred.length; + for(int i=0;i>i)&0xFF)); + } + if(cred!=null) { + os.write(cred); + } + df.newData().load(t).to(os); + } finally { + // Note: Someone on the Web noticed that using a DataOutputStream would not full close out without a flush first, + // leaving files open. + try { + os.flush(); + } catch (IOException e) { + access.log(Level.INFO, "Note: Caught Exeption while flushing CipherStream. Handled."); + } + try { + os.close(); + } catch (IOException e) { + access.log(Level.INFO, "Note: Caught Exeption while closing CipherStream. Handled."); + } + } + return null; + } + }); + } catch(Exception e) { + throw new CadiException(e); + } finally { + dos.close(); + } + return Files.move(tpath, target, StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + throw new CadiException(e); + } - } + } - public T readDisk(final RosettaDF df, final byte[] cred, final String filename,final Holder hp, final Holder hl) throws CadiException { - if(hp.get()==null) { - hp.set(Paths.get(tokenDir,filename)); - } - return readDisk(df,cred,hp.get(),hl); - } - - public T readDisk(final RosettaDF df, final byte[] cred, final Path target, final Holder hexpired) throws CadiException { - // Try from Disk - T t = null; - if(Files.exists(target)) { - try { - final InputStream is = Files.newInputStream(target,StandardOpenOption.READ); - try { - // Read Expired unencrypted - long exp=0; - for(int i=0;i() { - @Override - public T exec(Encryption enc) throws Exception { - CipherInputStream dis = enc.inputStream(is,false); - try { - int size=0; - for(int i=0;i256) { - throw new CadiException("Invalid size in Token Persistence"); - } else if(cred!=null && size!=cred.length) { - throw new CadiException(HASH_NO_MATCH); - } - if(cred!=null) { - byte[] array = new byte[size]; - if(dis.read(array)>0) { - for(int i=0;i T readDisk(final RosettaDF df, final byte[] cred, final String filename,final Holder hp, final Holder hl) throws CadiException { + if(hp.get()==null) { + hp.set(Paths.get(tokenDir,filename)); + } + return readDisk(df,cred,hp.get(),hl); + } + + public T readDisk(final RosettaDF df, final byte[] cred, final Path target, final Holder hexpired) throws CadiException { + // Try from Disk + T t = null; + if(Files.exists(target)) { + try { + final InputStream is = Files.newInputStream(target,StandardOpenOption.READ); + try { + // Read Expired unencrypted + long exp=0; + for(int i=0;i() { + @Override + public T exec(Encryption enc) throws Exception { + CipherInputStream dis = enc.inputStream(is,false); + try { + int size=0; + for(int i=0;i256) { + throw new CadiException("Invalid size in Token Persistence"); + } else if(cred!=null && size!=cred.length) { + throw new CadiException(HASH_NO_MATCH); + } + if(cred!=null) { + byte[] array = new byte[size]; + if(dis.read(array)>0) { + for(int i=0;i hp) throws IOException { - Path p = hp.get(); - if(p==null) { - hp.set(p=Paths.get(tokenDir,filename)); - } - return Files.getLastModifiedTime(p); - } + public Path getPath(String filename) { + return Paths.get(tokenDir,filename); + } + + public FileTime getFileTime(String filename, Holder hp) throws IOException { + Path p = hp.get(); + if(p==null) { + hp.set(p=Paths.get(tokenDir,filename)); + } + return Files.getLastModifiedTime(p); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persistable.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persistable.java index 65437795..1f22028b 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persistable.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persistable.java @@ -24,16 +24,16 @@ package org.onap.aaf.cadi.persist; import java.nio.file.Path; public interface Persistable { - public boolean checkSyncTime(); - public boolean checkReloadable(); - public void inc(); - public int count(); - public void clearCount(); - public boolean hasBeenTouched(); - public long expires(); // seconds from 1970 - public boolean expired(); - public byte[] getHash(); - public boolean match(byte[] hashIn); - public T get(); - public Path path(); + public boolean checkSyncTime(); + public boolean checkReloadable(); + public void inc(); + public int count(); + public void clearCount(); + public boolean hasBeenTouched(); + public long expires(); // seconds from 1970 + public boolean expired(); + public byte[] getHash(); + public boolean match(byte[] hashIn); + public T get(); + public Path path(); } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java index 8b98f5bf..dd136a2a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java @@ -30,134 +30,134 @@ import java.nio.file.attribute.FileTime; import org.onap.aaf.cadi.Access.Level; public class Persisting implements Persistable { - private static final byte[] EMPTY = new byte[0]; - private final byte[] hash; // need to be able to validate disk entry - - private static final long SYNC_TIME = 1000*60*1L; // Checking File change max 1 min - private FileTime lastTouched; - private int count; - private long expires; - private long nextCheck; - private T t; - private Path path; - private Persist persist; - - public Persisting(Persist p, T t, long expiresSecsFrom1970, byte[] hash, Path path) { - persist = p; - this.t=t; - expires = expiresSecsFrom1970; - this.path = path; - try { - lastTouched = Files.getLastModifiedTime(path); - } catch (IOException e) { - lastTouched = null; - } - count=0; - nextCheck=0; - if(hash==null) { - this.hash = EMPTY; - } else { - this.hash = hash; - } - } - - @Override - public T get() { - return t; - } - - @Override - public long expires() { - return expires; - } - - @Override - public boolean expired() { - return System.currentTimeMillis()/1000>expires; - } - - @Override - public boolean hasBeenTouched() { - try { - FileTime modT = Files.getLastModifiedTime(path); - if(lastTouched==null) { - lastTouched = modT; - return true; - } else { - return !modT.equals(lastTouched); - } - } catch (NoSuchFileException e) { - persist.access.log(Level.DEBUG, "File not found " + e.getMessage() + ", this is ok, marking as touched."); - return true; - } catch (IOException e) { - persist.access.log(e, "Accessing File Time"); - return true; - } - } - - @Override - public synchronized boolean checkSyncTime() { - long temp=System.currentTimeMillis(); - if(nextCheck==0 || nextCheck persist; + + public Persisting(Persist p, T t, long expiresSecsFrom1970, byte[] hash, Path path) { + persist = p; + this.t=t; + expires = expiresSecsFrom1970; + this.path = path; + try { + lastTouched = Files.getLastModifiedTime(path); + } catch (IOException e) { + lastTouched = null; + } + count=0; + nextCheck=0; + if(hash==null) { + this.hash = EMPTY; + } else { + this.hash = hash; + } + } + + @Override + public T get() { + return t; + } + + @Override + public long expires() { + return expires; + } + + @Override + public boolean expired() { + return System.currentTimeMillis()/1000>expires; + } + + @Override + public boolean hasBeenTouched() { + try { + FileTime modT = Files.getLastModifiedTime(path); + if(lastTouched==null) { + lastTouched = modT; + return true; + } else { + return !modT.equals(lastTouched); + } + } catch (NoSuchFileException e) { + persist.access.log(Level.DEBUG, "File not found " + e.getMessage() + ", this is ok, marking as touched."); + return true; + } catch (IOException e) { + persist.access.log(e, "Accessing File Time"); + return true; + } + } + + @Override + public synchronized boolean checkSyncTime() { + long temp=System.currentTimeMillis(); + if(nextCheck==0 || nextCheck { - public Result update(ENV env); - public Result cancel(ENV env); + public Result update(ENV env); + public Result cancel(ENV env); } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java index 954c8555..32ff8109 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java @@ -31,72 +31,72 @@ import org.onap.aaf.cadi.client.Result; import org.onap.aaf.misc.env.impl.BasicEnv; public class Registrar { - private static final String REGISTRAR = "Registrar"; - private static final long INTERVAL = 15*60*1000L; // 15 mins - private static final long START = 3000; // Start in 3 seconds - private static final Object LOCK = new Object(); - private Deque> registrants; - private Timer timer, erroringTimer; + private static final String REGISTRAR = "Registrar"; + private static final long INTERVAL = 15*60*1000L; // 15 mins + private static final long START = 3000; // Start in 3 seconds + private static final Object LOCK = new Object(); + private Deque> registrants; + private Timer timer, erroringTimer; - public Registrar(final ENV env, boolean shutdownHook) { - registrants = new ConcurrentLinkedDeque>(); + public Registrar(final ENV env, boolean shutdownHook) { + registrants = new ConcurrentLinkedDeque>(); - erroringTimer = null; - timer = new Timer(REGISTRAR,true); - timer.schedule(new RegistrationTimerTask(env), START, INTERVAL); - - if(shutdownHook) { - Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { - close(env); - } - }); - } - } - - private class RegistrationTimerTask extends TimerTask { - private final ENV env; - public RegistrationTimerTask(ENV env) { - this.env = env; - } - @Override - public void run() { - for(Iterator> iter = registrants.iterator(); iter.hasNext();) { - Registrant reg = iter.next(); - Result rv = reg.update(env); - synchronized(LOCK) { - if(rv.isOK()) { - if(erroringTimer!=null) { - erroringTimer.cancel(); - erroringTimer = null; - } - } else { - // Account for different Registrations not being to same place - if(erroringTimer==null) { - erroringTimer = new Timer(REGISTRAR + " error re-check ",true); - erroringTimer.schedule(new RegistrationTimerTask(env),20000,20000); - } - } - } - } - } - } - - public void register(Registrant r) { - registrants.addLast(r); - } - - public void deregister(Registrant r) { - registrants.remove(r); - } + erroringTimer = null; + timer = new Timer(REGISTRAR,true); + timer.schedule(new RegistrationTimerTask(env), START, INTERVAL); + + if(shutdownHook) { + Runtime.getRuntime().addShutdownHook(new Thread() { + public void run() { + close(env); + } + }); + } + } + + private class RegistrationTimerTask extends TimerTask { + private final ENV env; + public RegistrationTimerTask(ENV env) { + this.env = env; + } + @Override + public void run() { + for(Iterator> iter = registrants.iterator(); iter.hasNext();) { + Registrant reg = iter.next(); + Result rv = reg.update(env); + synchronized(LOCK) { + if(rv.isOK()) { + if(erroringTimer!=null) { + erroringTimer.cancel(); + erroringTimer = null; + } + } else { + // Account for different Registrations not being to same place + if(erroringTimer==null) { + erroringTimer = new Timer(REGISTRAR + " error re-check ",true); + erroringTimer.schedule(new RegistrationTimerTask(env),20000,20000); + } + } + } + } + } + } + + public void register(Registrant r) { + registrants.addLast(r); + } + + public void deregister(Registrant r) { + registrants.remove(r); + } - public void close(ENV env) { - timer.cancel(); + public void close(ENV env) { + timer.cancel(); - Registrant r; - while(registrants.peek()!=null) { - r = registrants.pop(); - r.cancel(env); - } - } + Registrant r; + while(registrants.peek()!=null) { + r = registrants.pop(); + r.cancel(env); + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java index b21f8975..ae7ded3a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java @@ -48,136 +48,136 @@ import locate.v1_0.MgmtEndpoint; import locate.v1_0.MgmtEndpoints; public class RemoteRegistrant implements Registrant { - private final MgmtEndpoint mep; - private final MgmtEndpoints meps; - private final AAFCon aafcon; - private final RosettaDF mgmtEndpointsDF; - private final Locator locator; - private final Access access; - private final int timeout; + private final MgmtEndpoint mep; + private final MgmtEndpoints meps; + private final AAFCon aafcon; + private final RosettaDF mgmtEndpointsDF; + private final Locator locator; + private final Access access; + private final int timeout; - @SafeVarargs - public RemoteRegistrant(AAFCon aafcon, String name, String version, int port, RemoteRegistrant ... others) throws CadiException, LocatorException { - this.aafcon = aafcon; - access = aafcon.access; - try { - mgmtEndpointsDF = aafcon.env.newDataFactory(MgmtEndpoints.class); - } catch (APIException e1) { - throw new CadiException(e1); - } - timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); - String aaf_locate = access.getProperty(Config.AAF_LOCATE_URL,null); - if(aaf_locate==null) { - throw new CadiException(Config.AAF_LOCATE_URL + " is required."); - } else { - // Note: want Property Locator or Single, not AAFLocator, because we want the core service, not what it can find - try { - if(aaf_locate.indexOf(',')>=0) { - locator = new PropertyLocator(aaf_locate); - } else { - locator = new SingleEndpointLocator(aaf_locate); - } - } catch (URISyntaxException e) { - throw new CadiException(e); - } - } - - mep = new MgmtEndpoint(); - mep.setName(name); - mep.setPort(port); + @SafeVarargs + public RemoteRegistrant(AAFCon aafcon, String name, String version, int port, RemoteRegistrant ... others) throws CadiException, LocatorException { + this.aafcon = aafcon; + access = aafcon.access; + try { + mgmtEndpointsDF = aafcon.env.newDataFactory(MgmtEndpoints.class); + } catch (APIException e1) { + throw new CadiException(e1); + } + timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); + String aaf_locate = access.getProperty(Config.AAF_LOCATE_URL,null); + if(aaf_locate==null) { + throw new CadiException(Config.AAF_LOCATE_URL + " is required."); + } else { + // Note: want Property Locator or Single, not AAFLocator, because we want the core service, not what it can find + try { + if(aaf_locate.indexOf(',')>=0) { + locator = new PropertyLocator(aaf_locate); + } else { + locator = new SingleEndpointLocator(aaf_locate); + } + } catch (URISyntaxException e) { + throw new CadiException(e); + } + } + + mep = new MgmtEndpoint(); + mep.setName(name); + mep.setPort(port); - try { - String hostnameToRegister = access.getProperty(Config.AAF_REGISTER_AS, null); - if(hostnameToRegister==null) { - hostnameToRegister = access.getProperty(Config.HOSTNAME, null); - } - if(hostnameToRegister==null) { - hostnameToRegister = Inet4Address.getLocalHost().getHostName(); - } - mep.setHostname(hostnameToRegister); - - String latitude = access.getProperty(Config.CADI_LATITUDE, null); - if(latitude==null) { - latitude = access.getProperty("AFT_LATITUDE", null); - } - String longitude = access.getProperty(Config.CADI_LONGITUDE, null); - if(longitude==null) { - longitude = access.getProperty("AFT_LONGITUDE", null); - } - if(latitude==null || longitude==null) { - throw new CadiException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " is required"); - } else { - mep.setLatitude(Float.parseFloat(latitude)); - mep.setLongitude(Float.parseFloat(longitude)); - } - String split[] = Split.split('.', version); - mep.setPkg(split.length>3?Integer.parseInt(split[3]):0); - mep.setPatch(split.length>2?Integer.parseInt(split[2]):0); - mep.setMinor(split.length>1?Integer.parseInt(split[1]):0); - mep.setMajor(split.length>0?Integer.parseInt(split[0]):0); - - String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); - if(subprotocols==null) { - mep.setProtocol("http"); - } else { - mep.setProtocol("https"); - for(String s : Split.split(',', subprotocols)) { - mep.getSubprotocol().add(s); - } - } - } catch (NumberFormatException | UnknownHostException e) { - throw new CadiException("Error extracting Data from Properties for Registrar",e); - } - meps = new MgmtEndpoints(); - meps.getMgmtEndpoint().add(mep); - for(RemoteRegistrant rr : others) { - meps.getMgmtEndpoint().add(rr.mep); - } - } - - @Override - public Result update(ENV env) { - try { - Rcli client = aafcon.client(locator); - try { - Future fup = client.update("/registration",mgmtEndpointsDF,meps); - if(fup.get(timeout)) { - access.log(Level.INFO, "Registration complete to",client.getURI()); - return Result.ok(fup.code(),null); - } else { - access.log(Level.ERROR,"Error registering to AAF Locator on ", client.getURI()); - return Result.err(fup.code(),fup.body()); - } - } catch (APIException e) { - access.log(e, "Error registering service to AAF Locator"); - return Result.err(503,e.getMessage()); - } - - } catch (CadiException e) { - return Result.err(503,e.getMessage()); - } - } + try { + String hostnameToRegister = access.getProperty(Config.AAF_REGISTER_AS, null); + if(hostnameToRegister==null) { + hostnameToRegister = access.getProperty(Config.HOSTNAME, null); + } + if(hostnameToRegister==null) { + hostnameToRegister = Inet4Address.getLocalHost().getHostName(); + } + mep.setHostname(hostnameToRegister); + + String latitude = access.getProperty(Config.CADI_LATITUDE, null); + if(latitude==null) { + latitude = access.getProperty("AFT_LATITUDE", null); + } + String longitude = access.getProperty(Config.CADI_LONGITUDE, null); + if(longitude==null) { + longitude = access.getProperty("AFT_LONGITUDE", null); + } + if(latitude==null || longitude==null) { + throw new CadiException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " is required"); + } else { + mep.setLatitude(Float.parseFloat(latitude)); + mep.setLongitude(Float.parseFloat(longitude)); + } + String split[] = Split.split('.', version); + mep.setPkg(split.length>3?Integer.parseInt(split[3]):0); + mep.setPatch(split.length>2?Integer.parseInt(split[2]):0); + mep.setMinor(split.length>1?Integer.parseInt(split[1]):0); + mep.setMajor(split.length>0?Integer.parseInt(split[0]):0); + + String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); + if(subprotocols==null) { + mep.setProtocol("http"); + } else { + mep.setProtocol("https"); + for(String s : Split.split(',', subprotocols)) { + mep.getSubprotocol().add(s); + } + } + } catch (NumberFormatException | UnknownHostException e) { + throw new CadiException("Error extracting Data from Properties for Registrar",e); + } + meps = new MgmtEndpoints(); + meps.getMgmtEndpoint().add(mep); + for(RemoteRegistrant rr : others) { + meps.getMgmtEndpoint().add(rr.mep); + } + } + + @Override + public Result update(ENV env) { + try { + Rcli client = aafcon.client(locator); + try { + Future fup = client.update("/registration",mgmtEndpointsDF,meps); + if(fup.get(timeout)) { + access.log(Level.INFO, "Registration complete to",client.getURI()); + return Result.ok(fup.code(),null); + } else { + access.log(Level.ERROR,"Error registering to AAF Locator on ", client.getURI()); + return Result.err(fup.code(),fup.body()); + } + } catch (APIException e) { + access.log(e, "Error registering service to AAF Locator"); + return Result.err(503,e.getMessage()); + } + + } catch (CadiException e) { + return Result.err(503,e.getMessage()); + } + } - @Override - public Result cancel(ENV env) { - try { - Rcli client = aafcon.client(locator); - try { - Future fup = client.delete("/registration",mgmtEndpointsDF,meps); - if(fup.get(timeout)) { - access.log(Level.INFO, "Deregistration complete on",client.getURI()); - return Result.ok(fup.code(),null); - } else { - return Result.err(fup.code(),fup.body()); - } - } catch (APIException e) { - access.log(e, "Error deregistering service on AAF Locator"); - return Result.err(503,e.getMessage()); - } - - } catch (CadiException e) { - return Result.err(503,e.getMessage()); - } - } + @Override + public Result cancel(ENV env) { + try { + Rcli client = aafcon.client(locator); + try { + Future fup = client.delete("/registration",mgmtEndpointsDF,meps); + if(fup.get(timeout)) { + access.log(Level.INFO, "Deregistration complete on",client.getURI()); + return Result.ok(fup.code(),null); + } else { + return Result.err(fup.code(),fup.body()); + } + } catch (APIException e) { + access.log(e, "Error deregistering service on AAF Locator"); + return Result.err(503,e.getMessage()); + } + + } catch (CadiException e) { + return Result.err(503,e.getMessage()); + } + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java index 41931976..77be3449 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java @@ -45,449 +45,449 @@ import org.onap.aaf.cadi.util.SubStandardConsole; import org.onap.aaf.cadi.util.TheConsole; public class AAFSSO { - public static final MyConsole cons = TheConsole.implemented() ? new TheConsole() : new SubStandardConsole(); -// private static final int EIGHT_HOURS = 8 * 60 * 60 * 1000; + public static final MyConsole cons = TheConsole.implemented() ? new TheConsole() : new SubStandardConsole(); +// private static final int EIGHT_HOURS = 8 * 60 * 60 * 1000; - private Properties diskprops; - private boolean touchDiskprops; - private File dot_aaf = null; - private File sso = null; // instantiated, if ever, with diskprops + private Properties diskprops; + private boolean touchDiskprops; + private File dot_aaf = null; + private File sso = null; // instantiated, if ever, with diskprops - boolean removeSSO = false; - boolean loginOnly = false; - boolean doExit = true; - private PropAccess access; - private StringBuilder err; - private String user; - private String encrypted_pass; - private boolean use_X509; + boolean removeSSO = false; + boolean loginOnly = false; + boolean doExit = true; + private PropAccess access; + private StringBuilder err; + private String user; + private String encrypted_pass; + private boolean use_X509; - private PrintStream os; + private PrintStream os; - private Method close; - private final PrintStream stdOutOrig; - private final PrintStream stdErrOrig; - private boolean ok; + private Method close; + private final PrintStream stdOutOrig; + private final PrintStream stdErrOrig; + private boolean ok; - public AAFSSO(String[] args) throws IOException, CadiException { - this(args,new Properties()); - } - - public AAFSSO(String[] args, ProcessArgs pa) throws IOException, CadiException { - this(args,pa.process(args, new Properties())); - } + public AAFSSO(String[] args) throws IOException, CadiException { + this(args,new Properties()); + } + + public AAFSSO(String[] args, ProcessArgs pa) throws IOException, CadiException { + this(args,pa.process(args, new Properties())); + } - public AAFSSO(String[] args, Properties dp) throws IOException, CadiException { - stdOutOrig = System.out; - stdErrOrig = System.err; - ok = true; - List nargs = parseArgs(args); - diskprops = dp; - touchDiskprops = false; + public AAFSSO(String[] args, Properties dp) throws IOException, CadiException { + stdOutOrig = System.out; + stdErrOrig = System.err; + ok = true; + List nargs = parseArgs(args); + diskprops = dp; + touchDiskprops = false; - dot_aaf = new File(System.getProperty("user.home") + "/.aaf"); - if (!dot_aaf.exists()) { - dot_aaf.mkdirs(); - } - File f = new File(dot_aaf, "sso.out"); - os = new PrintStream(new FileOutputStream(f, true)); - //System.setOut(os); - System.setErr(os); + dot_aaf = new File(System.getProperty("user.home") + "/.aaf"); + if (!dot_aaf.exists()) { + dot_aaf.mkdirs(); + } + File f = new File(dot_aaf, "sso.out"); + os = new PrintStream(new FileOutputStream(f, true)); + //System.setOut(os); + System.setErr(os); - sso = new File(dot_aaf, "sso.props"); - if(sso.exists()) { - InputStream propStream = new FileInputStream(sso); - try { - diskprops.load(propStream); - } finally { - propStream.close(); - } - } - - File dot_aaf_kf = new File(dot_aaf, "keyfile"); + sso = new File(dot_aaf, "sso.props"); + if(sso.exists()) { + InputStream propStream = new FileInputStream(sso); + try { + diskprops.load(propStream); + } finally { + propStream.close(); + } + } + + File dot_aaf_kf = new File(dot_aaf, "keyfile"); - if (removeSSO) { - if (dot_aaf_kf.exists()) { - dot_aaf_kf.setWritable(true, true); - dot_aaf_kf.delete(); - } - if (sso.exists()) { - Properties temp = new Properties(); - // Keep only these - for(Entry es : diskprops.entrySet()) { - if(Config.CADI_LATITUDE.equals(es.getKey()) || - Config.CADI_LONGITUDE.equals(es.getKey()) || - Config.AAF_DEFAULT_REALM.equals(es.getKey())) { - temp.setProperty(es.getKey().toString(), es.getValue().toString()); - } - } - diskprops = temp; - touchDiskprops = true; - } - String[] naargs = new String[nargs.size()]; - nargs.toArray(naargs); - access = new PropAccess(os, naargs); - ok = false; - setLogDefault(); - System.out.println("AAF SSO information removed"); - } else { - // Config.setDefaultRealm(access); - - if (!dot_aaf_kf.exists()) { - FileOutputStream fos = new FileOutputStream(dot_aaf_kf); - try { - fos.write(Symm.keygen()); - setReadonly(dot_aaf_kf); - } finally { - fos.close(); - } - } + if (removeSSO) { + if (dot_aaf_kf.exists()) { + dot_aaf_kf.setWritable(true, true); + dot_aaf_kf.delete(); + } + if (sso.exists()) { + Properties temp = new Properties(); + // Keep only these + for(Entry es : diskprops.entrySet()) { + if(Config.CADI_LATITUDE.equals(es.getKey()) || + Config.CADI_LONGITUDE.equals(es.getKey()) || + Config.AAF_DEFAULT_REALM.equals(es.getKey())) { + temp.setProperty(es.getKey().toString(), es.getValue().toString()); + } + } + diskprops = temp; + touchDiskprops = true; + } + String[] naargs = new String[nargs.size()]; + nargs.toArray(naargs); + access = new PropAccess(os, naargs); + ok = false; + setLogDefault(); + System.out.println("AAF SSO information removed"); + } else { + // Config.setDefaultRealm(access); + + if (!dot_aaf_kf.exists()) { + FileOutputStream fos = new FileOutputStream(dot_aaf_kf); + try { + fos.write(Symm.keygen()); + setReadonly(dot_aaf_kf); + } finally { + fos.close(); + } + } - for(Entry es : diskprops.entrySet()) { - nargs.add(es.getKey().toString() + '=' + es.getValue().toString()); - } - String[] naargs = new String[nargs.size()]; - nargs.toArray(naargs); - access = new PropAccess(os, naargs); - - if(loginOnly) { - for(String tag : new String[] {Config.AAF_APPID, Config.AAF_APPPASS, - Config.CADI_ALIAS, Config.CADI_KEYSTORE,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { - access.getProperties().remove(tag); - diskprops.remove(tag); - } - touchDiskprops=true; + for(Entry es : diskprops.entrySet()) { + nargs.add(es.getKey().toString() + '=' + es.getValue().toString()); + } + String[] naargs = new String[nargs.size()]; + nargs.toArray(naargs); + access = new PropAccess(os, naargs); + + if(loginOnly) { + for(String tag : new String[] {Config.AAF_APPID, Config.AAF_APPPASS, + Config.CADI_ALIAS, Config.CADI_KEYSTORE,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { + access.getProperties().remove(tag); + diskprops.remove(tag); + } + touchDiskprops=true; // TODO Do we want to require reset of Passwords at least every Eight Hours. -// } else if (sso.lastModified() > (System.currentTimeMillis() - EIGHT_HOURS)) { -// for(String tag : new String[] {Config.AAF_APPPASS,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { -// access.getProperties().remove(tag); -// diskprops.remove(tag); -// } -// touchDiskprops=true; - } - - String keyfile = access.getProperty(Config.CADI_KEYFILE); // in case its CertificateMan props - if (keyfile == null) { - access.setProperty(Config.CADI_KEYFILE, dot_aaf_kf.getAbsolutePath()); - addProp(Config.CADI_KEYFILE,dot_aaf_kf.getAbsolutePath()); - } - - - String alias, appID; - alias = access.getProperty(Config.CADI_ALIAS); - if(alias==null) { - appID = access.getProperty(Config.AAF_APPID); - user=appID; - } else { - user=alias; - appID=null; - } - - if(appID!=null && access.getProperty(Config.AAF_APPPASS)==null) { - char[] password = cons.readPassword("Password for %s: ", appID); - String app_pass = access.encrypt(new String(password)); - access.setProperty(Config.AAF_APPPASS,app_pass); - diskprops.setProperty(Config.AAF_APPPASS, app_pass); - } - - String keystore=access.getProperty(Config.CADI_KEYSTORE); - String keystore_pass=access.getProperty(Config.CADI_KEYSTORE_PASSWORD); - - if(user==null || (alias!=null && (keystore==null || keystore_pass==null))) { - String select = null; - String name; - for (File tsf : dot_aaf.listFiles()) { - name = tsf.getName(); - if (!name.contains("trust") && (name.endsWith(".jks") || name.endsWith(".p12"))) { - setLogDefault(); - select = cons.readLine("Use %s for Identity? (y/n): ",tsf.getName()); - if("y".equalsIgnoreCase(select)) { - keystore = tsf.getCanonicalPath(); - access.setProperty(Config.CADI_KEYSTORE, keystore); - addProp(Config.CADI_KEYSTORE, keystore); - char[] password = cons.readPassword("Keystore Password: "); - encrypted_pass= access.encrypt(new String(password)); - access.setProperty(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass); - addProp(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass); - - // TODO READ Aliases out of Keystore? - user = alias = cons.readLine("Keystore alias: "); - access.setProperty(Config.CADI_ALIAS, user); - addProp(Config.CADI_ALIAS, user); - break; - } - } - } - if(alias==null) { - user = appID = cons.readLine(Config.AAF_APPID + ": "); - access.setProperty(Config.AAF_APPID, appID); - addProp(Config.AAF_APPID, appID); - char[] password = cons.readPassword(Config.AAF_APPPASS + ": "); - encrypted_pass= access.encrypt(new String(password)); - access.setProperty(Config.AAF_APPPASS, encrypted_pass); - addProp(Config.AAF_APPPASS, encrypted_pass); - } - } else { - encrypted_pass = access.getProperty(Config.CADI_KEYSTORE_PASSWORD); - if(encrypted_pass == null) { - keystore_pass = null; - encrypted_pass = access.getProperty(Config.AAF_APPPASS); - } else { - keystore_pass = encrypted_pass; - } - } - - - if (alias!=null) { - use_X509 = true; - } else { - use_X509 = false; - Symm decryptor = Symm.obtain(dot_aaf_kf); - if (user == null) { - if (sso.exists()) { - String cm_url = access.getProperty(Config.CM_URL); // SSO might overwrite... - FileInputStream fos = new FileInputStream(sso); - try { - access.load(fos); - user = access.getProperty(Config.AAF_APPID); - encrypted_pass = access.getProperty(Config.AAF_APPPASS); - // decrypt with .aaf, and re-encrypt with regular Keyfile - access.setProperty(Config.AAF_APPPASS, - access.encrypt(decryptor.depass(encrypted_pass))); - if (cm_url != null) { //Command line CM_URL Overwrites ssofile. - access.setProperty(Config.CM_URL, cm_url); - } - } finally { - fos.close(); - } - } else { - diskprops = new Properties(); - String realm = Config.getDefaultRealm(); - // Turn on Console Sysout - System.setOut(System.out); - user = cons.readLine("aaf_id(%s@%s): ", System.getProperty("user.name"), realm); - if (user == null) { - user = System.getProperty("user.name") + '@' + realm; - } else if (user.length() == 0) { // - user = System.getProperty("user.name") + '@' + realm; - } else if ((user.indexOf('@') < 0) && (realm != null)) { - user = user + '@' + realm; - } - access.setProperty(Config.AAF_APPID, user); - diskprops.setProperty(Config.AAF_APPID, user); - encrypted_pass = new String(cons.readPassword("aaf_password: ")); - System.setOut(os); - encrypted_pass = Symm.ENC + decryptor.enpass(encrypted_pass); - access.setProperty(Config.AAF_APPPASS, encrypted_pass); - diskprops.setProperty(Config.AAF_APPPASS, encrypted_pass); - diskprops.setProperty(Config.CADI_KEYFILE, access.getProperty(Config.CADI_KEYFILE)); - } - } - } - if (user == null) { - err = new StringBuilder("Add -D" + Config.AAF_APPID + "= "); - } - - if (encrypted_pass == null && alias == null) { - if (err == null) { - err = new StringBuilder(); - } else { - err.append("and "); - } - err.append("-D" + Config.AAF_APPPASS + "= "); - } - - String locateUrl = access.getProperty(Config.AAF_LOCATE_URL); - if(locateUrl==null) { - locateUrl=AAFSSO.cons.readLine("AAF Locator URL=https://"); - if(locateUrl==null || locateUrl.length()==0) { - err = new StringBuilder(Config.AAF_LOCATE_URL); - err.append(" is required."); - ok = false; - return; - } else { - locateUrl="https://"+locateUrl; - } - access.setProperty(Config.AAF_LOCATE_URL, locateUrl); - addProp(Config.AAF_LOCATE_URL, locateUrl); - } - - access.setProperty(Config.AAF_URL, Defaults.AAF_URL); - access.setProperty(Config.CM_URL, Defaults.CM_URL); - String cadiLatitude = access.getProperty(Config.CADI_LATITUDE); - if(cadiLatitude==null) { - System.out.println("# If you do not know your Global Coordinates, we suggest bing.com/maps"); - cadiLatitude=AAFSSO.cons.readLine("cadi_latitude[0.000]="); - if(cadiLatitude==null || cadiLatitude.isEmpty()) { - cadiLatitude="0.000"; - } - access.setProperty(Config.CADI_LATITUDE, cadiLatitude); - addProp(Config.CADI_LATITUDE, cadiLatitude); - - } - String cadiLongitude = access.getProperty(Config.CADI_LONGITUDE); - if(cadiLongitude==null) { - cadiLongitude=AAFSSO.cons.readLine("cadi_longitude[0.000]="); - if(cadiLongitude==null || cadiLongitude.isEmpty()) { - cadiLongitude="0.000"; - } - access.setProperty(Config.CADI_LONGITUDE, cadiLongitude); - addProp(Config.CADI_LONGITUDE, cadiLongitude); - } - - String cadi_truststore = access.getProperty(Config.CADI_TRUSTSTORE); - if(cadi_truststore==null) { - String name; - String select; - for (File tsf : dot_aaf.listFiles()) { - name = tsf.getName(); - if (name.contains("trust") && - (name.endsWith(".jks") || name.endsWith(".p12"))) { - select = cons.readLine("Use %s for TrustStore? (y/n):",tsf.getName()); - if("y".equalsIgnoreCase(select)) { - cadi_truststore=tsf.getCanonicalPath(); - access.setProperty(Config.CADI_TRUSTSTORE, cadi_truststore); - addProp(Config.CADI_TRUSTSTORE, cadi_truststore); - break; - } - } - } - } - if(cadi_truststore!=null) { - if(cadi_truststore.indexOf(File.separatorChar)<0) { - cadi_truststore=dot_aaf.getPath()+File.separator+cadi_truststore; - } - String cadi_truststore_password = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD); - if(cadi_truststore_password==null) { - cadi_truststore_password=AAFSSO.cons.readLine("cadi_truststore_password[%s]=","changeit"); - cadi_truststore_password = access.encrypt(cadi_truststore_password); - access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password); - addProp(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password); - } - } - ok = err==null; - } - writeFiles(); - } +// } else if (sso.lastModified() > (System.currentTimeMillis() - EIGHT_HOURS)) { +// for(String tag : new String[] {Config.AAF_APPPASS,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { +// access.getProperties().remove(tag); +// diskprops.remove(tag); +// } +// touchDiskprops=true; + } + + String keyfile = access.getProperty(Config.CADI_KEYFILE); // in case its CertificateMan props + if (keyfile == null) { + access.setProperty(Config.CADI_KEYFILE, dot_aaf_kf.getAbsolutePath()); + addProp(Config.CADI_KEYFILE,dot_aaf_kf.getAbsolutePath()); + } + + + String alias, appID; + alias = access.getProperty(Config.CADI_ALIAS); + if(alias==null) { + appID = access.getProperty(Config.AAF_APPID); + user=appID; + } else { + user=alias; + appID=null; + } + + if(appID!=null && access.getProperty(Config.AAF_APPPASS)==null) { + char[] password = cons.readPassword("Password for %s: ", appID); + String app_pass = access.encrypt(new String(password)); + access.setProperty(Config.AAF_APPPASS,app_pass); + diskprops.setProperty(Config.AAF_APPPASS, app_pass); + } + + String keystore=access.getProperty(Config.CADI_KEYSTORE); + String keystore_pass=access.getProperty(Config.CADI_KEYSTORE_PASSWORD); + + if(user==null || (alias!=null && (keystore==null || keystore_pass==null))) { + String select = null; + String name; + for (File tsf : dot_aaf.listFiles()) { + name = tsf.getName(); + if (!name.contains("trust") && (name.endsWith(".jks") || name.endsWith(".p12"))) { + setLogDefault(); + select = cons.readLine("Use %s for Identity? (y/n): ",tsf.getName()); + if("y".equalsIgnoreCase(select)) { + keystore = tsf.getCanonicalPath(); + access.setProperty(Config.CADI_KEYSTORE, keystore); + addProp(Config.CADI_KEYSTORE, keystore); + char[] password = cons.readPassword("Keystore Password: "); + encrypted_pass= access.encrypt(new String(password)); + access.setProperty(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass); + addProp(Config.CADI_KEYSTORE_PASSWORD, encrypted_pass); + + // TODO READ Aliases out of Keystore? + user = alias = cons.readLine("Keystore alias: "); + access.setProperty(Config.CADI_ALIAS, user); + addProp(Config.CADI_ALIAS, user); + break; + } + } + } + if(alias==null) { + user = appID = cons.readLine(Config.AAF_APPID + ": "); + access.setProperty(Config.AAF_APPID, appID); + addProp(Config.AAF_APPID, appID); + char[] password = cons.readPassword(Config.AAF_APPPASS + ": "); + encrypted_pass= access.encrypt(new String(password)); + access.setProperty(Config.AAF_APPPASS, encrypted_pass); + addProp(Config.AAF_APPPASS, encrypted_pass); + } + } else { + encrypted_pass = access.getProperty(Config.CADI_KEYSTORE_PASSWORD); + if(encrypted_pass == null) { + keystore_pass = null; + encrypted_pass = access.getProperty(Config.AAF_APPPASS); + } else { + keystore_pass = encrypted_pass; + } + } + + + if (alias!=null) { + use_X509 = true; + } else { + use_X509 = false; + Symm decryptor = Symm.obtain(dot_aaf_kf); + if (user == null) { + if (sso.exists()) { + String cm_url = access.getProperty(Config.CM_URL); // SSO might overwrite... + FileInputStream fos = new FileInputStream(sso); + try { + access.load(fos); + user = access.getProperty(Config.AAF_APPID); + encrypted_pass = access.getProperty(Config.AAF_APPPASS); + // decrypt with .aaf, and re-encrypt with regular Keyfile + access.setProperty(Config.AAF_APPPASS, + access.encrypt(decryptor.depass(encrypted_pass))); + if (cm_url != null) { //Command line CM_URL Overwrites ssofile. + access.setProperty(Config.CM_URL, cm_url); + } + } finally { + fos.close(); + } + } else { + diskprops = new Properties(); + String realm = Config.getDefaultRealm(); + // Turn on Console Sysout + System.setOut(System.out); + user = cons.readLine("aaf_id(%s@%s): ", System.getProperty("user.name"), realm); + if (user == null) { + user = System.getProperty("user.name") + '@' + realm; + } else if (user.length() == 0) { // + user = System.getProperty("user.name") + '@' + realm; + } else if ((user.indexOf('@') < 0) && (realm != null)) { + user = user + '@' + realm; + } + access.setProperty(Config.AAF_APPID, user); + diskprops.setProperty(Config.AAF_APPID, user); + encrypted_pass = new String(cons.readPassword("aaf_password: ")); + System.setOut(os); + encrypted_pass = Symm.ENC + decryptor.enpass(encrypted_pass); + access.setProperty(Config.AAF_APPPASS, encrypted_pass); + diskprops.setProperty(Config.AAF_APPPASS, encrypted_pass); + diskprops.setProperty(Config.CADI_KEYFILE, access.getProperty(Config.CADI_KEYFILE)); + } + } + } + if (user == null) { + err = new StringBuilder("Add -D" + Config.AAF_APPID + "= "); + } + + if (encrypted_pass == null && alias == null) { + if (err == null) { + err = new StringBuilder(); + } else { + err.append("and "); + } + err.append("-D" + Config.AAF_APPPASS + "= "); + } + + String locateUrl = access.getProperty(Config.AAF_LOCATE_URL); + if(locateUrl==null) { + locateUrl=AAFSSO.cons.readLine("AAF Locator URL=https://"); + if(locateUrl==null || locateUrl.length()==0) { + err = new StringBuilder(Config.AAF_LOCATE_URL); + err.append(" is required."); + ok = false; + return; + } else { + locateUrl="https://"+locateUrl; + } + access.setProperty(Config.AAF_LOCATE_URL, locateUrl); + addProp(Config.AAF_LOCATE_URL, locateUrl); + } + + access.setProperty(Config.AAF_URL, Defaults.AAF_URL); + access.setProperty(Config.CM_URL, Defaults.CM_URL); + String cadiLatitude = access.getProperty(Config.CADI_LATITUDE); + if(cadiLatitude==null) { + System.out.println("# If you do not know your Global Coordinates, we suggest bing.com/maps"); + cadiLatitude=AAFSSO.cons.readLine("cadi_latitude[0.000]="); + if(cadiLatitude==null || cadiLatitude.isEmpty()) { + cadiLatitude="0.000"; + } + access.setProperty(Config.CADI_LATITUDE, cadiLatitude); + addProp(Config.CADI_LATITUDE, cadiLatitude); + + } + String cadiLongitude = access.getProperty(Config.CADI_LONGITUDE); + if(cadiLongitude==null) { + cadiLongitude=AAFSSO.cons.readLine("cadi_longitude[0.000]="); + if(cadiLongitude==null || cadiLongitude.isEmpty()) { + cadiLongitude="0.000"; + } + access.setProperty(Config.CADI_LONGITUDE, cadiLongitude); + addProp(Config.CADI_LONGITUDE, cadiLongitude); + } + + String cadi_truststore = access.getProperty(Config.CADI_TRUSTSTORE); + if(cadi_truststore==null) { + String name; + String select; + for (File tsf : dot_aaf.listFiles()) { + name = tsf.getName(); + if (name.contains("trust") && + (name.endsWith(".jks") || name.endsWith(".p12"))) { + select = cons.readLine("Use %s for TrustStore? (y/n):",tsf.getName()); + if("y".equalsIgnoreCase(select)) { + cadi_truststore=tsf.getCanonicalPath(); + access.setProperty(Config.CADI_TRUSTSTORE, cadi_truststore); + addProp(Config.CADI_TRUSTSTORE, cadi_truststore); + break; + } + } + } + } + if(cadi_truststore!=null) { + if(cadi_truststore.indexOf(File.separatorChar)<0) { + cadi_truststore=dot_aaf.getPath()+File.separator+cadi_truststore; + } + String cadi_truststore_password = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD); + if(cadi_truststore_password==null) { + cadi_truststore_password=AAFSSO.cons.readLine("cadi_truststore_password[%s]=","changeit"); + cadi_truststore_password = access.encrypt(cadi_truststore_password); + access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password); + addProp(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password); + } + } + ok = err==null; + } + writeFiles(); + } - public void setLogDefault() { - this.setLogDefault(PropAccess.DEFAULT); - System.setOut(stdOutOrig); - } + public void setLogDefault() { + this.setLogDefault(PropAccess.DEFAULT); + System.setOut(stdOutOrig); + } - public void setStdErrDefault() { - access.setLogLevel(PropAccess.DEFAULT); - System.setErr(stdErrOrig); - } + public void setStdErrDefault() { + access.setLogLevel(PropAccess.DEFAULT); + System.setErr(stdErrOrig); + } - public void setLogDefault(Level level) { - if(access!=null) { - access.setLogLevel(level); - } - System.setOut(stdOutOrig); - } + public void setLogDefault(Level level) { + if(access!=null) { + access.setLogLevel(level); + } + System.setOut(stdOutOrig); + } - public boolean loginOnly() { - return loginOnly; - } + public boolean loginOnly() { + return loginOnly; + } - public void addProp(String key, String value) { - if(key==null || value==null) { - return; - } - touchDiskprops=true; - diskprops.setProperty(key, value); - } + public void addProp(String key, String value) { + if(key==null || value==null) { + return; + } + touchDiskprops=true; + diskprops.setProperty(key, value); + } - public void writeFiles() throws IOException { - if(touchDiskprops) { - // Store Creds, if they work - if (diskprops != null) { - if (!dot_aaf.exists()) { - dot_aaf.mkdirs(); - } - FileOutputStream fos = new FileOutputStream(sso); - try { - diskprops.store(fos, "AAF Single Signon"); - } finally { - fos.close(); - setReadonly(sso); - } - } - if (sso != null) { - setReadonly(sso); - sso.setWritable(true, true); - } - } - } + public void writeFiles() throws IOException { + if(touchDiskprops) { + // Store Creds, if they work + if (diskprops != null) { + if (!dot_aaf.exists()) { + dot_aaf.mkdirs(); + } + FileOutputStream fos = new FileOutputStream(sso); + try { + diskprops.store(fos, "AAF Single Signon"); + } finally { + fos.close(); + setReadonly(sso); + } + } + if (sso != null) { + setReadonly(sso); + sso.setWritable(true, true); + } + } + } - public PropAccess access() { - return access; - } + public PropAccess access() { + return access; + } - public StringBuilder err() { - return err; - } + public StringBuilder err() { + return err; + } - public String user() { - return user; - } + public String user() { + return user; + } - public String enc_pass() { - return encrypted_pass; - } + public String enc_pass() { + return encrypted_pass; + } - public boolean useX509() { - return use_X509; - } + public boolean useX509() { + return use_X509; + } - public void close() { - if (close != null) { - try { - close.invoke(null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - // nothing to do here. - } - close = null; - } - } + public void close() { + if (close != null) { + try { + close.invoke(null); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + // nothing to do here. + } + close = null; + } + } - private List parseArgs(String[] args) - { - List larg = new ArrayList<>(args.length); + private List parseArgs(String[] args) + { + List larg = new ArrayList<>(args.length); - // Cover for bash's need to escape *.. (\\*) - // also, remove SSO if required - for (int i = 0; i < args.length; ++i) { - if ("\\*".equals(args[i])) { - args[i] = "*"; - } + // Cover for bash's need to escape *.. (\\*) + // also, remove SSO if required + for (int i = 0; i < args.length; ++i) { + if ("\\*".equals(args[i])) { + args[i] = "*"; + } - if ("-logout".equalsIgnoreCase(args[i])) { - removeSSO = true; - } else if ("-login".equalsIgnoreCase(args[i])) { - loginOnly = true; - } else if ("-noexit".equalsIgnoreCase(args[i])) { - doExit = false; - } else { - larg.add(args[i]); - } - } - return larg; - } - - private void setReadonly(File file) { - file.setExecutable(false, false); - file.setWritable(false, false); - file.setReadable(false, false); - file.setReadable(true, true); - } + if ("-logout".equalsIgnoreCase(args[i])) { + removeSSO = true; + } else if ("-login".equalsIgnoreCase(args[i])) { + loginOnly = true; + } else if ("-noexit".equalsIgnoreCase(args[i])) { + doExit = false; + } else { + larg.add(args[i]); + } + } + return larg; + } + + private void setReadonly(File file) { + file.setExecutable(false, false); + file.setWritable(false, false); + file.setReadable(false, false); + file.setReadable(true, true); + } - public boolean ok() { - return ok; - } - - public static interface ProcessArgs { - public Properties process(final String[] args, final Properties props); - } + public boolean ok() { + return ok; + } + + public static interface ProcessArgs { + public Properties process(final String[] args, final Properties props); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/cert/test/JU_AAFListedCertIdentity.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/cert/test/JU_AAFListedCertIdentity.java index f2d91b02..1d1c6163 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/cert/test/JU_AAFListedCertIdentity.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/cert/test/JU_AAFListedCertIdentity.java @@ -59,119 +59,119 @@ import aaf.v2_0.Users.User; public class JU_AAFListedCertIdentity { - @Mock private AAFCon conMock; - @Mock private Rcli rcliMock; - @Mock private RosettaDF userDFMock; - @Mock private RosettaDF certDFMock; - @Mock private Future futureUsersMock; - @Mock private Future futureCertsMock; - - @Mock private Users usersMock; - @Mock private User userMock1; - @Mock private User userMock2; - @Mock private User userMock3; - - @Mock private Certs certsMock; - @Mock private Cert certMock1; - @Mock private Cert certMock2; - @Mock private Cert certMock3; - - @Mock private HttpServletRequest reqMock; - @Mock private X509Certificate x509Mock; - - private List usersList; - private List certsList; - - private PropAccess access; - - private ByteArrayOutputStream outStream; - - private static final String USERS = "user1,user2,user3"; - private static final String ID = "id"; - private static final String FINGERPRINT = "fingerprint"; - - private static final byte[] certBytes = "certificate".getBytes(); - - @Before - public void setup() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - MockitoAnnotations.initMocks(this); - - certsList = new ArrayList<>(); - certsList.add(certMock1); - certsList.add(certMock2); - certsList.add(certMock3); - - usersList = new ArrayList<>(); - usersList.add(userMock1); - usersList.add(userMock2); - usersList.add(userMock3); - - outStream = new ByteArrayOutputStream(); - access = new PropAccess(new PrintStream(outStream), new String[0]); - outStream.reset(); - access.setProperty(Config.AAF_CERT_IDS, USERS); - setFinal(conMock, conMock.getClass().getField("usersDF"), userDFMock); - setFinal(conMock, conMock.getClass().getField("certsDF"), certDFMock); - setFinal(conMock, conMock.getClass().getField("access"), access); - } - - @Test - public void test() throws APIException, CadiException, CertificateException { - doReturn(rcliMock).when(conMock).client(Config.AAF_DEFAULT_VERSION); - when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/tguard/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); - when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/basicAuth/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); - when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/csp/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); - - when(futureUsersMock.get(5000)).thenReturn(true); - futureUsersMock.value = usersMock; - when(usersMock.getUser()).thenReturn(usersList); - - when(rcliMock.read("/authn/cert/id/user1", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); - when(rcliMock.read("/authn/cert/id/user2", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); - when(rcliMock.read("/authn/cert/id/user3", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); - - when(futureCertsMock.get(5000)).thenReturn(true); - futureCertsMock.value = certsMock; - when(certsMock.getCert()).thenReturn(certsList); - - when(userMock1.getId()).thenReturn("user1"); - when(userMock2.getId()).thenReturn("user2"); - when(userMock3.getId()).thenReturn("user3"); - - prepareCert(certMock1); - prepareCert(certMock2); - prepareCert(certMock3); - - AAFListedCertIdentity certID = new AAFListedCertIdentity(access, conMock); - - when(x509Mock.getEncoded()).thenReturn(certBytes); - certID.identity(reqMock, null, null); - certID.identity(reqMock, null, certBytes); - certID.identity(reqMock, x509Mock, null); - certID.identity(reqMock, x509Mock, certBytes); - - Set hashSetOfUsers = AAFListedCertIdentity.trusted("basicAuth"); - assertThat(hashSetOfUsers.contains("user1"), is(true)); - assertThat(hashSetOfUsers.contains("user2"), is(true)); - assertThat(hashSetOfUsers.contains("user3"), is(true)); - - } - - private void setFinal(Object object, Field field, Object newValue) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - field.setAccessible(true); - - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & Modifier.FINAL); - - field.set(object, newValue); - } - - private void prepareCert(Cert cert) { - Date date = new Date(); - when(cert.getExpires()).thenReturn(Chrono.timeStamp(new Date(date.getTime() + (60 * 60 * 24)))); - when(cert.getId()).thenReturn(ID); - when(cert.getFingerprint()).thenReturn(FINGERPRINT.getBytes()); - } + @Mock private AAFCon conMock; + @Mock private Rcli rcliMock; + @Mock private RosettaDF userDFMock; + @Mock private RosettaDF certDFMock; + @Mock private Future futureUsersMock; + @Mock private Future futureCertsMock; + + @Mock private Users usersMock; + @Mock private User userMock1; + @Mock private User userMock2; + @Mock private User userMock3; + + @Mock private Certs certsMock; + @Mock private Cert certMock1; + @Mock private Cert certMock2; + @Mock private Cert certMock3; + + @Mock private HttpServletRequest reqMock; + @Mock private X509Certificate x509Mock; + + private List usersList; + private List certsList; + + private PropAccess access; + + private ByteArrayOutputStream outStream; + + private static final String USERS = "user1,user2,user3"; + private static final String ID = "id"; + private static final String FINGERPRINT = "fingerprint"; + + private static final byte[] certBytes = "certificate".getBytes(); + + @Before + public void setup() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + certsList = new ArrayList<>(); + certsList.add(certMock1); + certsList.add(certMock2); + certsList.add(certMock3); + + usersList = new ArrayList<>(); + usersList.add(userMock1); + usersList.add(userMock2); + usersList.add(userMock3); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]); + outStream.reset(); + access.setProperty(Config.AAF_CERT_IDS, USERS); + setFinal(conMock, conMock.getClass().getField("usersDF"), userDFMock); + setFinal(conMock, conMock.getClass().getField("certsDF"), certDFMock); + setFinal(conMock, conMock.getClass().getField("access"), access); + } + + @Test + public void test() throws APIException, CadiException, CertificateException { + doReturn(rcliMock).when(conMock).client(Config.AAF_DEFAULT_VERSION); + when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/tguard/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); + when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/basicAuth/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); + when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/csp/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); + + when(futureUsersMock.get(5000)).thenReturn(true); + futureUsersMock.value = usersMock; + when(usersMock.getUser()).thenReturn(usersList); + + when(rcliMock.read("/authn/cert/id/user1", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); + when(rcliMock.read("/authn/cert/id/user2", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); + when(rcliMock.read("/authn/cert/id/user3", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); + + when(futureCertsMock.get(5000)).thenReturn(true); + futureCertsMock.value = certsMock; + when(certsMock.getCert()).thenReturn(certsList); + + when(userMock1.getId()).thenReturn("user1"); + when(userMock2.getId()).thenReturn("user2"); + when(userMock3.getId()).thenReturn("user3"); + + prepareCert(certMock1); + prepareCert(certMock2); + prepareCert(certMock3); + + AAFListedCertIdentity certID = new AAFListedCertIdentity(access, conMock); + + when(x509Mock.getEncoded()).thenReturn(certBytes); + certID.identity(reqMock, null, null); + certID.identity(reqMock, null, certBytes); + certID.identity(reqMock, x509Mock, null); + certID.identity(reqMock, x509Mock, certBytes); + + Set hashSetOfUsers = AAFListedCertIdentity.trusted("basicAuth"); + assertThat(hashSetOfUsers.contains("user1"), is(true)); + assertThat(hashSetOfUsers.contains("user2"), is(true)); + assertThat(hashSetOfUsers.contains("user3"), is(true)); + + } + + private void setFinal(Object object, Field field, Object newValue) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + field.setAccessible(true); + + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & Modifier.FINAL); + + field.set(object, newValue); + } + + private void prepareCert(Cert cert) { + Date date = new Date(); + when(cert.getExpires()).thenReturn(Chrono.timeStamp(new Date(date.getTime() + (60 * 60 * 24)))); + when(cert.getId()).thenReturn(ID); + when(cert.getFingerprint()).thenReturn(FINGERPRINT.getBytes()); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/client/test/JU_ErrMessageTest.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/client/test/JU_ErrMessageTest.java index bb2edfb8..995e3d49 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/client/test/JU_ErrMessageTest.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/client/test/JU_ErrMessageTest.java @@ -43,92 +43,92 @@ import org.onap.aaf.misc.rosetta.env.RosettaEnv; import aaf.v2_0.Error; public class JU_ErrMessageTest { - - @Mock - private RosettaEnv env; - - @Mock(answer=Answers.RETURNS_DEEP_STUBS) - private RosettaDF errDF; + + @Mock + private RosettaEnv env; + + @Mock(answer=Answers.RETURNS_DEEP_STUBS) + private RosettaDF errDF; - private ErrMessage errMessage; + private ErrMessage errMessage; - private String attErrJson = "key:value"; - - private Error error; + private String attErrJson = "key:value"; + + private Error error; - private Future future; + private Future future; - private ByteArrayOutputStream errStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - - when(env.newDataFactory(Error.class)).thenReturn(errDF); - - future = new Future() { + private ByteArrayOutputStream errStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + when(env.newDataFactory(Error.class)).thenReturn(errDF); + + future = new Future() { - @Override - public boolean get(int timeout) throws CadiException { - return false; - } + @Override + public boolean get(int timeout) throws CadiException { + return false; + } - @Override - public int code() { - return 0; - } + @Override + public int code() { + return 0; + } - @Override - public String body() { - return "Body"; - } + @Override + public String body() { + return "Body"; + } - @Override - public String header(String tag) { - return "header"; - } - }; - - error = new Error(); - error.setMessageId("Error Message Id"); - error.setText("Error Text"); - errMessage = new ErrMessage(env); - - errStream = new ByteArrayOutputStream(); - } + @Override + public String header(String tag) { + return "header"; + } + }; + + error = new Error(); + error.setMessageId("Error Message Id"); + error.setText("Error Text"); + errMessage = new ErrMessage(env); + + errStream = new ByteArrayOutputStream(); + } - @Test - public void testPrintErrMessage() throws APIException { - when(errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()).thenReturn(error); - - errMessage.printErr(new PrintStream(errStream), attErrJson); - assertEquals("Error Message Id Error Text" + System.lineSeparator(), errStream.toString()); - } - - @Test - public void testToMsgJsonErrAttribute() throws APIException { - when(errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()).thenReturn(error); - - StringBuilder sb = new StringBuilder(); - errMessage.toMsg(sb,attErrJson); - - assertEquals(sb.toString(),"Error Message Id Error Text"); - } - - @Test - public void testToMsgFuture() { - StringBuilder sb = errMessage.toMsg(future); - - assertEquals(sb.toString(), "0: Body"); - } + @Test + public void testPrintErrMessage() throws APIException { + when(errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()).thenReturn(error); + + errMessage.printErr(new PrintStream(errStream), attErrJson); + assertEquals("Error Message Id Error Text" + System.lineSeparator(), errStream.toString()); + } + + @Test + public void testToMsgJsonErrAttribute() throws APIException { + when(errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()).thenReturn(error); + + StringBuilder sb = new StringBuilder(); + errMessage.toMsg(sb,attErrJson); + + assertEquals(sb.toString(),"Error Message Id Error Text"); + } + + @Test + public void testToMsgFuture() { + StringBuilder sb = errMessage.toMsg(future); + + assertEquals(sb.toString(), "0: Body"); + } - - @Test - public void testToMsgFutureWithoutException() throws APIException { - when(errDF.newData().in(TYPE.JSON).load(future.body()).asObject()).thenReturn(error); - - StringBuilder sb = errMessage.toMsg(future); - - assertEquals(sb.toString(), "Error Message Id Error Text"); - } + + @Test + public void testToMsgFutureWithoutException() throws APIException { + when(errDF.newData().in(TYPE.JSON).load(future.body()).asObject()).thenReturn(error); + + StringBuilder sb = errMessage.toMsg(future); + + assertEquals(sb.toString(), "Error Message Id Error Text"); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertMarshal.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertMarshal.java index 560014d1..96061aa8 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertMarshal.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertMarshal.java @@ -42,58 +42,58 @@ import aaf.v2_0.Certs.Cert; public class JU_CertMarshal { - private static final String fingerprint = "fingerprint"; - private static final String id = "id"; - private static final String x500 = "x500"; - - private String fingerprintAsString; - - private XMLGregorianCalendar expires; - - private ByteArrayOutputStream outStream; - - @Before - public void setup() { - expires = Chrono.timeStamp(); - outStream = new ByteArrayOutputStream(); - StringBuilder sb = new StringBuilder(); - DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb); - fingerprintAsString = sb.toString(); - } - - @Test - public void test() throws ParseException, IOException { - Cert cert = setupCert(); - CertMarshal cm = new CertMarshal(); - OutRaw raw = new OutRaw(); - - raw.extract(cert, new PrintStream(outStream), cm); - - String[] output = outStream.toString().split("\n"); - - String[] expected = new String[] { - "{ - ", - ", - fingerprint : \"" + fingerprintAsString + "\"", - ", - id : \"" + id + "\"", - ", - x500 : \"" + x500 + "\"", - ", - expires : \"" + Chrono.dateTime(expires) + "\"", - "} - ", - }; - - assertThat(output.length, is(expected.length)); - - for (int i = 0; i < output.length; i++) { - assertThat(output[i], is(expected[i])); - } - } - - private Cert setupCert() { - Cert cert = new Cert(); - cert.setId(id); - cert.setX500(x500); - cert.setExpires(expires); - cert.setFingerprint(fingerprint.getBytes()); - return cert; - } + private static final String fingerprint = "fingerprint"; + private static final String id = "id"; + private static final String x500 = "x500"; + + private String fingerprintAsString; + + private XMLGregorianCalendar expires; + + private ByteArrayOutputStream outStream; + + @Before + public void setup() { + expires = Chrono.timeStamp(); + outStream = new ByteArrayOutputStream(); + StringBuilder sb = new StringBuilder(); + DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb); + fingerprintAsString = sb.toString(); + } + + @Test + public void test() throws ParseException, IOException { + Cert cert = setupCert(); + CertMarshal cm = new CertMarshal(); + OutRaw raw = new OutRaw(); + + raw.extract(cert, new PrintStream(outStream), cm); + + String[] output = outStream.toString().split("\n"); + + String[] expected = new String[] { + "{ - ", + ", - fingerprint : \"" + fingerprintAsString + "\"", + ", - id : \"" + id + "\"", + ", - x500 : \"" + x500 + "\"", + ", - expires : \"" + Chrono.dateTime(expires) + "\"", + "} - ", + }; + + assertThat(output.length, is(expected.length)); + + for (int i = 0; i < output.length; i++) { + assertThat(output[i], is(expected[i])); + } + } + + private Cert setupCert() { + Cert cert = new Cert(); + cert.setId(id); + cert.setX500(x500); + cert.setExpires(expires); + cert.setFingerprint(fingerprint.getBytes()); + return cert; + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java index 6598fbe4..172ed758 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java @@ -42,77 +42,77 @@ import aaf.v2_0.Certs.Cert; public class JU_CertsMarshal { - private static final String fingerprint = "fingerprint"; - private static final String id = "id"; - private static final String x500 = "x500"; - - private String fingerprintAsString; - - private XMLGregorianCalendar expires; - - private ByteArrayOutputStream outStream; - - @Before - public void setup() { - expires = Chrono.timeStamp(); - outStream = new ByteArrayOutputStream(); - StringBuilder sb = new StringBuilder(); - DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb); - fingerprintAsString = sb.toString(); - } - - @Test - public void test() throws ParseException, IOException { - CertsStub certs = new CertsStub(); - CertsMarshal cm = new CertsMarshal(); - OutRaw raw = new OutRaw(); - - raw.extract(certs, new PrintStream(outStream), cm); - String[] output = outStream.toString().split("\n"); - - String[] expected = new String[] { - "{ - ", - "[ - cert", - "{ - ", - ", - fingerprint : \"" + fingerprintAsString + "\"", - ", - id : \"" + id + "\"", - ", - x500 : \"" + x500 + "\"", - ", - expires : \"" + Chrono.dateTime(expires) + "\"", - "} - ", - ", - ", - "{ - ", - ", - fingerprint : \"" + fingerprintAsString + "\"", - ", - id : \"" + id + "\"", - ", - x500 : \"" + x500 + "\"", - ", - expires : \"" + Chrono.dateTime(expires) + "\"", - "} - ", - "] - ", - "} - ", - }; - - assertThat(output.length, is(expected.length)); - - for (int i = 0; i < output.length; i++) { - assertThat(output[i], is(expected[i])); - } - } - - private Cert setupCert() { - Cert cert = new Cert(); - cert.setId(id); - cert.setX500(x500); - cert.setExpires(expires); - cert.setFingerprint(fingerprint.getBytes()); - return cert; - } - - private class CertsStub extends Certs { - public CertsStub() { - cert = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - cert.add(setupCert()); - } - } - } + private static final String fingerprint = "fingerprint"; + private static final String id = "id"; + private static final String x500 = "x500"; + + private String fingerprintAsString; + + private XMLGregorianCalendar expires; + + private ByteArrayOutputStream outStream; + + @Before + public void setup() { + expires = Chrono.timeStamp(); + outStream = new ByteArrayOutputStream(); + StringBuilder sb = new StringBuilder(); + DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb); + fingerprintAsString = sb.toString(); + } + + @Test + public void test() throws ParseException, IOException { + CertsStub certs = new CertsStub(); + CertsMarshal cm = new CertsMarshal(); + OutRaw raw = new OutRaw(); + + raw.extract(certs, new PrintStream(outStream), cm); + String[] output = outStream.toString().split("\n"); + + String[] expected = new String[] { + "{ - ", + "[ - cert", + "{ - ", + ", - fingerprint : \"" + fingerprintAsString + "\"", + ", - id : \"" + id + "\"", + ", - x500 : \"" + x500 + "\"", + ", - expires : \"" + Chrono.dateTime(expires) + "\"", + "} - ", + ", - ", + "{ - ", + ", - fingerprint : \"" + fingerprintAsString + "\"", + ", - id : \"" + id + "\"", + ", - x500 : \"" + x500 + "\"", + ", - expires : \"" + Chrono.dateTime(expires) + "\"", + "} - ", + "] - ", + "} - ", + }; + + assertThat(output.length, is(expected.length)); + + for (int i = 0; i < output.length; i++) { + assertThat(output[i], is(expected[i])); + } + } + + private Cert setupCert() { + Cert cert = new Cert(); + cert.setId(id); + cert.setX500(x500); + cert.setExpires(expires); + cert.setFingerprint(fingerprint.getBytes()); + return cert; + } + + private class CertsStub extends Certs { + public CertsStub() { + cert = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + cert.add(setupCert()); + } + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_AAFPermission.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_AAFPermission.java index 939e9b18..0b9399ae 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_AAFPermission.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_AAFPermission.java @@ -33,118 +33,118 @@ import org.onap.aaf.cadi.Permission; import org.onap.aaf.cadi.aaf.AAFPermission; public class JU_AAFPermission { - private final static String ns = "ns"; - private final static String type = "type"; - private final static String instance = "instance"; - private final static String action = "action"; - private final static String key = ns + '|' + type + '|' + instance + '|' + action; - private final static String role = "role"; - - private static List roles; - - @Before - public void setup() { - roles = new ArrayList<>(); - roles.add(role); - } - - @Test - public void constructor1Test() { - AAFPermission perm = new AAFPermission(ns, type, instance, action); - assertThat(perm.getNS(), is(ns)); - assertThat(perm.getType(), is(type)); - assertThat(perm.getInstance(), is(instance)); - assertThat(perm.getAction(), is(action)); - assertThat(perm.getKey(), is(key)); - assertThat(perm.permType(), is("AAF")); - assertThat(perm.roles().size(), is(0)); - assertThat(perm.toString(), is("AAFPermission:" + - "\n\tNS: " + ns + - "\n\tType: " + type + - "\n\tInstance: " + instance + - "\n\tAction: " + action + - "\n\tKey: " + key)); - } - - @Test - public void constructor2Test() { - AAFPermission perm; - - perm = new AAFPermission(ns, type, instance, action, null); - assertThat(perm.getNS(), is(ns)); - assertThat(perm.getType(), is(type)); - assertThat(perm.getInstance(), is(instance)); - assertThat(perm.getAction(), is(action)); - assertThat(perm.getKey(), is(key)); - assertThat(perm.permType(), is("AAF")); - assertThat(perm.roles().size(), is(0)); - assertThat(perm.toString(), is("AAFPermission:" + - "\n\tNS: " + ns + - "\n\tType: " + type + - "\n\tInstance: " + instance + - "\n\tAction: " + action + - "\n\tKey: " + key)); - - perm = new AAFPermission(ns, type, instance, action, roles); - assertThat(perm.getNS(), is(ns)); - assertThat(perm.getType(), is(type)); - assertThat(perm.getInstance(), is(instance)); - assertThat(perm.getAction(), is(action)); - assertThat(perm.getKey(), is(key)); - assertThat(perm.permType(), is("AAF")); - assertThat(perm.roles().size(), is(1)); - assertThat(perm.roles().get(0), is(role)); - assertThat(perm.toString(), is("AAFPermission:" + - "\n\tNS: " + ns + - "\n\tType: " + type + - "\n\tInstance: " + instance + - "\n\tAction: " + action + - "\n\tKey: " + key)); - } - - @Test - public void matchTest() { - final AAFPermission controlPermission = new AAFPermission(ns,type, instance, action); - PermissionStub perm; - AAFPermission aafperm; - - aafperm = new AAFPermission(ns, type, instance, action); - assertThat(controlPermission.match(aafperm), is(true)); - - perm = new PermissionStub(key); - assertThat(controlPermission.match(perm), is(true)); - - // Coverage tests - perm = new PermissionStub("not a valid key"); - assertThat(controlPermission.match(perm), is(false)); - perm = new PermissionStub("type"); - assertThat(controlPermission.match(perm), is(false)); - perm = new PermissionStub("type|instance|badAction"); - assertThat(controlPermission.match(perm), is(false)); - } - - @Test - public void coverageTest() { - AAFPermissionStub aafps = new AAFPermissionStub(); - assertThat(aafps.getNS(), is(nullValue())); - assertThat(aafps.getType(), is(nullValue())); - assertThat(aafps.getInstance(), is(nullValue())); - assertThat(aafps.getAction(), is(nullValue())); - assertThat(aafps.getKey(), is(nullValue())); - assertThat(aafps.permType(), is("AAF")); - assertThat(aafps.roles().size(), is(0)); - } - - private class PermissionStub implements Permission { - private String key; - - public PermissionStub(String key) { this.key = key; } - @Override public String permType() { return null; } - @Override public String getKey() { return key; } - @Override public boolean match(Permission p) { return false; } - } - - private class AAFPermissionStub extends AAFPermission { - - } + private final static String ns = "ns"; + private final static String type = "type"; + private final static String instance = "instance"; + private final static String action = "action"; + private final static String key = ns + '|' + type + '|' + instance + '|' + action; + private final static String role = "role"; + + private static List roles; + + @Before + public void setup() { + roles = new ArrayList<>(); + roles.add(role); + } + + @Test + public void constructor1Test() { + AAFPermission perm = new AAFPermission(ns, type, instance, action); + assertThat(perm.getNS(), is(ns)); + assertThat(perm.getType(), is(type)); + assertThat(perm.getInstance(), is(instance)); + assertThat(perm.getAction(), is(action)); + assertThat(perm.getKey(), is(key)); + assertThat(perm.permType(), is("AAF")); + assertThat(perm.roles().size(), is(0)); + assertThat(perm.toString(), is("AAFPermission:" + + "\n\tNS: " + ns + + "\n\tType: " + type + + "\n\tInstance: " + instance + + "\n\tAction: " + action + + "\n\tKey: " + key)); + } + + @Test + public void constructor2Test() { + AAFPermission perm; + + perm = new AAFPermission(ns, type, instance, action, null); + assertThat(perm.getNS(), is(ns)); + assertThat(perm.getType(), is(type)); + assertThat(perm.getInstance(), is(instance)); + assertThat(perm.getAction(), is(action)); + assertThat(perm.getKey(), is(key)); + assertThat(perm.permType(), is("AAF")); + assertThat(perm.roles().size(), is(0)); + assertThat(perm.toString(), is("AAFPermission:" + + "\n\tNS: " + ns + + "\n\tType: " + type + + "\n\tInstance: " + instance + + "\n\tAction: " + action + + "\n\tKey: " + key)); + + perm = new AAFPermission(ns, type, instance, action, roles); + assertThat(perm.getNS(), is(ns)); + assertThat(perm.getType(), is(type)); + assertThat(perm.getInstance(), is(instance)); + assertThat(perm.getAction(), is(action)); + assertThat(perm.getKey(), is(key)); + assertThat(perm.permType(), is("AAF")); + assertThat(perm.roles().size(), is(1)); + assertThat(perm.roles().get(0), is(role)); + assertThat(perm.toString(), is("AAFPermission:" + + "\n\tNS: " + ns + + "\n\tType: " + type + + "\n\tInstance: " + instance + + "\n\tAction: " + action + + "\n\tKey: " + key)); + } + + @Test + public void matchTest() { + final AAFPermission controlPermission = new AAFPermission(ns,type, instance, action); + PermissionStub perm; + AAFPermission aafperm; + + aafperm = new AAFPermission(ns, type, instance, action); + assertThat(controlPermission.match(aafperm), is(true)); + + perm = new PermissionStub(key); + assertThat(controlPermission.match(perm), is(true)); + + // Coverage tests + perm = new PermissionStub("not a valid key"); + assertThat(controlPermission.match(perm), is(false)); + perm = new PermissionStub("type"); + assertThat(controlPermission.match(perm), is(false)); + perm = new PermissionStub("type|instance|badAction"); + assertThat(controlPermission.match(perm), is(false)); + } + + @Test + public void coverageTest() { + AAFPermissionStub aafps = new AAFPermissionStub(); + assertThat(aafps.getNS(), is(nullValue())); + assertThat(aafps.getType(), is(nullValue())); + assertThat(aafps.getInstance(), is(nullValue())); + assertThat(aafps.getAction(), is(nullValue())); + assertThat(aafps.getKey(), is(nullValue())); + assertThat(aafps.permType(), is("AAF")); + assertThat(aafps.roles().size(), is(0)); + } + + private class PermissionStub implements Permission { + private String key; + + public PermissionStub(String key) { this.key = key; } + @Override public String permType() { return null; } + @Override public String getKey() { return key; } + @Override public boolean match(Permission p) { return false; } + } + + private class AAFPermissionStub extends AAFPermission { + + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_PermEval.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_PermEval.java index 9433cef1..297292d7 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_PermEval.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/JU_PermEval.java @@ -29,185 +29,185 @@ import org.onap.aaf.cadi.aaf.PermEval; public class JU_PermEval { - @Test - public void instanceNullTest() { - assertThat(PermEval.evalInstance(null, null), is(false)); - assertThat(PermEval.evalInstance(null, "test"), is(false)); - assertThat(PermEval.evalInstance("test", null), is(false)); - } - - @Test - public void instanceEmptyTest() { - assertThat(PermEval.evalInstance("", ""), is(false)); - assertThat(PermEval.evalInstance("", "test"), is(false)); - assertThat(PermEval.evalInstance("test", ""), is(false)); - } - - @Test - public void instanceAsterixTest() { - assertThat(PermEval.evalInstance("*", "*"), is(true)); - assertTrue(PermEval.evalInstance("*","fred")); - } - - @Test - public void instanceRegexTest() { - assertThat(PermEval.evalInstance("test", "!test"), is(true)); - assertThat(PermEval.evalInstance(",", "!"), is(true)); - assertThat(PermEval.evalInstance("test,test", "!test"), is(true)); - - assertThat(PermEval.evalInstance("test", "!"), is(false)); - assertThat(PermEval.evalInstance("test", "!mismatch"), is(false)); - assertThat(PermEval.evalInstance("test,mismatch", "!mismatch"), is(false)); - } - - @Test - public void instanceKeyTest() { - // Reject non-keys - assertThat(PermEval.evalInstance("fred", ":fred"), is(false)); - - // Reject differing number of keys - assertThat(PermEval.evalInstance(":fred:barney", ":fred"), is(false)); - assertThat(PermEval.evalInstance(":fred", ":fred:barney"), is(false)); - - // Accept all wildcard keys - assertThat(PermEval.evalInstance(":*", ":fred"), is(true)); - - // Accept matching empty keys - assertThat(PermEval.evalInstance(":", ":"), is(true)); - - // Reject non-matching empty keys - assertThat(PermEval.evalInstance(":fred", ":"), is(false)); - - // Accept matches starting with a wildcard - assertThat(PermEval.evalInstance(":!.*ed", ":fred"), is(true)); - - // Reject non-matches starting with a wildcard - assertThat(PermEval.evalInstance(":!.*arney", ":fred"), is(false)); - - // Accept matches ending with a wildcard - assertThat(PermEval.evalInstance(":fr*", ":fred"), is(true)); - - // Reject non-matches ending with a wildcard - assertThat(PermEval.evalInstance(":bar*", ":fred"), is(false)); - - // Accept exact keys - assertThat(PermEval.evalInstance(":fred", ":fred"), is(true)); - - // Reject mismatched keys - assertThat(PermEval.evalInstance(":fred", ":barney"), is(false)); - - // Check using alt-start character - assertThat(PermEval.evalInstance("/fred", "/fred"), is(true)); - assertThat(PermEval.evalInstance("/barney", "/fred"), is(false)); - } - - @Test - public void instanceDirectTest() { - assertThat(PermEval.evalInstance("fred","fred"), is(true)); - assertThat(PermEval.evalInstance("fred,wilma","fred"), is(true)); - assertThat(PermEval.evalInstance("barney,betty,fred,wilma","fred"), is(true)); - assertThat(PermEval.evalInstance("barney,betty,wilma","fred"), is(false)); - - assertThat(PermEval.evalInstance("fr*","fred"), is(true)); - assertThat(PermEval.evalInstance("freddy*","fred"), is(false)); - assertThat(PermEval.evalInstance("ba*","fred"), is(false)); - } - - @Test - public void actionTest() { - // Accept server * - assertThat(PermEval.evalAction("*", ""), is(true)); - assertThat(PermEval.evalAction("*", "literally anything"), is(true)); - - // Reject empty actions - assertThat(PermEval.evalAction("literally anything", ""), is(false)); - - // Accept match as regex - assertThat(PermEval.evalAction("action", "!action"), is(true)); - - // Reject non-match as regex - assertThat(PermEval.evalAction("action", "!nonaction"), is(false)); - - // Accept exact match - assertThat(PermEval.evalAction("action", "action"), is(true)); - - // Reject non-match - assertThat(PermEval.evalAction("action", "nonaction"), is(false)); - } - - @Test - public void redundancyTest() { - // TRUE - assertTrue(PermEval.evalInstance(":fred:fred",":fred:fred")); - assertTrue(PermEval.evalInstance(":fred:fred,wilma",":fred:fred")); - assertTrue(PermEval.evalInstance(":fred:barney,betty,fred,wilma",":fred:fred")); - assertTrue(PermEval.evalInstance(":*:fred",":fred:fred")); - assertTrue(PermEval.evalInstance(":fred:*",":fred:fred")); - assertTrue(PermEval.evalInstance(":!f.*:fred",":fred:fred")); - assertTrue(PermEval.evalInstance(":fred:!f.*",":fred:fred")); - - // FALSE - assertFalse(PermEval.evalInstance("fred","wilma")); - assertFalse(PermEval.evalInstance("fred,barney,betty","wilma")); - assertFalse(PermEval.evalInstance(":fred:fred",":fred:wilma")); - assertFalse(PermEval.evalInstance(":fred:fred",":wilma:fred")); - assertFalse(PermEval.evalInstance(":wilma:!f.*",":fred:fred")); - assertFalse(PermEval.evalInstance(":!f.*:wilma",":fred:fred")); - assertFalse(PermEval.evalInstance(":!w.*:!f.*",":fred:fred")); - assertFalse(PermEval.evalInstance(":!f.*:!w.*",":fred:fred")); - - assertFalse(PermEval.evalInstance(":fred:!x.*",":fred:fred")); - - // MSO Tests 12/3/2015 - assertFalse(PermEval.evalInstance("/v1/services/features/*","/v1/services/features")); - assertFalse(PermEval.evalInstance(":v1:services:features:*",":v1:services:features")); - assertTrue(PermEval.evalInstance("/v1/services/features/*","/v1/services/features/api1")); - assertTrue(PermEval.evalInstance(":v1:services:features:*",":v1:services:features:api2")); - // MSO - Xue Gao - assertTrue(PermEval.evalInstance(":v1:requests:*",":v1:requests:test0-service")); - - - - // Same tests, with Slashes - assertTrue(PermEval.evalInstance("/fred/fred","/fred/fred")); - assertTrue(PermEval.evalInstance("/fred/fred,wilma","/fred/fred")); - assertTrue(PermEval.evalInstance("/fred/barney,betty,fred,wilma","/fred/fred")); - assertTrue(PermEval.evalInstance("*","fred")); - assertTrue(PermEval.evalInstance("/*/fred","/fred/fred")); - assertTrue(PermEval.evalInstance("/fred/*","/fred/fred")); - assertTrue(PermEval.evalInstance("/!f.*/fred","/fred/fred")); - assertTrue(PermEval.evalInstance("/fred/!f.*","/fred/fred")); - - // FALSE - assertFalse(PermEval.evalInstance("fred","wilma")); - assertFalse(PermEval.evalInstance("fred,barney,betty","wilma")); - assertFalse(PermEval.evalInstance("/fred/fred","/fred/wilma")); - assertFalse(PermEval.evalInstance("/fred/fred","/wilma/fred")); - assertFalse(PermEval.evalInstance("/wilma/!f.*","/fred/fred")); - assertFalse(PermEval.evalInstance("/!f.*/wilma","/fred/fred")); - assertFalse(PermEval.evalInstance("/!w.*/!f.*","/fred/fred")); - assertFalse(PermEval.evalInstance("/!f.*/!w.*","/fred/fred")); - - assertFalse(PermEval.evalInstance("/fred/!x.*","/fred/fred")); - - assertTrue(PermEval.evalInstance(":!com.att.*:role:write",":com.att.temp:role:write")); - - // CPFSF-431 Group needed help with Wild Card - // They tried - assertTrue(PermEval.evalInstance( - ":topic.com.att.ecomp_test.crm.pre*", - ":topic.com.att.ecomp_test.crm.predemo100" - )); - - // Also can be - assertTrue(PermEval.evalInstance( - ":!topic.com.att.ecomp_test.crm.pre.*", - ":topic.com.att.ecomp_test.crm.predemo100" - )); - - // coverage - @SuppressWarnings("unused") - PermEval pe = new PermEval(); - } + @Test + public void instanceNullTest() { + assertThat(PermEval.evalInstance(null, null), is(false)); + assertThat(PermEval.evalInstance(null, "test"), is(false)); + assertThat(PermEval.evalInstance("test", null), is(false)); + } + + @Test + public void instanceEmptyTest() { + assertThat(PermEval.evalInstance("", ""), is(false)); + assertThat(PermEval.evalInstance("", "test"), is(false)); + assertThat(PermEval.evalInstance("test", ""), is(false)); + } + + @Test + public void instanceAsterixTest() { + assertThat(PermEval.evalInstance("*", "*"), is(true)); + assertTrue(PermEval.evalInstance("*","fred")); + } + + @Test + public void instanceRegexTest() { + assertThat(PermEval.evalInstance("test", "!test"), is(true)); + assertThat(PermEval.evalInstance(",", "!"), is(true)); + assertThat(PermEval.evalInstance("test,test", "!test"), is(true)); + + assertThat(PermEval.evalInstance("test", "!"), is(false)); + assertThat(PermEval.evalInstance("test", "!mismatch"), is(false)); + assertThat(PermEval.evalInstance("test,mismatch", "!mismatch"), is(false)); + } + + @Test + public void instanceKeyTest() { + // Reject non-keys + assertThat(PermEval.evalInstance("fred", ":fred"), is(false)); + + // Reject differing number of keys + assertThat(PermEval.evalInstance(":fred:barney", ":fred"), is(false)); + assertThat(PermEval.evalInstance(":fred", ":fred:barney"), is(false)); + + // Accept all wildcard keys + assertThat(PermEval.evalInstance(":*", ":fred"), is(true)); + + // Accept matching empty keys + assertThat(PermEval.evalInstance(":", ":"), is(true)); + + // Reject non-matching empty keys + assertThat(PermEval.evalInstance(":fred", ":"), is(false)); + + // Accept matches starting with a wildcard + assertThat(PermEval.evalInstance(":!.*ed", ":fred"), is(true)); + + // Reject non-matches starting with a wildcard + assertThat(PermEval.evalInstance(":!.*arney", ":fred"), is(false)); + + // Accept matches ending with a wildcard + assertThat(PermEval.evalInstance(":fr*", ":fred"), is(true)); + + // Reject non-matches ending with a wildcard + assertThat(PermEval.evalInstance(":bar*", ":fred"), is(false)); + + // Accept exact keys + assertThat(PermEval.evalInstance(":fred", ":fred"), is(true)); + + // Reject mismatched keys + assertThat(PermEval.evalInstance(":fred", ":barney"), is(false)); + + // Check using alt-start character + assertThat(PermEval.evalInstance("/fred", "/fred"), is(true)); + assertThat(PermEval.evalInstance("/barney", "/fred"), is(false)); + } + + @Test + public void instanceDirectTest() { + assertThat(PermEval.evalInstance("fred","fred"), is(true)); + assertThat(PermEval.evalInstance("fred,wilma","fred"), is(true)); + assertThat(PermEval.evalInstance("barney,betty,fred,wilma","fred"), is(true)); + assertThat(PermEval.evalInstance("barney,betty,wilma","fred"), is(false)); + + assertThat(PermEval.evalInstance("fr*","fred"), is(true)); + assertThat(PermEval.evalInstance("freddy*","fred"), is(false)); + assertThat(PermEval.evalInstance("ba*","fred"), is(false)); + } + + @Test + public void actionTest() { + // Accept server * + assertThat(PermEval.evalAction("*", ""), is(true)); + assertThat(PermEval.evalAction("*", "literally anything"), is(true)); + + // Reject empty actions + assertThat(PermEval.evalAction("literally anything", ""), is(false)); + + // Accept match as regex + assertThat(PermEval.evalAction("action", "!action"), is(true)); + + // Reject non-match as regex + assertThat(PermEval.evalAction("action", "!nonaction"), is(false)); + + // Accept exact match + assertThat(PermEval.evalAction("action", "action"), is(true)); + + // Reject non-match + assertThat(PermEval.evalAction("action", "nonaction"), is(false)); + } + + @Test + public void redundancyTest() { + // TRUE + assertTrue(PermEval.evalInstance(":fred:fred",":fred:fred")); + assertTrue(PermEval.evalInstance(":fred:fred,wilma",":fred:fred")); + assertTrue(PermEval.evalInstance(":fred:barney,betty,fred,wilma",":fred:fred")); + assertTrue(PermEval.evalInstance(":*:fred",":fred:fred")); + assertTrue(PermEval.evalInstance(":fred:*",":fred:fred")); + assertTrue(PermEval.evalInstance(":!f.*:fred",":fred:fred")); + assertTrue(PermEval.evalInstance(":fred:!f.*",":fred:fred")); + + // FALSE + assertFalse(PermEval.evalInstance("fred","wilma")); + assertFalse(PermEval.evalInstance("fred,barney,betty","wilma")); + assertFalse(PermEval.evalInstance(":fred:fred",":fred:wilma")); + assertFalse(PermEval.evalInstance(":fred:fred",":wilma:fred")); + assertFalse(PermEval.evalInstance(":wilma:!f.*",":fred:fred")); + assertFalse(PermEval.evalInstance(":!f.*:wilma",":fred:fred")); + assertFalse(PermEval.evalInstance(":!w.*:!f.*",":fred:fred")); + assertFalse(PermEval.evalInstance(":!f.*:!w.*",":fred:fred")); + + assertFalse(PermEval.evalInstance(":fred:!x.*",":fred:fred")); + + // MSO Tests 12/3/2015 + assertFalse(PermEval.evalInstance("/v1/services/features/*","/v1/services/features")); + assertFalse(PermEval.evalInstance(":v1:services:features:*",":v1:services:features")); + assertTrue(PermEval.evalInstance("/v1/services/features/*","/v1/services/features/api1")); + assertTrue(PermEval.evalInstance(":v1:services:features:*",":v1:services:features:api2")); + // MSO - Xue Gao + assertTrue(PermEval.evalInstance(":v1:requests:*",":v1:requests:test0-service")); + + + + // Same tests, with Slashes + assertTrue(PermEval.evalInstance("/fred/fred","/fred/fred")); + assertTrue(PermEval.evalInstance("/fred/fred,wilma","/fred/fred")); + assertTrue(PermEval.evalInstance("/fred/barney,betty,fred,wilma","/fred/fred")); + assertTrue(PermEval.evalInstance("*","fred")); + assertTrue(PermEval.evalInstance("/*/fred","/fred/fred")); + assertTrue(PermEval.evalInstance("/fred/*","/fred/fred")); + assertTrue(PermEval.evalInstance("/!f.*/fred","/fred/fred")); + assertTrue(PermEval.evalInstance("/fred/!f.*","/fred/fred")); + + // FALSE + assertFalse(PermEval.evalInstance("fred","wilma")); + assertFalse(PermEval.evalInstance("fred,barney,betty","wilma")); + assertFalse(PermEval.evalInstance("/fred/fred","/fred/wilma")); + assertFalse(PermEval.evalInstance("/fred/fred","/wilma/fred")); + assertFalse(PermEval.evalInstance("/wilma/!f.*","/fred/fred")); + assertFalse(PermEval.evalInstance("/!f.*/wilma","/fred/fred")); + assertFalse(PermEval.evalInstance("/!w.*/!f.*","/fred/fred")); + assertFalse(PermEval.evalInstance("/!f.*/!w.*","/fred/fred")); + + assertFalse(PermEval.evalInstance("/fred/!x.*","/fred/fred")); + + assertTrue(PermEval.evalInstance(":!com.att.*:role:write",":com.att.temp:role:write")); + + // CPFSF-431 Group needed help with Wild Card + // They tried + assertTrue(PermEval.evalInstance( + ":topic.com.att.ecomp_test.crm.pre*", + ":topic.com.att.ecomp_test.crm.predemo100" + )); + + // Also can be + assertTrue(PermEval.evalInstance( + ":!topic.com.att.ecomp_test.crm.pre.*", + ":topic.com.att.ecomp_test.crm.predemo100" + )); + + // coverage + @SuppressWarnings("unused") + PermEval pe = new PermEval(); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java index 2e509b0f..8cb4e906 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java @@ -40,44 +40,44 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.impl.BasicTrans; public class TestHClient { - public static void main(String[] args) { - try { - PropAccess access = new PropAccess(args); - String aaf_url = access.getProperty(Config.AAF_URL); - if(aaf_url == null) { - access.log(Level.ERROR, Config.AAF_URL," is required"); - } else { - HMangr hman = null; - try { - SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); - AbsAAFLocator loc = new AAFLocator(si,new URI(aaf_url)); - for(Item item = loc.first(); item!=null; item=loc.next(item)) { - System.out.println(loc.get(item)); - } - - hman = new HMangr(access,loc); - final String path = String.format("/authz/perms/user/%s", - access.getProperty(Config.AAF_APPID,"xx9999@people.osaaf.org")); - hman.best(si.defSS, new Retryable() { - @Override - public Void code(Rcli cli) throws APIException, CadiException { - Future ft = cli.read(path,"application/json"); - if(ft.get(10000)) { - System.out.println("Hurray,\n"+ft.body()); - } else { - System.out.println("not quite: " + ft.code()); - } - return null; - }}); - } finally { - if(hman!=null) { - hman.close(); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - + public static void main(String[] args) { + try { + PropAccess access = new PropAccess(args); + String aaf_url = access.getProperty(Config.AAF_URL); + if(aaf_url == null) { + access.log(Level.ERROR, Config.AAF_URL," is required"); + } else { + HMangr hman = null; + try { + SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); + AbsAAFLocator loc = new AAFLocator(si,new URI(aaf_url)); + for(Item item = loc.first(); item!=null; item=loc.next(item)) { + System.out.println(loc.get(item)); + } + + hman = new HMangr(access,loc); + final String path = String.format("/authz/perms/user/%s", + access.getProperty(Config.AAF_APPID,"xx9999@people.osaaf.org")); + hman.best(si.defSS, new Retryable() { + @Override + public Void code(Rcli cli) throws APIException, CadiException { + Future ft = cli.read(path,"application/json"); + if(ft.get(10000)) { + System.out.println("Hurray,\n"+ft.body()); + } else { + System.out.println("not quite: " + ft.code()); + } + return null; + }}); + } finally { + if(hman!=null) { + hman.close(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java index 4d767c9c..c76d178f 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java @@ -56,68 +56,68 @@ import locate.v1_0.Endpoint; import locate.v1_0.Endpoints; public class JU_AAFLocator { - - @Mock private HClient clientMock; - @Mock private Future futureMock; - @Mock private Endpoints endpointsMock; - - private PropAccess access; - - private ByteArrayOutputStream errStream; - - private static final String uriString = "https://example.com"; + + @Mock private HClient clientMock; + @Mock private Future futureMock; + @Mock private Endpoints endpointsMock; + + private PropAccess access; + + private ByteArrayOutputStream errStream; + + private static final String uriString = "https://example.com"; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - - doReturn(futureMock).when(clientMock).futureRead((RosettaDF)any(), eq(TYPE.JSON)); - when(clientMock.timeout()).thenReturn(1); - when(clientMock.getURI()).thenReturn(new URI(uriString)); - when(futureMock.get(1)).thenReturn(true); - - futureMock.value = endpointsMock; - List endpoints = new ArrayList<>(); - endpoints.add(new Endpoint()); - when(endpointsMock.getEndpoint()).thenReturn(endpoints); + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + doReturn(futureMock).when(clientMock).futureRead((RosettaDF)any(), eq(TYPE.JSON)); + when(clientMock.timeout()).thenReturn(1); + when(clientMock.getURI()).thenReturn(new URI(uriString)); + when(futureMock.get(1)).thenReturn(true); + + futureMock.value = endpointsMock; + List endpoints = new ArrayList<>(); + endpoints.add(new Endpoint()); + when(endpointsMock.getEndpoint()).thenReturn(endpoints); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - - errStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + + errStream = new ByteArrayOutputStream(); - System.setErr(new PrintStream(errStream)); - } - - @After - public void tearDown() { - System.setErr(System.err); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - Field field = SecurityInfoC.class.getDeclaredField("sicMap"); - field.setAccessible(true); - field.set(null, new HashMap<>()); - } + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + Field field = SecurityInfoC.class.getDeclaredField("sicMap"); + field.setAccessible(true); + field.set(null, new HashMap<>()); + } - @Test - public void test() throws CadiException, URISyntaxException, LocatorException { - access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat - access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon - SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); - URI locatorURI = new URI("https://somemachine.moc:10/com.att.aaf.service:2.0"); -// AbsAAFLocator al = new AAFLocator(si, locatorURI) { -// @Override -// protected HClient createClient(SecuritySetter ss, URI uri, int connectTimeout) throws LocatorException { -// return clientMock; -// } -// }; - // Start over: This was originally calling a developer machine. -// assertThat(al.refresh(), is(true)); -// when(futureMock.get(1)).thenReturn(false); -// assertThat(al.refresh(), is(false)); -// String errorMessage = errStream.toString().split(": ", 2)[1]; -// assertThat(errorMessage, is("Error reading location information from " + uriString + ": 0 null\n \n")); - } + @Test + public void test() throws CadiException, URISyntaxException, LocatorException { + access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat + access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon + SecurityInfoC si = SecurityInfoC.instance(access, HttpURLConnection.class); + URI locatorURI = new URI("https://somemachine.moc:10/com.att.aaf.service:2.0"); +// AbsAAFLocator al = new AAFLocator(si, locatorURI) { +// @Override +// protected HClient createClient(SecuritySetter ss, URI uri, int connectTimeout) throws LocatorException { +// return clientMock; +// } +// }; + // Start over: This was originally calling a developer machine. +// assertThat(al.refresh(), is(true)); +// when(futureMock.get(1)).thenReturn(false); +// assertThat(al.refresh(), is(false)); +// String errorMessage = errStream.toString().split(": ", 2)[1]; +// assertThat(errorMessage, is("Error reading location information from " + uriString + ": 0 null\n \n")); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java index 1e469eca..64f4c997 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java @@ -47,84 +47,84 @@ import org.onap.aaf.misc.env.Env; public class JU_AAFTrustChecker { - private final static String type = "type"; - private final static String instance = "instance"; - private final static String action = "action"; - private final static String key = type + '|' + instance + '|' + action; - private final static String name = "name"; - private final static String otherName = "otherName"; - - private PropAccess access; - - @Mock private Env envMock; - @Mock private TafResp trespMock; - @Mock private HttpServletRequest reqMock; - @Mock private TaggedPrincipal tpMock; - @Mock private Lur lurMock; - @Mock private TaggedPrincipal princMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() { - AAFTrustChecker trustChecker; - - // coverage calls - trustChecker = new AAFTrustChecker(access); - trustChecker = new AAFTrustChecker(envMock); - - access.setProperty(Config.CADI_TRUST_PERM, "example"); - when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn("example"); - trustChecker = new AAFTrustChecker(access); - trustChecker = new AAFTrustChecker(envMock); - - access.setProperty(Config.CADI_TRUST_PERM, key); - when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(key); - trustChecker = new AAFTrustChecker(access); - trustChecker = new AAFTrustChecker(envMock); - - trustChecker.setLur(lurMock); - - assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); - - when(reqMock.getHeader(null)).thenReturn("comma,comma,comma"); - assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); - - when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:colon,comma,comma"); - assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); - - when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:AS,comma,comma"); - when(trespMock.getPrincipal()).thenReturn(tpMock); - when(tpMock.getName()).thenReturn(name); - when(lurMock.fish(princMock, null)).thenReturn(true); - TafResp tntResp = trustChecker.mayTrust(trespMock, reqMock); - - assertThat(tntResp instanceof TrustNotTafResp, is(true)); - assertThat(tntResp.toString(), is("name requested trust as colon, but does not have Authorization")); - - when(reqMock.getHeader(null)).thenReturn(name + ":colon:colon:AS,comma,comma"); - assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); - - when(envMock.getProperty(Config.CADI_ALIAS, null)).thenReturn(name); - when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(null); - trustChecker = new AAFTrustChecker(envMock); - trustChecker.setLur(lurMock); - - when(trespMock.getPrincipal()).thenReturn(princMock); - when(princMock.getName()).thenReturn(otherName); - when(lurMock.fish(princMock, null)).thenReturn(true); - TafResp ttResp = trustChecker.mayTrust(trespMock, reqMock); - assertThat(ttResp instanceof TrustTafResp, is(true)); - assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null")); - - when(princMock.getName()).thenReturn(name); - ttResp = trustChecker.mayTrust(trespMock, reqMock); - assertThat(ttResp instanceof TrustTafResp, is(true)); - assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null")); - } + private final static String type = "type"; + private final static String instance = "instance"; + private final static String action = "action"; + private final static String key = type + '|' + instance + '|' + action; + private final static String name = "name"; + private final static String otherName = "otherName"; + + private PropAccess access; + + @Mock private Env envMock; + @Mock private TafResp trespMock; + @Mock private HttpServletRequest reqMock; + @Mock private TaggedPrincipal tpMock; + @Mock private Lur lurMock; + @Mock private TaggedPrincipal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() { + AAFTrustChecker trustChecker; + + // coverage calls + trustChecker = new AAFTrustChecker(access); + trustChecker = new AAFTrustChecker(envMock); + + access.setProperty(Config.CADI_TRUST_PERM, "example"); + when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn("example"); + trustChecker = new AAFTrustChecker(access); + trustChecker = new AAFTrustChecker(envMock); + + access.setProperty(Config.CADI_TRUST_PERM, key); + when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(key); + trustChecker = new AAFTrustChecker(access); + trustChecker = new AAFTrustChecker(envMock); + + trustChecker.setLur(lurMock); + + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(reqMock.getHeader(null)).thenReturn("comma,comma,comma"); + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:colon,comma,comma"); + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:AS,comma,comma"); + when(trespMock.getPrincipal()).thenReturn(tpMock); + when(tpMock.getName()).thenReturn(name); + when(lurMock.fish(princMock, null)).thenReturn(true); + TafResp tntResp = trustChecker.mayTrust(trespMock, reqMock); + + assertThat(tntResp instanceof TrustNotTafResp, is(true)); + assertThat(tntResp.toString(), is("name requested trust as colon, but does not have Authorization")); + + when(reqMock.getHeader(null)).thenReturn(name + ":colon:colon:AS,comma,comma"); + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(envMock.getProperty(Config.CADI_ALIAS, null)).thenReturn(name); + when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(null); + trustChecker = new AAFTrustChecker(envMock); + trustChecker.setLur(lurMock); + + when(trespMock.getPrincipal()).thenReturn(princMock); + when(princMock.getName()).thenReturn(otherName); + when(lurMock.fish(princMock, null)).thenReturn(true); + TafResp ttResp = trustChecker.mayTrust(trespMock, reqMock); + assertThat(ttResp instanceof TrustTafResp, is(true)); + assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null")); + + when(princMock.getName()).thenReturn(name); + ttResp = trustChecker.mayTrust(trespMock, reqMock); + assertThat(ttResp instanceof TrustTafResp, is(true)); + assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null")); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java index e9c74cbf..825e3c91 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java @@ -44,150 +44,150 @@ import org.onap.aaf.misc.env.impl.BasicTrans; public class JU_AbsAAFLocator { - @Mock private LocatorCreator locatorCreatorMock; - - private PropAccess access; - private URI uri; - - private static final String uriString = "example.com"; - - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat - access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon - - uri = new URI(uriString); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - AbsAAFLocator.setCreator(null); - } - - @Test - public void test() throws LocatorException { - AAFLocatorStub loc; - - // Test with http - loc = new AAFLocatorStub(access, "httpname"); - assertThat(loc.getName(), is("httpname")); - assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION)); - assertThat(loc.toString(), is("AAFLocator for " + "httpname" + " on " + loc.getURI())); - - loc = new AAFLocatorStub(access, "name"); - assertThat(loc.getName(), is("name")); - assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION)); - loc = new AAFLocatorStub(access, "name:v2.0"); - assertThat(loc.getName(), is("name")); - assertThat(loc.getVersion(), is("v2.0")); - } - - @Test - public void createTest() throws LocatorException { - AbsAAFLocator.setCreator(locatorCreatorMock); - - assertThat(AbsAAFLocator.create("nonsense"), is(nullValue())); - assertThat(AbsAAFLocator.create("nonsense/locate"), is(nullValue())); - assertThat(AbsAAFLocator.create("nonsense/locate/"), is(nullValue())); - assertThat(AbsAAFLocator.create("nonsense/locate//"), is(nullValue())); - assertThat(AbsAAFLocator.create("nonsense/locate/name:v2.0"), is(nullValue())); - - assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue())); - - doReturn(mock(AbsAAFLocator.class)).when(locatorCreatorMock).create(anyString(), anyString()); - assertThat(AbsAAFLocator.create("http/locate/name:v2.0/path"), is(not(nullValue()))); - - AbsAAFLocator.setCreator(null); - assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue())); - - assertThat(AbsAAFLocator.create("http"), is(not(nullValue()))); - - AbsAAFLocator.setCreator(locatorCreatorMock); - assertThat(AbsAAFLocator.create("first", "second"), is(not(nullValue()))); - } - - @Test - public void nameFromLocatorURITest() throws LocatorException, URISyntaxException { - AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0"); - assertThat(loc.getNameFromURI(new URI("example.com")), is("example.com")); - assertThat(loc.getNameFromURI(new URI("example.com/extra/stuff")), is("example.com/extra/stuff")); - assertThat(loc.getNameFromURI(new URI("example.com/locate/stuff")), is("stuff")); // n' stuff - } - - @Test - public void setSelfTest() throws LocatorException { - AbsAAFLocator.setCreatorSelf("host", 8000); - AbsAAFLocator.setCreator(null); - AbsAAFLocator.setCreatorSelf("host", 8000); - (new AAFLocatorStub(access, "name:v2.0")).setSelf("host", 8000); // oof - } - - @Test - public void coverage() throws LocatorException { - AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0"); - assertThat(loc.get(null), is(nullValue())); - - try { - loc.get(mock(Item.class)); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - - try { - loc.invalidate(mock(Item.class)); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - - try { - loc.best(); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - - assertThat(loc.first(), is(nullValue())); - - assertThat(loc.hasItems(), is(false)); - assertThat(loc.next(null), is(nullValue())); - - try { - loc.next(mock(Item.class)); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - - loc.destroy(); - - - assertThat(loc.exposeGetURI(uri), is(uri)); - - assertThat(loc.setPathInfo("pathInfo"), is(not(nullValue()))); - assertThat(loc.setQuery("query"), is(not(nullValue()))); - assertThat(loc.setFragment("fragment"), is(not(nullValue()))); - - assertThat(loc.exposeGetURI(uri), is(not(uri))); - } - - - @Test(expected = LocatorException.class) - public void throwsTest() throws LocatorException { - @SuppressWarnings("unused") - AAFLocatorStub loc = new AAFLocatorStub(new PropAccess(), "name"); - } - - private class AAFLocatorStub extends AbsAAFLocator { - public AAFLocatorStub(Access access, String name) throws LocatorException { - super(access, name, 10000L); - } - @Override public boolean refresh() { return false; } - @Override protected URI getURI() { return uri; } - public String getName() { return name; } - public String getVersion() { return version; } - public String getNameFromURI(URI uri) { return nameFromLocatorURI(uri); } - public URI exposeGetURI(URI uri) throws LocatorException { return super.getURI(uri); } - } + @Mock private LocatorCreator locatorCreatorMock; + + private PropAccess access; + private URI uri; + + private static final String uriString = "example.com"; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat + access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon + + uri = new URI(uriString); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + AbsAAFLocator.setCreator(null); + } + + @Test + public void test() throws LocatorException { + AAFLocatorStub loc; + + // Test with http + loc = new AAFLocatorStub(access, "httpname"); + assertThat(loc.getName(), is("httpname")); + assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION)); + assertThat(loc.toString(), is("AAFLocator for " + "httpname" + " on " + loc.getURI())); + + loc = new AAFLocatorStub(access, "name"); + assertThat(loc.getName(), is("name")); + assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION)); + loc = new AAFLocatorStub(access, "name:v2.0"); + assertThat(loc.getName(), is("name")); + assertThat(loc.getVersion(), is("v2.0")); + } + + @Test + public void createTest() throws LocatorException { + AbsAAFLocator.setCreator(locatorCreatorMock); + + assertThat(AbsAAFLocator.create("nonsense"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate/"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate//"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate/name:v2.0"), is(nullValue())); + + assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue())); + + doReturn(mock(AbsAAFLocator.class)).when(locatorCreatorMock).create(anyString(), anyString()); + assertThat(AbsAAFLocator.create("http/locate/name:v2.0/path"), is(not(nullValue()))); + + AbsAAFLocator.setCreator(null); + assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue())); + + assertThat(AbsAAFLocator.create("http"), is(not(nullValue()))); + + AbsAAFLocator.setCreator(locatorCreatorMock); + assertThat(AbsAAFLocator.create("first", "second"), is(not(nullValue()))); + } + + @Test + public void nameFromLocatorURITest() throws LocatorException, URISyntaxException { + AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0"); + assertThat(loc.getNameFromURI(new URI("example.com")), is("example.com")); + assertThat(loc.getNameFromURI(new URI("example.com/extra/stuff")), is("example.com/extra/stuff")); + assertThat(loc.getNameFromURI(new URI("example.com/locate/stuff")), is("stuff")); // n' stuff + } + + @Test + public void setSelfTest() throws LocatorException { + AbsAAFLocator.setCreatorSelf("host", 8000); + AbsAAFLocator.setCreator(null); + AbsAAFLocator.setCreatorSelf("host", 8000); + (new AAFLocatorStub(access, "name:v2.0")).setSelf("host", 8000); // oof + } + + @Test + public void coverage() throws LocatorException { + AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0"); + assertThat(loc.get(null), is(nullValue())); + + try { + loc.get(mock(Item.class)); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + try { + loc.invalidate(mock(Item.class)); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + try { + loc.best(); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + assertThat(loc.first(), is(nullValue())); + + assertThat(loc.hasItems(), is(false)); + assertThat(loc.next(null), is(nullValue())); + + try { + loc.next(mock(Item.class)); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + loc.destroy(); + + + assertThat(loc.exposeGetURI(uri), is(uri)); + + assertThat(loc.setPathInfo("pathInfo"), is(not(nullValue()))); + assertThat(loc.setQuery("query"), is(not(nullValue()))); + assertThat(loc.setFragment("fragment"), is(not(nullValue()))); + + assertThat(loc.exposeGetURI(uri), is(not(uri))); + } + + + @Test(expected = LocatorException.class) + public void throwsTest() throws LocatorException { + @SuppressWarnings("unused") + AAFLocatorStub loc = new AAFLocatorStub(new PropAccess(), "name"); + } + + private class AAFLocatorStub extends AbsAAFLocator { + public AAFLocatorStub(Access access, String name) throws LocatorException { + super(access, name, 10000L); + } + @Override public boolean refresh() { return false; } + @Override protected URI getURI() { return uri; } + public String getName() { return name; } + public String getVersion() { return version; } + public String getNameFromURI(URI uri) { return nameFromLocatorURI(uri); } + public URI exposeGetURI(URI uri) throws LocatorException { return super.getURI(uri); } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java index d50b87a2..70550451 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java @@ -52,112 +52,112 @@ import certman.v1_0.CertInfo; public class JU_ArtifactDir { - @Mock private Trans transMock; - @Mock private CertInfo certInfoMock; - @Mock private Artifact artiMock; - - private static final String dirName = "src/test/resources/artifacts"; - private static final String nsName = "org.onap.test"; - private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life - - private List issuers; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - issuers = new ArrayList<>(); - issuers.add("issuer1"); - issuers.add("issuer2"); - } - - @After - public void tearDown() { - ArtifactDir.clear(); - } - - @AfterClass - public static void tearDownOnce() { - cleanup(); - } - - @Test - public void test() throws CadiException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { - ArtifactDirStud artiDir = new ArtifactDirStud(); - - try { - artiDir.place(transMock, certInfoMock, artiMock, "machine"); - fail("Should've thrown an exception"); - } catch (CadiException e) { - assertThat(e.getMessage(), is("File Artifacts require a path\nFile Artifacts require an AAF Namespace")); - } - - when(artiMock.getDir()).thenReturn(dirName); - try { - artiDir.place(transMock, certInfoMock, artiMock, "machine"); - fail("Should've thrown an exception"); - } catch (CadiException e) { - assertThat(e.getMessage(), is("File Artifacts require an AAF Namespace")); - } - - when(artiMock.getNs()).thenReturn(nsName); - when(certInfoMock.getCaIssuerDNs()).thenReturn(issuers); - when(certInfoMock.getChallenge()).thenReturn(luggagePassword); - artiDir.place(transMock, certInfoMock, artiMock, "machine"); - - File writableFile = new File(dirName + '/' + nsName + "writable.txt"); - ArtifactDir.write(writableFile, Chmod.to755, "first data point", "second data point"); - try { - ArtifactDir.write(writableFile, Chmod.to755, (String[])null); - fail("Should've thrown an exception"); - } catch(NullPointerException e) { - } - - KeyStore ks = KeyStore.getInstance(Agent.PKCS12); - try { - ArtifactDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray()); - fail("Should've thrown an exception"); - } catch(CadiException e) { - } - - ks.load(null, null); - ArtifactDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray()); - - ArtifactDirStud artiDir2 = new ArtifactDirStud(); - artiDir2.place(transMock, certInfoMock, artiMock, "machine"); - - // coverage - artiDir.place(transMock, certInfoMock, artiMock, "machine"); - - ArtifactDir.clear(); - artiDir.place(transMock, certInfoMock, artiMock, "machine"); - - } - - @Test(expected = CadiException.class) - public void throwsTest() throws CadiException { - ArtifactDirStud artiDir = new ArtifactDirStud(); - when(artiMock.getDir()).thenReturn(dirName); - when(artiMock.getNs()).thenReturn(nsName); - artiDir.place(transMock, certInfoMock, artiMock, "machine"); - } - - private class ArtifactDirStud extends ArtifactDir { - @Override - protected boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { - // This is only here so that we have a concrete class to test - return false; - } - } - - private static void cleanup() { - File dir = new File(dirName); - if (dir.exists()) { - for (File f : dir.listFiles()) { - f.delete(); - } - dir.delete(); - } - } + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + + private List issuers; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + issuers = new ArrayList<>(); + issuers.add("issuer1"); + issuers.add("issuer2"); + } + + @After + public void tearDown() { + ArtifactDir.clear(); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + } + + @Test + public void test() throws CadiException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { + ArtifactDirStud artiDir = new ArtifactDirStud(); + + try { + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("File Artifacts require a path\nFile Artifacts require an AAF Namespace")); + } + + when(artiMock.getDir()).thenReturn(dirName); + try { + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("File Artifacts require an AAF Namespace")); + } + + when(artiMock.getNs()).thenReturn(nsName); + when(certInfoMock.getCaIssuerDNs()).thenReturn(issuers); + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + + File writableFile = new File(dirName + '/' + nsName + "writable.txt"); + ArtifactDir.write(writableFile, Chmod.to755, "first data point", "second data point"); + try { + ArtifactDir.write(writableFile, Chmod.to755, (String[])null); + fail("Should've thrown an exception"); + } catch(NullPointerException e) { + } + + KeyStore ks = KeyStore.getInstance(Agent.PKCS12); + try { + ArtifactDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray()); + fail("Should've thrown an exception"); + } catch(CadiException e) { + } + + ks.load(null, null); + ArtifactDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray()); + + ArtifactDirStud artiDir2 = new ArtifactDirStud(); + artiDir2.place(transMock, certInfoMock, artiMock, "machine"); + + // coverage + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + + ArtifactDir.clear(); + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + + } + + @Test(expected = CadiException.class) + public void throwsTest() throws CadiException { + ArtifactDirStud artiDir = new ArtifactDirStud(); + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + } + + private class ArtifactDirStud extends ArtifactDir { + @Override + protected boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { + // This is only here so that we have a concrete class to test + return false; + } + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CertException.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CertException.java index a973bc22..80c1f880 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CertException.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CertException.java @@ -28,22 +28,22 @@ import org.onap.aaf.cadi.configure.CertException; public class JU_CertException { - private static final String message = "The message associated with the exception"; + private static final String message = "The message associated with the exception"; - @Test(expected = CertException.class) - public void test() throws CertException { - CertException except; + @Test(expected = CertException.class) + public void test() throws CertException { + CertException except; - except = new CertException(message); - assertThat(except.getMessage(), is(message)); + except = new CertException(message); + assertThat(except.getMessage(), is(message)); - except = new CertException(new Exception(message)); - assertThat(except.getMessage(), is("java.lang.Exception: " + message)); + except = new CertException(new Exception(message)); + assertThat(except.getMessage(), is("java.lang.Exception: " + message)); - except = new CertException(message, new Exception(message)); - assertThat(except.getMessage(), is(message)); + except = new CertException(message, new Exception(message)); + assertThat(except.getMessage(), is(message)); - throw new CertException(); - } + throw new CertException(); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java index b50c5a5e..e1c334ff 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java @@ -32,99 +32,99 @@ import org.onap.aaf.cadi.configure.Agent; public class JU_CmAgent { - private static final String resourceDirString = "src/test/resources"; - private static final String aafDir = resourceDirString + "/aaf"; - - private ByteArrayInputStream inStream; - - @Before - public void setup() { - System.setProperty("user.home", aafDir); - - // Simulate user input - inStream = new ByteArrayInputStream("test\nhttp://example.com\nhttp://example.com".getBytes()); - System.setIn(inStream); - } - - @After - public void tearDown() { - recursiveDelete(new File(aafDir)); - } - - @Test - public void test() { - String[] args; - args = new String[] { - "-login", - "-noExit", - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "-noExit", - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "place", - "-noExit", - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "-noExit", - "create" - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "-noExit", - "read" - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "-noExit", - "copy" - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "-noExit", - "update" - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "-noExit", - "delete" - }; - Agent.main(args); - - inStream.reset(); - args = new String[] { - "-noExit", - "showpass" - }; - Agent.main(args); - - } - - private void recursiveDelete(File file) { - for (File f : file.listFiles()) { - if (f.isDirectory()) { - recursiveDelete(f); - } - f.delete(); - } - file.delete(); - } + private static final String resourceDirString = "src/test/resources"; + private static final String aafDir = resourceDirString + "/aaf"; + + private ByteArrayInputStream inStream; + + @Before + public void setup() { + System.setProperty("user.home", aafDir); + + // Simulate user input + inStream = new ByteArrayInputStream("test\nhttp://example.com\nhttp://example.com".getBytes()); + System.setIn(inStream); + } + + @After + public void tearDown() { + recursiveDelete(new File(aafDir)); + } + + @Test + public void test() { + String[] args; + args = new String[] { + "-login", + "-noExit", + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "-noExit", + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "place", + "-noExit", + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "-noExit", + "create" + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "-noExit", + "read" + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "-noExit", + "copy" + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "-noExit", + "update" + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "-noExit", + "delete" + }; + Agent.main(args); + + inStream.reset(); + args = new String[] { + "-noExit", + "showpass" + }; + Agent.main(args); + + } + + private void recursiveDelete(File file) { + for (File f : file.listFiles()) { + if (f.isDirectory()) { + recursiveDelete(f); + } + f.delete(); + } + file.delete(); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java index 5827e8c0..76c31b8d 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java @@ -68,299 +68,299 @@ import org.onap.aaf.misc.env.Trans; public class JU_Factory { - private static final String message = "The quick brown fox jumps over the lazy dog."; - private static final String subjectDNText = "subjectDN"; - private static final String certText = "Some text that might be included in a certificate"; - private static final String resourceDirName = "src/test/resources"; - - private File resourceDir; - private File publicKeyFile; - private File privateKeyFile; - private File certFile; - - @Mock private Trans transMock; - @Mock private TimeTaken timeTakenMock; - @Mock private LogTarget logTargetMock; - @Mock private X509Certificate x509CertMock; - @Mock private Certificate certMock; - @Mock private Principal subjectDN; - - - @Before - public void setup() throws CertificateEncodingException { - MockitoAnnotations.initMocks(this); - - resourceDir = new File(resourceDirName); - resourceDir.mkdirs(); - publicKeyFile = new File(resourceDirName, "/publicKey"); - privateKeyFile = new File(resourceDirName, "/privateKey"); - publicKeyFile.delete(); - privateKeyFile.delete(); - - certFile = new File(resourceDirName + "/exampleCertificate.cer"); - - when(transMock.start(anyString(), anyInt())).thenReturn(timeTakenMock); - when(transMock.debug()).thenReturn(logTargetMock); - - when(subjectDN.toString()).thenReturn(subjectDNText); - - when(x509CertMock.getSubjectDN()).thenReturn(subjectDN); - when(x509CertMock.getEncoded()).thenReturn(certText.getBytes()); - - when(certMock.getEncoded()).thenReturn(certText.getBytes()); - } - - @After - public void tearDown() { - publicKeyFile = new File(resourceDirName, "/publicKey"); - privateKeyFile = new File(resourceDirName, "/privateKey"); - publicKeyFile.delete(); - privateKeyFile.delete(); - } - - @Test - public void generateKeyPairTest() throws Exception { - // This instatiation isn't actually necessary, but it gets coverage - Cipher encryptor = Factory.pkCipher(); - Cipher decryptor = Factory.pkCipher(); - - KeyPair kp1 = Factory.generateKeyPair(transMock); - encryptor = Factory.pkCipher(kp1.getPublic(), true); - decryptor = Factory.pkCipher(kp1.getPrivate(), false); - byte[] encrypedMessage1 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); - String output1 = new String(decryptor.doFinal(encrypedMessage1)); - assertThat(output1, is(message)); - - // coverage - when(transMock.start("Generate KeyPair", Env.SUB)).thenReturn(null); - KeyPair kp2 = Factory.generateKeyPair(transMock); - encryptor = Factory.pkCipher(kp2.getPublic(), true); - decryptor = Factory.pkCipher(kp2.getPrivate(), false); - byte[] encrypedMessage2 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); - String output2 = new String(decryptor.doFinal(encrypedMessage2)); - assertThat(output2, is(message)); - - KeyPair kp3 = Factory.generateKeyPair(null); - encryptor = Factory.pkCipher(kp3.getPublic(), true); - decryptor = Factory.pkCipher(kp3.getPrivate(), false); - byte[] encrypedMessage3 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); - String output3 = new String(decryptor.doFinal(encrypedMessage3)); - assertThat(output3, is(message)); - } - - @Test - public void keyStringManipTest() throws Exception { - KeyPair kp = Factory.generateKeyPair(transMock); - - String publicKeyString = Factory.toString(transMock, kp.getPublic()); - String privateKeyString = Factory.toString(transMock, kp.getPrivate()); - - assertThat(publicKeyString.startsWith("-----BEGIN PUBLIC KEY-----"), is(true)); - assertThat(publicKeyString.endsWith("-----END PUBLIC KEY-----\n"), is(true)); - - assertThat(privateKeyString.startsWith("-----BEGIN PRIVATE KEY-----"), is(true)); - assertThat(privateKeyString.endsWith("-----END PRIVATE KEY-----\n"), is(true)); - - PublicKey publicKey = Factory.toPublicKey(transMock, publicKeyString); - PrivateKey privateKey = Factory.toPrivateKey(transMock, privateKeyString); - - Cipher encryptor = Factory.pkCipher(publicKey, true); - Cipher decryptor = Factory.pkCipher(privateKey, false); - byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); - String output = new String(decryptor.doFinal(encrypedMessage)); - assertThat(output, is(message)); - } - - @Test - public void keyFileManipTest() throws Exception { - KeyPair kp = Factory.generateKeyPair(transMock); - - String privateKeyString = Factory.toString(transMock, kp.getPrivate()); - writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header"); - - PublicKey publicKey = kp.getPublic(); - PrivateKey privateKey = Factory.toPrivateKey(transMock, privateKeyFile); - - Cipher encryptor = Factory.pkCipher(publicKey, true); - Cipher decryptor = Factory.pkCipher(privateKey, false); - byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); - String output = new String(decryptor.doFinal(encrypedMessage)); - assertThat(output, is(message)); - } - - @Test - public void certToStringTest() throws IOException, CertException, CertificateEncodingException { - String certString; - when(logTargetMock.isLoggable()).thenReturn(true); - - certString = Factory.toString(transMock, x509CertMock); - assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true)); - assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true)); - - certString = Factory.toString(transMock, certMock); - assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true)); - assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true)); - - try { - certString = Factory.toString(transMock, (Certificate)null); - fail("Should have thrown an exception"); - } catch (CertException e) { - assertThat(e.getMessage(), is("Certificate not built")); - } - - when(certMock.getEncoded()).thenThrow(new CertificateEncodingException()); - try { - certString = Factory.toString(transMock, certMock); - fail("Should have thrown an exception"); - } catch (CertException e) { - } - - // coverage - when(logTargetMock.isLoggable()).thenReturn(false); - certString = Factory.toString(transMock, x509CertMock); - } - - @Test - public void toX509Test() throws CertificateException, IOException, CertException { - String output; - Collection certs; - when(logTargetMock.isLoggable()).thenReturn(true); - - String certString = readFromFile(certFile, false); - - certs = Factory.toX509Certificate(certString); - // Contrived way of getting a Certificate out of a Collection - output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]); - assertThat(output, is(certString)); - - certs = Factory.toX509Certificate(transMock, certFile); - // Contrived way of getting a Certificate out of a Collection - output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]); - assertThat(output, is(certString)); - - List certStrings = new ArrayList<>(); - certStrings.add(certString); - certStrings.add(certString); - certs = Factory.toX509Certificate(certStrings); - // Contrived way of getting a Certificate out of a Collection - // it doesn't matter which one we get - they're the same - output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]); - assertThat(output, is(certString)); - } - - @Test - public void stripperTest() throws Exception { - KeyPair kp = Factory.generateKeyPair(transMock); - String privateKeyString = Factory.toString(transMock, kp.getPrivate()); - writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header"); - - StripperInputStream stripper = new StripperInputStream(privateKeyFile); - - String expected = cleanupString(privateKeyString); - byte[] buffer = new byte[10000]; - stripper.read(buffer); - String output = new String(buffer, 0, expected.length()); - assertThat(output, is(expected)); - stripper.close(); - - // coverage - stripper = new StripperInputStream(new FileInputStream(privateKeyFile)); - stripper.close(); - stripper = new StripperInputStream(new BufferedReader(new FileReader(privateKeyFile))); - stripper.close(); - stripper.close(); // also coverage... - } - - @Test - public void binaryTest() throws IOException { - String output = new String(Factory.binary(certFile)); - String expected = readFromFile(certFile, true); - assertThat(output, is(expected)); - } - - @Test - public void signatureTest() throws Exception { - KeyPair kp = Factory.generateKeyPair(transMock); - String signedString = "Something that needs signing"; - byte[] signedBytes = Factory.sign(transMock, signedString.getBytes(), kp.getPrivate()); - String output = Factory.toSignatureString(signedBytes); - assertThat(output.startsWith("-----BEGIN SIGNATURE-----"), is(true)); - assertThat(output.endsWith("-----END SIGNATURE-----\n"), is(true)); - assertThat(Factory.verify(transMock, signedString.getBytes(), signedBytes, kp.getPublic()), is(true)); - } - - @Test - public void base64ISTest() throws Exception { - KeyPair kp = Factory.generateKeyPair(transMock); - - String privateKeyString = Factory.toString(transMock, kp.getPrivate()); - String cleaned = cleanupString(privateKeyString); - writeToFile(privateKeyFile, cleaned, null); - Base64InputStream b64is = new Base64InputStream(privateKeyFile); - byte[] buffer = new byte[10000]; - b64is.read(buffer); - b64is.close(); - - FileInputStream fis = new FileInputStream(privateKeyFile); - b64is = new Base64InputStream(fis); - b64is.close(); - fis.close(); - } - - @Test - public void getSecurityProviderTest() throws CertException { - String[][] params = { - {"test", "test"}, - {"test", "test"}, - }; - assertThat(Factory.getSecurityProvider("PKCS12", params), is(nullValue())); - } - - private String cleanupString(String str) { - String[] lines = str.split("\n", 0); - List rawLines = new ArrayList<>(); - for (int i = 0; i < lines.length - 2; i++) { - rawLines.add(lines[i + 1]); - } - return join("", rawLines); - } - - /** - * Note: String.join is not part of JDK 7, which is what we compile to for CADI - */ - private String join(String delim, List rawLines) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for(String s : rawLines) { - if(first) { - first = false; - } else { - sb.append(delim); - } - sb.append(s); - } - return sb.toString(); - } - - private void writeToFile(File file, String contents, String header) throws Exception { - PrintWriter writer = new PrintWriter(file, "UTF-8"); - if (header != null) { - writer.println(header); - } - writer.println(contents); - writer.close(); - } - - private String readFromFile(File file, boolean addCR) throws IOException { - BufferedReader br = new BufferedReader(new FileReader(file)); - StringBuilder sb = new StringBuilder(); - String line; - while ((line = br.readLine()) != null) { - String lineEnd = (addCR) ? "\r\n" : "\n"; - sb.append(line + lineEnd); - } - br.close(); - return sb.toString(); - } + private static final String message = "The quick brown fox jumps over the lazy dog."; + private static final String subjectDNText = "subjectDN"; + private static final String certText = "Some text that might be included in a certificate"; + private static final String resourceDirName = "src/test/resources"; + + private File resourceDir; + private File publicKeyFile; + private File privateKeyFile; + private File certFile; + + @Mock private Trans transMock; + @Mock private TimeTaken timeTakenMock; + @Mock private LogTarget logTargetMock; + @Mock private X509Certificate x509CertMock; + @Mock private Certificate certMock; + @Mock private Principal subjectDN; + + + @Before + public void setup() throws CertificateEncodingException { + MockitoAnnotations.initMocks(this); + + resourceDir = new File(resourceDirName); + resourceDir.mkdirs(); + publicKeyFile = new File(resourceDirName, "/publicKey"); + privateKeyFile = new File(resourceDirName, "/privateKey"); + publicKeyFile.delete(); + privateKeyFile.delete(); + + certFile = new File(resourceDirName + "/exampleCertificate.cer"); + + when(transMock.start(anyString(), anyInt())).thenReturn(timeTakenMock); + when(transMock.debug()).thenReturn(logTargetMock); + + when(subjectDN.toString()).thenReturn(subjectDNText); + + when(x509CertMock.getSubjectDN()).thenReturn(subjectDN); + when(x509CertMock.getEncoded()).thenReturn(certText.getBytes()); + + when(certMock.getEncoded()).thenReturn(certText.getBytes()); + } + + @After + public void tearDown() { + publicKeyFile = new File(resourceDirName, "/publicKey"); + privateKeyFile = new File(resourceDirName, "/privateKey"); + publicKeyFile.delete(); + privateKeyFile.delete(); + } + + @Test + public void generateKeyPairTest() throws Exception { + // This instatiation isn't actually necessary, but it gets coverage + Cipher encryptor = Factory.pkCipher(); + Cipher decryptor = Factory.pkCipher(); + + KeyPair kp1 = Factory.generateKeyPair(transMock); + encryptor = Factory.pkCipher(kp1.getPublic(), true); + decryptor = Factory.pkCipher(kp1.getPrivate(), false); + byte[] encrypedMessage1 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); + String output1 = new String(decryptor.doFinal(encrypedMessage1)); + assertThat(output1, is(message)); + + // coverage + when(transMock.start("Generate KeyPair", Env.SUB)).thenReturn(null); + KeyPair kp2 = Factory.generateKeyPair(transMock); + encryptor = Factory.pkCipher(kp2.getPublic(), true); + decryptor = Factory.pkCipher(kp2.getPrivate(), false); + byte[] encrypedMessage2 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); + String output2 = new String(decryptor.doFinal(encrypedMessage2)); + assertThat(output2, is(message)); + + KeyPair kp3 = Factory.generateKeyPair(null); + encryptor = Factory.pkCipher(kp3.getPublic(), true); + decryptor = Factory.pkCipher(kp3.getPrivate(), false); + byte[] encrypedMessage3 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); + String output3 = new String(decryptor.doFinal(encrypedMessage3)); + assertThat(output3, is(message)); + } + + @Test + public void keyStringManipTest() throws Exception { + KeyPair kp = Factory.generateKeyPair(transMock); + + String publicKeyString = Factory.toString(transMock, kp.getPublic()); + String privateKeyString = Factory.toString(transMock, kp.getPrivate()); + + assertThat(publicKeyString.startsWith("-----BEGIN PUBLIC KEY-----"), is(true)); + assertThat(publicKeyString.endsWith("-----END PUBLIC KEY-----\n"), is(true)); + + assertThat(privateKeyString.startsWith("-----BEGIN PRIVATE KEY-----"), is(true)); + assertThat(privateKeyString.endsWith("-----END PRIVATE KEY-----\n"), is(true)); + + PublicKey publicKey = Factory.toPublicKey(transMock, publicKeyString); + PrivateKey privateKey = Factory.toPrivateKey(transMock, privateKeyString); + + Cipher encryptor = Factory.pkCipher(publicKey, true); + Cipher decryptor = Factory.pkCipher(privateKey, false); + byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); + String output = new String(decryptor.doFinal(encrypedMessage)); + assertThat(output, is(message)); + } + + @Test + public void keyFileManipTest() throws Exception { + KeyPair kp = Factory.generateKeyPair(transMock); + + String privateKeyString = Factory.toString(transMock, kp.getPrivate()); + writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header"); + + PublicKey publicKey = kp.getPublic(); + PrivateKey privateKey = Factory.toPrivateKey(transMock, privateKeyFile); + + Cipher encryptor = Factory.pkCipher(publicKey, true); + Cipher decryptor = Factory.pkCipher(privateKey, false); + byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8)); + String output = new String(decryptor.doFinal(encrypedMessage)); + assertThat(output, is(message)); + } + + @Test + public void certToStringTest() throws IOException, CertException, CertificateEncodingException { + String certString; + when(logTargetMock.isLoggable()).thenReturn(true); + + certString = Factory.toString(transMock, x509CertMock); + assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true)); + assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true)); + + certString = Factory.toString(transMock, certMock); + assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true)); + assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true)); + + try { + certString = Factory.toString(transMock, (Certificate)null); + fail("Should have thrown an exception"); + } catch (CertException e) { + assertThat(e.getMessage(), is("Certificate not built")); + } + + when(certMock.getEncoded()).thenThrow(new CertificateEncodingException()); + try { + certString = Factory.toString(transMock, certMock); + fail("Should have thrown an exception"); + } catch (CertException e) { + } + + // coverage + when(logTargetMock.isLoggable()).thenReturn(false); + certString = Factory.toString(transMock, x509CertMock); + } + + @Test + public void toX509Test() throws CertificateException, IOException, CertException { + String output; + Collection certs; + when(logTargetMock.isLoggable()).thenReturn(true); + + String certString = readFromFile(certFile, false); + + certs = Factory.toX509Certificate(certString); + // Contrived way of getting a Certificate out of a Collection + output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]); + assertThat(output, is(certString)); + + certs = Factory.toX509Certificate(transMock, certFile); + // Contrived way of getting a Certificate out of a Collection + output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]); + assertThat(output, is(certString)); + + List certStrings = new ArrayList<>(); + certStrings.add(certString); + certStrings.add(certString); + certs = Factory.toX509Certificate(certStrings); + // Contrived way of getting a Certificate out of a Collection + // it doesn't matter which one we get - they're the same + output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]); + assertThat(output, is(certString)); + } + + @Test + public void stripperTest() throws Exception { + KeyPair kp = Factory.generateKeyPair(transMock); + String privateKeyString = Factory.toString(transMock, kp.getPrivate()); + writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header"); + + StripperInputStream stripper = new StripperInputStream(privateKeyFile); + + String expected = cleanupString(privateKeyString); + byte[] buffer = new byte[10000]; + stripper.read(buffer); + String output = new String(buffer, 0, expected.length()); + assertThat(output, is(expected)); + stripper.close(); + + // coverage + stripper = new StripperInputStream(new FileInputStream(privateKeyFile)); + stripper.close(); + stripper = new StripperInputStream(new BufferedReader(new FileReader(privateKeyFile))); + stripper.close(); + stripper.close(); // also coverage... + } + + @Test + public void binaryTest() throws IOException { + String output = new String(Factory.binary(certFile)); + String expected = readFromFile(certFile, true); + assertThat(output, is(expected)); + } + + @Test + public void signatureTest() throws Exception { + KeyPair kp = Factory.generateKeyPair(transMock); + String signedString = "Something that needs signing"; + byte[] signedBytes = Factory.sign(transMock, signedString.getBytes(), kp.getPrivate()); + String output = Factory.toSignatureString(signedBytes); + assertThat(output.startsWith("-----BEGIN SIGNATURE-----"), is(true)); + assertThat(output.endsWith("-----END SIGNATURE-----\n"), is(true)); + assertThat(Factory.verify(transMock, signedString.getBytes(), signedBytes, kp.getPublic()), is(true)); + } + + @Test + public void base64ISTest() throws Exception { + KeyPair kp = Factory.generateKeyPair(transMock); + + String privateKeyString = Factory.toString(transMock, kp.getPrivate()); + String cleaned = cleanupString(privateKeyString); + writeToFile(privateKeyFile, cleaned, null); + Base64InputStream b64is = new Base64InputStream(privateKeyFile); + byte[] buffer = new byte[10000]; + b64is.read(buffer); + b64is.close(); + + FileInputStream fis = new FileInputStream(privateKeyFile); + b64is = new Base64InputStream(fis); + b64is.close(); + fis.close(); + } + + @Test + public void getSecurityProviderTest() throws CertException { + String[][] params = { + {"test", "test"}, + {"test", "test"}, + }; + assertThat(Factory.getSecurityProvider("PKCS12", params), is(nullValue())); + } + + private String cleanupString(String str) { + String[] lines = str.split("\n", 0); + List rawLines = new ArrayList<>(); + for (int i = 0; i < lines.length - 2; i++) { + rawLines.add(lines[i + 1]); + } + return join("", rawLines); + } + + /** + * Note: String.join is not part of JDK 7, which is what we compile to for CADI + */ + private String join(String delim, List rawLines) { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for(String s : rawLines) { + if(first) { + first = false; + } else { + sb.append(delim); + } + sb.append(s); + } + return sb.toString(); + } + + private void writeToFile(File file, String contents, String header) throws Exception { + PrintWriter writer = new PrintWriter(file, "UTF-8"); + if (header != null) { + writer.println(header); + } + writer.println(contents); + writer.close(); + } + + private String readFromFile(File file, boolean addCR) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(file)); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + String lineEnd = (addCR) ? "\r\n" : "\n"; + sb.append(line + lineEnd); + } + br.close(); + return sb.toString(); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java index 7afb4cf4..6bb31b2f 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java @@ -40,61 +40,61 @@ import certman.v1_0.CertInfo; public class JU_PlaceArtifactInFiles { - @Mock private Trans transMock; - @Mock private CertInfo certInfoMock; - @Mock private Artifact artiMock; - - private static final String dirName = "src/test/resources/artifacts"; - private static final String nsName = "org.onap.test"; - private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life - - private List certs; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - certs = new ArrayList<>(); - certs.add("cert1"); - certs.add("cert2"); - - when(certInfoMock.getChallenge()).thenReturn(luggagePassword); - when(certInfoMock.getCerts()).thenReturn(certs); - - when(artiMock.getDir()).thenReturn(dirName); - when(artiMock.getNs()).thenReturn(nsName); - } - - @AfterClass - public static void tearDownOnce() { - cleanup(); - PlaceArtifactInFiles.clear(); - } - - @Test - public void test() throws CadiException { - PlaceArtifactInFiles placer = new PlaceArtifactInFiles(); - placer.place(transMock, certInfoMock, artiMock, "machine"); - assertThat(placer._place(transMock, certInfoMock, artiMock), is(true)); - assertThat(new File(dirName + '/' + nsName + ".crt").exists(), is(true)); - assertThat(new File(dirName + '/' + nsName + ".key").exists(), is(true)); - - when(certInfoMock.getCerts()).thenReturn(null); - try { - placer._place(transMock, certInfoMock, artiMock); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - } - - private static void cleanup() { - File dir = new File(dirName); - if (dir.exists()) { - for (File f : dir.listFiles()) { - f.delete(); - } - dir.delete(); - } - } + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + + private List certs; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + certs = new ArrayList<>(); + certs.add("cert1"); + certs.add("cert2"); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + when(certInfoMock.getCerts()).thenReturn(certs); + + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + PlaceArtifactInFiles.clear(); + } + + @Test + public void test() throws CadiException { + PlaceArtifactInFiles placer = new PlaceArtifactInFiles(); + placer.place(transMock, certInfoMock, artiMock, "machine"); + assertThat(placer._place(transMock, certInfoMock, artiMock), is(true)); + assertThat(new File(dirName + '/' + nsName + ".crt").exists(), is(true)); + assertThat(new File(dirName + '/' + nsName + ".key").exists(), is(true)); + + when(certInfoMock.getCerts()).thenReturn(null); + try { + placer._place(transMock, certInfoMock, artiMock); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java index d61ac499..1a653ab2 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java @@ -54,100 +54,100 @@ import certman.v1_0.CertInfo; public class JU_PlaceArtifactInKeystore { - @Mock private Trans transMock; - @Mock private CertInfo certInfoMock; - @Mock private Artifact artiMock; - - private static final String caName = "onap"; - private static final String dirName = "src/test/resources/artifacts"; - private static final String nsName = "org.onap.test"; - private static final String mechID = "m12345"; - private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life - - private static String privateKeyString; - private static String x509Chain; - private static String x509String; - - private List certs; - - @Before - public void setup() throws FileNotFoundException, IOException, CertificateException { - MockitoAnnotations.initMocks(this); - - x509Chain = fromFile(new File("src/test/resources/cert.pem")); - x509String = fromFile(new File("src/test/resources/exampleCertificate.cer")); - privateKeyString = fromFile(new File("src/test/resources/key.pem")); - - certs = new ArrayList<>(); - - when(certInfoMock.getChallenge()).thenReturn(luggagePassword); - when(certInfoMock.getCerts()).thenReturn(certs); - - when(artiMock.getCa()).thenReturn(caName); - when(artiMock.getDir()).thenReturn(dirName); - when(artiMock.getNs()).thenReturn(nsName); - when(artiMock.getMechid()).thenReturn(mechID); - - when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString); - - when(transMock.start("Reconstitute Private Key", Env.SUB)).thenReturn(mock(TimeTaken.class)); - } - - @AfterClass - public static void tearDownOnce() { - cleanup(); - PlaceArtifactInKeystore.clear(); - } - - @Test - public void test() throws CadiException { - // Note: PKCS12 can't be tested in JDK 7 and earlier. Can't handle Trusting Certificates. - PlaceArtifactInKeystore placer = new PlaceArtifactInKeystore(Agent.JKS); - - certs.add(x509String); - certs.add(x509Chain); - assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true)); - for (String ext : new String[] {"chal", "keyfile", Agent.JKS, "trust.jks", "cred.props"}) { - File f = new File(dirName + '/' + nsName + '.' + ext); - assertThat(f.exists(), is(true)); - } - - // coverage - assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true)); - - when(certInfoMock.getCerts()).thenReturn(null); - try { - placer._place(transMock, certInfoMock, artiMock); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - - } - - private static void cleanup() { - File dir = new File(dirName); - if (dir.exists()) { - for (File f : dir.listFiles()) { - f.delete(); - } - dir.delete(); - } - } - - public String fromFile(File file) throws IOException { - BufferedReader br = new BufferedReader(new FileReader(file)); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - String line; - baos.write(br.readLine().getBytes()); - // Here comes the hacky part - baos.write("\n".getBytes()); - while((line=br.readLine())!=null) { - if(line.length()>0) { - baos.write(line.getBytes()); - baos.write("\n".getBytes()); - } - } - br.close(); - return baos.toString(); - } + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String caName = "onap"; + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String mechID = "m12345"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + + private static String privateKeyString; + private static String x509Chain; + private static String x509String; + + private List certs; + + @Before + public void setup() throws FileNotFoundException, IOException, CertificateException { + MockitoAnnotations.initMocks(this); + + x509Chain = fromFile(new File("src/test/resources/cert.pem")); + x509String = fromFile(new File("src/test/resources/exampleCertificate.cer")); + privateKeyString = fromFile(new File("src/test/resources/key.pem")); + + certs = new ArrayList<>(); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + when(certInfoMock.getCerts()).thenReturn(certs); + + when(artiMock.getCa()).thenReturn(caName); + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + when(artiMock.getMechid()).thenReturn(mechID); + + when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString); + + when(transMock.start("Reconstitute Private Key", Env.SUB)).thenReturn(mock(TimeTaken.class)); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + PlaceArtifactInKeystore.clear(); + } + + @Test + public void test() throws CadiException { + // Note: PKCS12 can't be tested in JDK 7 and earlier. Can't handle Trusting Certificates. + PlaceArtifactInKeystore placer = new PlaceArtifactInKeystore(Agent.JKS); + + certs.add(x509String); + certs.add(x509Chain); + assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true)); + for (String ext : new String[] {"chal", "keyfile", Agent.JKS, "trust.jks", "cred.props"}) { + File f = new File(dirName + '/' + nsName + '.' + ext); + assertThat(f.exists(), is(true)); + } + + // coverage + assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true)); + + when(certInfoMock.getCerts()).thenReturn(null); + try { + placer._place(transMock, certInfoMock, artiMock); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } + + public String fromFile(File file) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(file)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + String line; + baos.write(br.readLine().getBytes()); + // Here comes the hacky part + baos.write("\n".getBytes()); + while((line=br.readLine())!=null) { + if(line.length()>0) { + baos.write(line.getBytes()); + baos.write("\n".getBytes()); + } + } + br.close(); + return baos.toString(); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java index 7f9cc765..d66546bf 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java @@ -41,60 +41,60 @@ import certman.v1_0.CertInfo; public class JU_PlaceArtifactOnStream { - @Mock private Trans transMock; - @Mock private CertInfo certInfoMock; - @Mock private Artifact artiMock; - - private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life - private static final String privateKeyString = "I'm a private key!"; - - private ByteArrayOutputStream outStream; - - private List certs; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - certs = new ArrayList<>(); - certs.add("cert1"); - certs.add("cert2"); - - when(certInfoMock.getChallenge()).thenReturn(luggagePassword); - when(certInfoMock.getCerts()).thenReturn(certs); - when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString); - - outStream = new ByteArrayOutputStream(); - } - - @Test - public void test() { - PlaceArtifactOnStream placer = new PlaceArtifactOnStream(new PrintStream(outStream)); - placer.place(transMock, certInfoMock, artiMock, "machine"); - - String[] output = outStream.toString().split(System.lineSeparator(), 0); - - String[] expected = { - "Challenge: " + luggagePassword, - "PrivateKey:", - privateKeyString, - "Certificate Chain:", - "cert1", - "cert2" - }; - - assertThat(output.length, is(expected.length)); - for (int i = 0; i < output.length; i++) { - assertThat(output[i], is(expected[i])); - } - - // coverage - when(certInfoMock.getNotes()).thenReturn(""); - placer.place(transMock, certInfoMock, artiMock, "machine"); - - when(certInfoMock.getNotes()).thenReturn("Some Notes"); - when(transMock.info()).thenReturn(mock(LogTarget.class)); - placer.place(transMock, certInfoMock, artiMock, "machine"); - } + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + private static final String privateKeyString = "I'm a private key!"; + + private ByteArrayOutputStream outStream; + + private List certs; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + certs = new ArrayList<>(); + certs.add("cert1"); + certs.add("cert2"); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + when(certInfoMock.getCerts()).thenReturn(certs); + when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString); + + outStream = new ByteArrayOutputStream(); + } + + @Test + public void test() { + PlaceArtifactOnStream placer = new PlaceArtifactOnStream(new PrintStream(outStream)); + placer.place(transMock, certInfoMock, artiMock, "machine"); + + String[] output = outStream.toString().split(System.lineSeparator(), 0); + + String[] expected = { + "Challenge: " + luggagePassword, + "PrivateKey:", + privateKeyString, + "Certificate Chain:", + "cert1", + "cert2" + }; + + assertThat(output.length, is(expected.length)); + for (int i = 0; i < output.length; i++) { + assertThat(output[i], is(expected[i])); + } + + // coverage + when(certInfoMock.getNotes()).thenReturn(""); + placer.place(transMock, certInfoMock, artiMock, "machine"); + + when(certInfoMock.getNotes()).thenReturn("Some Notes"); + when(transMock.info()).thenReturn(mock(LogTarget.class)); + placer.place(transMock, certInfoMock, artiMock, "machine"); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactScripts.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactScripts.java index 682606c0..75db53f7 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactScripts.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactScripts.java @@ -38,55 +38,55 @@ import certman.v1_0.CertInfo; public class JU_PlaceArtifactScripts { - @Mock private Trans transMock; - @Mock private CertInfo certInfoMock; - @Mock private Artifact artiMock; - - private static final String dirName = "src/test/resources/artifacts"; - private static final String nsName = "org.onap.test"; - private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life - private static final String notification = "A notification"; - private static final String osUser = "user"; // That's the stupidest combination I've ever heard in my life - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - when(artiMock.getDir()).thenReturn(dirName); - when(artiMock.getNs()).thenReturn(nsName); - when(artiMock.getNotification()).thenReturn(notification); - when(artiMock.getOsUser()).thenReturn(osUser); - - when(certInfoMock.getChallenge()).thenReturn(luggagePassword); - } - - @AfterClass - public static void tearDownOnce() { - cleanup(); - PlaceArtifactScripts.clear(); - } - - @Test - public void test() throws CadiException { - PlaceArtifactScripts placer = new PlaceArtifactScripts(); - placer.place(transMock, certInfoMock, artiMock, "machine"); - - assertThat(new File(dirName + '/' + nsName + ".crontab.sh").exists(), is(true)); - assertThat(new File(dirName + '/' + nsName + ".check.sh").exists(), is(true)); - - //coverage - when(artiMock.getNotification()).thenReturn("mailto: " + notification); - placer.place(transMock, certInfoMock, artiMock, "machine"); - } - - private static void cleanup() { - File dir = new File(dirName); - if (dir.exists()) { - for (File f : dir.listFiles()) { - f.delete(); - } - dir.delete(); - } - } + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + private static final String notification = "A notification"; + private static final String osUser = "user"; // That's the stupidest combination I've ever heard in my life + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + when(artiMock.getNotification()).thenReturn(notification); + when(artiMock.getOsUser()).thenReturn(osUser); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + PlaceArtifactScripts.clear(); + } + + @Test + public void test() throws CadiException { + PlaceArtifactScripts placer = new PlaceArtifactScripts(); + placer.place(transMock, certInfoMock, artiMock, "machine"); + + assertThat(new File(dirName + '/' + nsName + ".crontab.sh").exists(), is(true)); + assertThat(new File(dirName + '/' + nsName + ".check.sh").exists(), is(true)); + + //coverage + when(artiMock.getNotification()).thenReturn("mailto: " + notification); + placer.place(transMock, certInfoMock, artiMock, "machine"); + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java index 11d58ea0..537e218f 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java @@ -31,40 +31,40 @@ import org.onap.aaf.cadi.oauth.AAFToken; public class JU_AAFToken { - @Test - public void testMax() throws CadiException { - UUID uuid = new UUID(Long.MAX_VALUE,Long.MAX_VALUE); - String token = AAFToken.toToken(uuid); - UUID uuid2 = AAFToken.fromToken(token); - assertEquals(uuid, uuid2); - } - - @Test - public void testMin() throws CadiException { - UUID uuid = new UUID(Long.MIN_VALUE,Long.MIN_VALUE); - String token = AAFToken.toToken(uuid); - UUID uuid2 = AAFToken.fromToken(token); - assertEquals(uuid, uuid2); - } + @Test + public void testMax() throws CadiException { + UUID uuid = new UUID(Long.MAX_VALUE,Long.MAX_VALUE); + String token = AAFToken.toToken(uuid); + UUID uuid2 = AAFToken.fromToken(token); + assertEquals(uuid, uuid2); + } + + @Test + public void testMin() throws CadiException { + UUID uuid = new UUID(Long.MIN_VALUE,Long.MIN_VALUE); + String token = AAFToken.toToken(uuid); + UUID uuid2 = AAFToken.fromToken(token); + assertEquals(uuid, uuid2); + } - @Test - public void testRandom() throws CadiException { - for(int i=0;i<100;++i) { - UUID uuid = UUID.randomUUID(); - String token = AAFToken.toToken(uuid); - UUID uuid2 = AAFToken.fromToken(token); - assertEquals(uuid, uuid2); - } - } + @Test + public void testRandom() throws CadiException { + for(int i=0;i<100;++i) { + UUID uuid = UUID.randomUUID(); + String token = AAFToken.toToken(uuid); + UUID uuid2 = AAFToken.fromToken(token); + assertEquals(uuid, uuid2); + } + } - @Test - public void nullTest() { - // Invalid characters - assertNull(AAFToken.fromToken("~~invalid characters~~")); - - // Invalid CADI tokens - assertNull(AAFToken.fromToken("ABCDEF")); - assertNull(AAFToken.fromToken("12345678901234567890123456789012345678")); - } + @Test + public void nullTest() { + // Invalid characters + assertNull(AAFToken.fromToken("~~invalid characters~~")); + + // Invalid CADI tokens + assertNull(AAFToken.fromToken("ABCDEF")); + assertNull(AAFToken.fromToken("12345678901234567890123456789012345678")); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java index 52b2beb4..8764c8d3 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java @@ -48,38 +48,38 @@ import org.onap.aaf.cadi.client.Result; public class JU_OAuth2HttpTaf { - private static final String authz = "Bearer John Doe"; + private static final String authz = "Bearer John Doe"; - @Mock private TokenMgr tmgrMock; - @Mock private HttpServletResponse respMock; - @Mock private HttpServletRequest reqMock; - @Mock private OAuth2Principal princMock; + @Mock private TokenMgr tmgrMock; + @Mock private HttpServletResponse respMock; + @Mock private HttpServletRequest reqMock; + @Mock private OAuth2Principal princMock; - private PropAccess access; + private PropAccess access; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } - @Test - public void test() throws APIException, CadiException, LocatorException { - OAuth2HttpTaf taf = new OAuth2HttpTaf(access, tmgrMock); + @Test + public void test() throws APIException, CadiException, LocatorException { + OAuth2HttpTaf taf = new OAuth2HttpTaf(access, tmgrMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - when(reqMock.getHeader("Authorization")).thenReturn(authz); + taf.validate(LifeForm.CBLF, reqMock, respMock); + when(reqMock.getHeader("Authorization")).thenReturn(authz); - doReturn(Result.ok(200, princMock)).when(tmgrMock).toPrincipal(anyString(), (byte[])any()); - taf.validate(LifeForm.CBLF, reqMock, respMock); + doReturn(Result.ok(200, princMock)).when(tmgrMock).toPrincipal(anyString(), (byte[])any()); + taf.validate(LifeForm.CBLF, reqMock, respMock); - when(reqMock.isSecure()).thenReturn(true); + when(reqMock.isSecure()).thenReturn(true); - doReturn(Result.err(404, "not found")).when(tmgrMock).toPrincipal(anyString(), (byte[])any()); - taf.validate(LifeForm.CBLF, reqMock, respMock); + doReturn(Result.err(404, "not found")).when(tmgrMock).toPrincipal(anyString(), (byte[])any()); + taf.validate(LifeForm.CBLF, reqMock, respMock); - taf.revalidate(null, null); - } + taf.revalidate(null, null); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java index 94737b0c..2f4cd7b6 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java @@ -40,29 +40,29 @@ import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_OAuth2HttpTafResp { - private static final String description = "description"; + private static final String description = "description"; - @Mock private TrustPrincipal princMock; - @Mock private OAuth2Principal oauthMock; - @Mock private HttpServletResponse respMock; + @Mock private TrustPrincipal princMock; + @Mock private OAuth2Principal oauthMock; + @Mock private HttpServletResponse respMock; - private PropAccess access; + private PropAccess access; - private RESP status; + private RESP status; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - status = RESP.NO_FURTHER_PROCESSING; - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + status = RESP.NO_FURTHER_PROCESSING; + } - @Test - public void test() throws IOException { - OAuth2HttpTafResp resp = new OAuth2HttpTafResp(access, princMock, description, status, respMock); - resp = new OAuth2HttpTafResp(access, oauthMock, description, status, respMock, true); - assertThat(resp.isFailedAttempt(), is(true)); - assertThat(resp.isAuthenticated(), is(status)); - assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); - } + @Test + public void test() throws IOException { + OAuth2HttpTafResp resp = new OAuth2HttpTafResp(access, princMock, description, status, respMock); + resp = new OAuth2HttpTafResp(access, oauthMock, description, status, respMock, true); + assertThat(resp.isFailedAttempt(), is(true)); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java index 853c4ae3..3864cc25 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java @@ -42,59 +42,59 @@ import org.onap.aaf.cadi.oauth.TokenPerm; import org.onap.aaf.cadi.principal.BearerPrincipal; public class JU_OAuth2Lur { - - private List aafPerms; - private List perms; - - @Mock private TokenMgr tmMock; - @Mock private AAFPermission pondMock; - @Mock private Principal princMock; - @Mock private OAuth2Principal oauthPrincMock; - @Mock private BearerPrincipal bearPrincMock; - @Mock private TokenPerm tpMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } + + private List aafPerms; + private List perms; + + @Mock private TokenMgr tmMock; + @Mock private AAFPermission pondMock; + @Mock private Principal princMock; + @Mock private OAuth2Principal oauthPrincMock; + @Mock private BearerPrincipal bearPrincMock; + @Mock private TokenPerm tpMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } - @Test - public void test() { - OAuth2Lur lur = new OAuth2Lur(tmMock); - lur.createPerm("testPerm"); - lur.createPerm("testPerm1|testPerm2|testPerm3"); + @Test + public void test() { + OAuth2Lur lur = new OAuth2Lur(tmMock); + lur.createPerm("testPerm"); + lur.createPerm("testPerm1|testPerm2|testPerm3"); - assertThat(lur.fish(princMock, pondMock), is(false)); - assertThat(lur.fish(oauthPrincMock, pondMock), is(false)); - - when(oauthPrincMock.tokenPerm()).thenReturn(tpMock); - assertThat(lur.fish(oauthPrincMock, pondMock), is(false)); - - aafPerms = new ArrayList<>(); - aafPerms.add(pondMock); - aafPerms.add(pondMock); - when(tpMock.perms()).thenReturn(aafPerms); - when(pondMock.match(pondMock)).thenReturn(false).thenReturn(true); - assertThat(lur.fish(oauthPrincMock, pondMock), is(true)); + assertThat(lur.fish(princMock, pondMock), is(false)); + assertThat(lur.fish(oauthPrincMock, pondMock), is(false)); + + when(oauthPrincMock.tokenPerm()).thenReturn(tpMock); + assertThat(lur.fish(oauthPrincMock, pondMock), is(false)); + + aafPerms = new ArrayList<>(); + aafPerms.add(pondMock); + aafPerms.add(pondMock); + when(tpMock.perms()).thenReturn(aafPerms); + when(pondMock.match(pondMock)).thenReturn(false).thenReturn(true); + assertThat(lur.fish(oauthPrincMock, pondMock), is(true)); - perms = new ArrayList<>(); - perms.add(pondMock); - perms.add(pondMock); - lur.fishAll(oauthPrincMock, perms); + perms = new ArrayList<>(); + perms.add(pondMock); + perms.add(pondMock); + lur.fishAll(oauthPrincMock, perms); - when(oauthPrincMock.tokenPerm()).thenReturn(null); - lur.fishAll(oauthPrincMock, perms); - - assertThat(lur.handlesExclusively(pondMock), is(false)); - - assertThat(lur.handles(null), is(false)); - assertThat(lur.handles(princMock), is(false)); - assertThat(lur.handles(bearPrincMock), is(false)); - when(bearPrincMock.getBearer()).thenReturn("not null :)"); - assertThat(lur.handles(bearPrincMock), is(true)); + when(oauthPrincMock.tokenPerm()).thenReturn(null); + lur.fishAll(oauthPrincMock, perms); + + assertThat(lur.handlesExclusively(pondMock), is(false)); + + assertThat(lur.handles(null), is(false)); + assertThat(lur.handles(princMock), is(false)); + assertThat(lur.handles(bearPrincMock), is(false)); + when(bearPrincMock.getBearer()).thenReturn("not null :)"); + assertThat(lur.handles(bearPrincMock), is(true)); - lur.destroy(); - lur.clear(null, null); - } + lur.destroy(); + lur.clear(null, null); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Principal.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Principal.java index 45736949..630adacb 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Principal.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Principal.java @@ -34,27 +34,27 @@ import org.onap.aaf.cadi.oauth.TokenPerm; public class JU_OAuth2Principal { - @Mock TokenPerm tpMock; - - - private static final String username = "username"; - - private static final byte[] hash = "hashstring".getBytes(); - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - when(tpMock.getUsername()).thenReturn(username); - } + @Mock TokenPerm tpMock; + + + private static final String username = "username"; + + private static final byte[] hash = "hashstring".getBytes(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + when(tpMock.getUsername()).thenReturn(username); + } - @Test - public void test() { - OAuth2Principal princ = new OAuth2Principal(tpMock, hash); - assertThat(princ.getName(), is(username)); - assertThat(princ.tokenPerm(), is(tpMock)); - assertThat(princ.tag(), is("OAuth")); - assertThat(princ.personalName(), is(username)); - } + @Test + public void test() { + OAuth2Principal princ = new OAuth2Principal(tpMock, hash); + assertThat(princ.getName(), is(username)); + assertThat(princ.tokenPerm(), is(tpMock)); + assertThat(princ.tag(), is("OAuth")); + assertThat(princ.personalName(), is(username)); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java index 555eda41..ef22b792 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java @@ -56,237 +56,237 @@ import junit.framework.Assert; public class JU_OAuthTest { - private ByteArrayOutputStream outStream; + private ByteArrayOutputStream outStream; - private static PropAccess access; - private static TokenClientFactory tcf; + private static PropAccess access; + private static TokenClientFactory tcf; - @BeforeClass - public static void setUpBeforeClass() { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); + @BeforeClass + public static void setUpBeforeClass() { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); - access = new PropAccess(); - try { - tcf = TokenClientFactory.instance(access); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - } + access = new PropAccess(); + try { + tcf = TokenClientFactory.instance(access); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(); + } + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - Field field = SecurityInfoC.class.getDeclaredField("sicMap"); - field.setAccessible(true); - field.set(null, new HashMap<>()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + Field field = SecurityInfoC.class.getDeclaredField("sicMap"); + field.setAccessible(true); + field.set(null, new HashMap<>()); + } - @Before - public void setUp() throws Exception { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - } + @Before + public void setUp() throws Exception { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } - @After - public void tearDown() throws Exception { - System.setOut(System.out); - } + @After + public void tearDown() throws Exception { + System.setOut(System.out); + } - @Test - public void testROPCFlowHappy() { - try { - // AAF OAuth - String client_id = access.getProperty(Config.AAF_APPID); - String client_secret = access.getProperty(Config.AAF_APPPASS); - String tokenServiceURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL); -// Assert.assertNotNull(tokenServiceURL); - String tokenIntrospectURL = access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL); - String tokenAltIntrospectURL = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL); -// Assert.assertNotNull(tokenIntrospectURL); - final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL); - String username = access.getProperty("cadi_username"); + @Test + public void testROPCFlowHappy() { + try { + // AAF OAuth + String client_id = access.getProperty(Config.AAF_APPID); + String client_secret = access.getProperty(Config.AAF_APPPASS); + String tokenServiceURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL); +// Assert.assertNotNull(tokenServiceURL); + String tokenIntrospectURL = access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL); + String tokenAltIntrospectURL = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL); +// Assert.assertNotNull(tokenIntrospectURL); + final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL); + String username = access.getProperty("cadi_username"); - TokenClient tc; - Result rtt; - if(true) { - tc = tcf.newClient(tokenServiceURL, 3000); - tc.client_creds(client_id,client_secret); - tc.password(access.getProperty("cadi_username"),access.getProperty("cadi_password")); - rtt = tc.getToken(Kind.BASIC_AUTH,"org.osaaf.aaf","org.osaaf.test"); - if(rtt.isOK()) { - print(rtt.value); - rtt = tc.refreshToken(rtt.value); - if(rtt.isOK()) { - print(rtt.value); - TokenClient ic = tcf.newClient(tokenIntrospectURL,3000); - ic.client_creds(client_id,client_secret); + TokenClient tc; + Result rtt; + if(true) { + tc = tcf.newClient(tokenServiceURL, 3000); + tc.client_creds(client_id,client_secret); + tc.password(access.getProperty("cadi_username"),access.getProperty("cadi_password")); + rtt = tc.getToken(Kind.BASIC_AUTH,"org.osaaf.aaf","org.osaaf.test"); + if(rtt.isOK()) { + print(rtt.value); + rtt = tc.refreshToken(rtt.value); + if(rtt.isOK()) { + print(rtt.value); + TokenClient ic = tcf.newClient(tokenIntrospectURL,3000); + ic.client_creds(client_id,client_secret); - Result ri = ic.introspect(rtt.value.getAccessToken()); - if(ri.isOK()) { - print(ri.value); - } else { - System.out.println(ri.code + ' ' + ri.error); - Assert.fail(ri.code + ' ' + ri.error); - } - TzClient helloClient = tcf.newTzClient(endServicesURL); - helloClient.setToken(client_id, rtt.value); -// String rv = serviceCall(helloClient); -// System.out.println(rv); - // Assert.assertEquals("Hello AAF OAuth2\n",rv); - } else { - System.out.println(rtt.code + ' ' + rtt.error); - Assert.fail(rtt.code + ' ' + rtt.error); - } - } else { - System.out.println(rtt.code + ' ' + rtt.error); - Assert.fail(rtt.code + ' ' + rtt.error); - } - } - - // ISAM Test - if(true) { - System.out.println("**** ISAM TEST ****"); - tokenServiceURL=access.getProperty(Config.AAF_ALT_OAUTH2_TOKEN_URL); - client_id=access.getProperty(Config.AAF_ALT_CLIENT_ID); - client_secret=access.getProperty(Config.AAF_ALT_CLIENT_SECRET); - if(tokenServiceURL!=null) { - tc = tcf.newClient(tokenServiceURL, 3000); - tc.client_creds(client_id, client_secret); - int at = username.indexOf('@'); - - tc.password(at>=0?username.substring(0, at):username,access.getProperty("cadi_password")); - rtt = tc.getToken("org.osaaf.aaf","org.osaaf.test"); - if(rtt.isOK()) { - print(rtt.value); - rtt = tc.refreshToken(rtt.value); - if(rtt.isOK()) { - print(rtt.value); - - tc = tcf.newClient(tokenAltIntrospectURL, 3000); - tc.client_creds(client_id, client_secret); - Result rti = tc.introspect(rtt.value.getAccessToken()); - if(rti.isOK()) { - System.out.print("Normal ISAM "); - print(rti.value); - } else { - System.out.println(rti.code + ' ' + rti.error); - Assert.fail(rtt.code + ' ' + rtt.error); - } + Result ri = ic.introspect(rtt.value.getAccessToken()); + if(ri.isOK()) { + print(ri.value); + } else { + System.out.println(ri.code + ' ' + ri.error); + Assert.fail(ri.code + ' ' + ri.error); + } + TzClient helloClient = tcf.newTzClient(endServicesURL); + helloClient.setToken(client_id, rtt.value); +// String rv = serviceCall(helloClient); +// System.out.println(rv); + // Assert.assertEquals("Hello AAF OAuth2\n",rv); + } else { + System.out.println(rtt.code + ' ' + rtt.error); + Assert.fail(rtt.code + ' ' + rtt.error); + } + } else { + System.out.println(rtt.code + ' ' + rtt.error); + Assert.fail(rtt.code + ' ' + rtt.error); + } + } + + // ISAM Test + if(true) { + System.out.println("**** ISAM TEST ****"); + tokenServiceURL=access.getProperty(Config.AAF_ALT_OAUTH2_TOKEN_URL); + client_id=access.getProperty(Config.AAF_ALT_CLIENT_ID); + client_secret=access.getProperty(Config.AAF_ALT_CLIENT_SECRET); + if(tokenServiceURL!=null) { + tc = tcf.newClient(tokenServiceURL, 3000); + tc.client_creds(client_id, client_secret); + int at = username.indexOf('@'); + + tc.password(at>=0?username.substring(0, at):username,access.getProperty("cadi_password")); + rtt = tc.getToken("org.osaaf.aaf","org.osaaf.test"); + if(rtt.isOK()) { + print(rtt.value); + rtt = tc.refreshToken(rtt.value); + if(rtt.isOK()) { + print(rtt.value); + + tc = tcf.newClient(tokenAltIntrospectURL, 3000); + tc.client_creds(client_id, client_secret); + Result rti = tc.introspect(rtt.value.getAccessToken()); + if(rti.isOK()) { + System.out.print("Normal ISAM "); + print(rti.value); + } else { + System.out.println(rti.code + ' ' + rti.error); + Assert.fail(rtt.code + ' ' + rtt.error); + } - tc = tcf.newClient(tokenIntrospectURL, 3000); - tc.client_creds(client_id, client_secret); - rti = tc.introspect(rtt.value.getAccessToken()); - if(rti.isOK()) { - System.out.print("AAF with ISAM Token "); - print(rti.value); - } else { - System.out.println(rti.code + ' ' + rti.error); - if(rti.code!=404) { - Assert.fail(rti.code + ' ' + rti.error); - } - } + tc = tcf.newClient(tokenIntrospectURL, 3000); + tc.client_creds(client_id, client_secret); + rti = tc.introspect(rtt.value.getAccessToken()); + if(rti.isOK()) { + System.out.print("AAF with ISAM Token "); + print(rti.value); + } else { + System.out.println(rti.code + ' ' + rti.error); + if(rti.code!=404) { + Assert.fail(rti.code + ' ' + rti.error); + } + } - TzClient tzClient = tcf.newTzClient(endServicesURL); - tzClient.setToken(client_id, rtt.value); - // Note: this is AAF's "Hello" server - String rv = serviceCall(tzClient); - System.out.println(rv); - // Assert.assertEquals("Hello AAF OAuth2\n",rv); - } else { - System.out.println(rtt.code + ' ' + rtt.error); - Assert.fail(rtt.code + ' ' + rtt.error); - } - } else { - System.out.println(rtt.code + ' ' + rtt.error); - Assert.fail(rtt.code + ' ' + rtt.error); - } - } else { - Assert.fail(Config.AAF_ALT_OAUTH2_TOKEN_URL + " is required"); - } - } - } catch (Exception e) { -// Assert.fail(); - } - } - - -// private TokenClient testROPCFlow(final String url, final String client_id, final String client_secret, String user, String password, final String ... scope) throws Exception { -// TokenClient tclient = tcf.newClient(url,3000); -// tclient.client_creds(client_id, client_secret); -// if(user!=null && password!=null) { -// tclient.password(user,password); -// } -// Result rt = tclient.getToken(scope); -// if(rt.isOK()) { -// print(rt.value); -// Result rti = tclient.introspect(rt.value.getAccessToken()); -// if(rti.isOK()) { -// print(rti.value); -// } else { -// printAndFail(rti); -// } -// } else { -// printAndFail(rt); -// } -// return tclient; -// } - - private String serviceCall(TzClient tzClient) throws Exception { - return tzClient.best(new Retryable() { - @Override - public String code(Rcli client) throws CadiException, ConnectException, APIException { - Future future = client.read(null,"text/plain"); - if(future.get(3000)) { - return future.value; - } else { - throw new APIException(future.code() + future.body()); - } - } - }); - } -// private void printAndFail(Result rt) { -// System.out.printf("HTTP Code %d: %s\n", rt.code, rt.error); -// Assert.fail(rt.toString()); -// } + TzClient tzClient = tcf.newTzClient(endServicesURL); + tzClient.setToken(client_id, rtt.value); + // Note: this is AAF's "Hello" server + String rv = serviceCall(tzClient); + System.out.println(rv); + // Assert.assertEquals("Hello AAF OAuth2\n",rv); + } else { + System.out.println(rtt.code + ' ' + rtt.error); + Assert.fail(rtt.code + ' ' + rtt.error); + } + } else { + System.out.println(rtt.code + ' ' + rtt.error); + Assert.fail(rtt.code + ' ' + rtt.error); + } + } else { + Assert.fail(Config.AAF_ALT_OAUTH2_TOKEN_URL + " is required"); + } + } + } catch (Exception e) { +// Assert.fail(); + } + } + + +// private TokenClient testROPCFlow(final String url, final String client_id, final String client_secret, String user, String password, final String ... scope) throws Exception { +// TokenClient tclient = tcf.newClient(url,3000); +// tclient.client_creds(client_id, client_secret); +// if(user!=null && password!=null) { +// tclient.password(user,password); +// } +// Result rt = tclient.getToken(scope); +// if(rt.isOK()) { +// print(rt.value); +// Result rti = tclient.introspect(rt.value.getAccessToken()); +// if(rti.isOK()) { +// print(rti.value); +// } else { +// printAndFail(rti); +// } +// } else { +// printAndFail(rt); +// } +// return tclient; +// } + + private String serviceCall(TzClient tzClient) throws Exception { + return tzClient.best(new Retryable() { + @Override + public String code(Rcli client) throws CadiException, ConnectException, APIException { + Future future = client.read(null,"text/plain"); + if(future.get(3000)) { + return future.value; + } else { + throw new APIException(future.code() + future.body()); + } + } + }); + } +// private void printAndFail(Result rt) { +// System.out.printf("HTTP Code %d: %s\n", rt.code, rt.error); +// Assert.fail(rt.toString()); +// } - private void print(Token t) { - GregorianCalendar exp_date = new GregorianCalendar(); - exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); - System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", - t.getAccessToken(), - t.getTokenType(), - t.getExpiresIn(), - Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), - t.getScope(), - t.getRefreshToken()); - } - - private void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { - System.out.println("Empty Introspect"); - return; - } - Date exp = new Date(ti.getExp()*1000); // seconds - System.out.printf("Introspect\n" - + "\tAccessToken:\t%s\n" - + "\tClient-id:\t%s\n" - + "\tClient Type:\t%s\n" - + "\tActive: \t%s\n" - + "\tUserName:\t%s\n" - + "\tExpires: \t%d (%s)\n" - + "\tScope:\t\t%s\n" - + "\tContent:\t\t%s\n", - ti.getAccessToken(), - ti.getClientId(), - ti.getClientType(), - ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), - ti.getUsername(), - ti.getExp(), - Chrono.timeStamp(exp), - ti.getScope(), - ti.getContent()==null?"":ti.getContent()); - - System.out.println(); - } + private void print(Token t) { + GregorianCalendar exp_date = new GregorianCalendar(); + exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); + System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", + t.getAccessToken(), + t.getTokenType(), + t.getExpiresIn(), + Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), + t.getScope(), + t.getRefreshToken()); + } + + private void print(Introspect ti) { + if(ti==null || ti.getClientId()==null) { + System.out.println("Empty Introspect"); + return; + } + Date exp = new Date(ti.getExp()*1000); // seconds + System.out.printf("Introspect\n" + + "\tAccessToken:\t%s\n" + + "\tClient-id:\t%s\n" + + "\tClient Type:\t%s\n" + + "\tActive: \t%s\n" + + "\tUserName:\t%s\n" + + "\tExpires: \t%d (%s)\n" + + "\tScope:\t\t%s\n" + + "\tContent:\t\t%s\n", + ti.getAccessToken(), + ti.getClientId(), + ti.getClientType(), + ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), + ti.getUsername(), + ti.getExp(), + Chrono.timeStamp(exp), + ti.getScope(), + ti.getContent()==null?"":ti.getContent()); + + System.out.println(); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TimedToken.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TimedToken.java index 775a0398..abfa4264 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TimedToken.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TimedToken.java @@ -40,45 +40,45 @@ import aafoauth.v2_0.Token; public class JU_TimedToken { - private static final byte[] hash = "hashstring".getBytes(); + private static final byte[] hash = "hashstring".getBytes(); - private static final int expires = 10000; + private static final int expires = 10000; - private Path path; + private Path path; - @Mock private Persist persistMock; - @Mock private Token tokenMock; + @Mock private Persist persistMock; + @Mock private Token tokenMock; - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); - when(tokenMock.getExpiresIn()).thenReturn(expires); - path = Files.createTempFile("fake", ".txt"); - } + when(tokenMock.getExpiresIn()).thenReturn(expires); + path = Files.createTempFile("fake", ".txt"); + } - @Test - public void test() { - int actuallyExpires = ((int)(System.currentTimeMillis() / 1000)) + expires; - TimedToken ttoken = new TimedToken(persistMock, tokenMock, hash, path); + @Test + public void test() { + int actuallyExpires = ((int)(System.currentTimeMillis() / 1000)) + expires; + TimedToken ttoken = new TimedToken(persistMock, tokenMock, hash, path); - assertThat(ttoken.get(), is(tokenMock)); - assertThat(ttoken.checkSyncTime(), is(true)); - assertThat(ttoken.checkReloadable(), is(false)); - assertThat(ttoken.hasBeenTouched(), is(false)); - assertThat(Math.abs(ttoken.expires() - actuallyExpires) < 10, is(true)); - assertThat(ttoken.expired(), is(false)); + assertThat(ttoken.get(), is(tokenMock)); + assertThat(ttoken.checkSyncTime(), is(true)); + assertThat(ttoken.checkReloadable(), is(false)); + assertThat(ttoken.hasBeenTouched(), is(false)); + assertThat(Math.abs(ttoken.expires() - actuallyExpires) < 10, is(true)); + assertThat(ttoken.expired(), is(false)); - assertThat(ttoken.match(hash), is(true)); - assertThat(ttoken.getHash(), is(hash)); + assertThat(ttoken.match(hash), is(true)); + assertThat(ttoken.getHash(), is(hash)); - assertThat(ttoken.path(), is(path)); + assertThat(ttoken.path(), is(path)); - assertThat(ttoken.count(), is(0)); - ttoken.inc(); - assertThat(ttoken.count(), is(1)); - ttoken.clearCount(); - assertThat(ttoken.count(), is(0)); - } + assertThat(ttoken.count(), is(0)); + ttoken.inc(); + assertThat(ttoken.count(), is(1)); + ttoken.clearCount(); + assertThat(ttoken.count(), is(0)); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenClientFactoryTest.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenClientFactoryTest.java index 27a1a271..e8fbbbd5 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenClientFactoryTest.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenClientFactoryTest.java @@ -39,37 +39,37 @@ import junit.framework.Assert; public class JU_TokenClientFactoryTest { - /** - * Acceptable Locator Patterns for choosing AAFLocator over others - */ - @Test - public void testLocatorString() { - /* - PropAccess access = new PropAccess(); - access.setProperty(Config.AAF_LOCATE_URL, "https://xytz.sbbc.dd:8095/locate"); - access.setProperty(Config.CADI_LATITUDE, "39.000"); - access.setProperty(Config.CADI_LONGITUDE, "-72.000"); - TokenClientFactory tcf; - try { - System.out.println("one"); - tcf = TokenClientFactory.instance(access); - System.out.println("two"); - Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd/locate/hello") instanceof AAFLocator); - System.out.println("three"); - Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd:8234/locate/hello") instanceof AAFLocator); - System.out.println("four"); - Assert.assertEquals(true, tcf.bestLocator("https://AAF_LOCATE_URL/hello") instanceof AAFLocator); - System.out.println("five"); - Assert.assertEquals(true, tcf.bestLocator("https://AAF_LOCATE_URL/AAF_FS.hello/2.0") instanceof AAFLocator); - System.out.println("six"); - Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd:8234/locate") instanceof PropertyLocator); - System.out.println("seven"); - Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd:8234/Something") instanceof PropertyLocator); - } catch (APIException | GeneralSecurityException | IOException | CadiException | LocatorException | URISyntaxException e) { - e.printStackTrace(); - Assert.fail(); - } - */ - } + /** + * Acceptable Locator Patterns for choosing AAFLocator over others + */ + @Test + public void testLocatorString() { + /* + PropAccess access = new PropAccess(); + access.setProperty(Config.AAF_LOCATE_URL, "https://xytz.sbbc.dd:8095/locate"); + access.setProperty(Config.CADI_LATITUDE, "39.000"); + access.setProperty(Config.CADI_LONGITUDE, "-72.000"); + TokenClientFactory tcf; + try { + System.out.println("one"); + tcf = TokenClientFactory.instance(access); + System.out.println("two"); + Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd/locate/hello") instanceof AAFLocator); + System.out.println("three"); + Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd:8234/locate/hello") instanceof AAFLocator); + System.out.println("four"); + Assert.assertEquals(true, tcf.bestLocator("https://AAF_LOCATE_URL/hello") instanceof AAFLocator); + System.out.println("five"); + Assert.assertEquals(true, tcf.bestLocator("https://AAF_LOCATE_URL/AAF_FS.hello/2.0") instanceof AAFLocator); + System.out.println("six"); + Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd:8234/locate") instanceof PropertyLocator); + System.out.println("seven"); + Assert.assertEquals(true, tcf.bestLocator("https://xytz.sbbc.dd:8234/Something") instanceof PropertyLocator); + } catch (APIException | GeneralSecurityException | IOException | CadiException | LocatorException | URISyntaxException e) { + e.printStackTrace(); + Assert.fail(); + } + */ + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java index 356c12d5..c40e4eb5 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java @@ -49,148 +49,148 @@ import aafoauth.v2_0.Introspect; public class JU_TokenPerm { - private static final byte[] hash = "hashstring".getBytes(); - - private static final String clientId = "clientId"; - private static final String username = "username"; - private static final String token = "token"; - private static final String scopes = "scopes"; - private static final String content = "content"; - - private static final long expires = 10000L; - - private static Path path; - - @Mock private Persist persistMock; - @Mock private RosettaDF dfMock; - @Mock private Introspect introspectMock; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - - when(introspectMock.getExp()).thenReturn(expires); - when(introspectMock.getClientId()).thenReturn(clientId); - when(introspectMock.getUsername()).thenReturn(username); - when(introspectMock.getAccessToken()).thenReturn(token); - when(introspectMock.getScope()).thenReturn(scopes); - when(introspectMock.getExp()).thenReturn(expires); - - path = Files.createTempFile("fake", ".txt"); - } - - @Test - public void tokenTest() throws APIException { - TokenPerm tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path); - assertThat(tokenPerm.perms().size(), is(0)); - assertThat(tokenPerm.getClientId(), is(clientId)); - assertThat(tokenPerm.getUsername(), is(username)); - assertThat(tokenPerm.getToken(), is(token)); - assertThat(tokenPerm.getScopes(), is(scopes)); - assertThat(tokenPerm.getIntrospect(), is(introspectMock)); - - when(introspectMock.getContent()).thenReturn(content); - tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path); - } - - @Test - public void test() throws ParseException { - String json; - LoadPermissions lp; - Permission p; - - json = "{\"perm\":[" + - " {\"ns\":\"com\",\"type\":\"access\",\"instance\":\"*\",\"action\":\"read,approve\"}," + - "]}"; - - lp = new LoadPermissions(new StringReader(json)); - assertThat(lp.perms.size(), is(1)); - - p = lp.perms.get(0); - assertThat(p.getKey(), is("com|access|*|read,approve")); - assertThat(p.permType(), is("AAF")); - - // Extra closing braces for coverage - json = "{\"perm\":[" + - " {\"ns\":\"com\",\"type\":\"access\",\"instance\":\"*\",\"action\":\"read,approve\"}}," + - "]]}"; - - lp = new LoadPermissions(new StringReader(json)); - assertThat(lp.perms.size(), is(1)); - - p = lp.perms.get(0); - assertThat(p.getKey(), is("com|access|*|read,approve")); - assertThat(p.permType(), is("AAF")); - - // Test without a type - json = "{\"perm\":[" + - " {\"instance\":\"*\",\"action\":\"read,approve\"}," + - "]}"; - - lp = new LoadPermissions(new StringReader(json)); - assertThat(lp.perms.size(), is(0)); - - // Test without an instance - json = "{\"perm\":[" + - " {\"type\":\"com.access\",\"action\":\"read,approve\"}," + - "]}"; - - lp = new LoadPermissions(new StringReader(json)); - assertThat(lp.perms.size(), is(0)); - - // Test without an action - json = "{\"perm\":[" + - " {\"type\":\"com.access\",\"instance\":\"*\"}," + - "]}"; - - lp = new LoadPermissions(new StringReader(json)); - assertThat(lp.perms.size(), is(0)); - } - - @Test - public void redundancyTest() { - String json = "{\"perm\":[" + - " {\"type\":\"com.access\",\"instance\":\"*\",\"action\":\"read,approve\"}," + - " {\"type\":\"org.osaaf.aaf.access\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.aaf.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.aaf.attrib\",\"instance\":\":com.att.*:swm\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.aaf.bogus\",\"instance\":\"sample\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.aaf.ca\",\"instance\":\"aaf\",\"action\":\"ip\"}," + - " {\"type\":\"org.osaaf.aaf.ca\",\"instance\":\"local\",\"action\":\"domain\"}," + - " {\"type\":\"org.osaaf.aaf.cache\",\"instance\":\"*\",\"action\":\"clear\"}," + - " {\"type\":\"org.osaaf.aaf.cass\",\"instance\":\":mithril\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.aaf.certman\",\"instance\":\"local\",\"action\":\"read,request,showpass\"}," + - " {\"type\":\"org.osaaf.aaf.db\",\"instance\":\"pool\",\"action\":\"clear\"}," + - " {\"type\":\"org.osaaf.aaf.deny\",\"instance\":\"com.att\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.aaf.jenkins\",\"instance\":\"mithrilcsp.sbc.com\",\"action\":\"admin\"}," + - " {\"type\":\"org.osaaf.aaf.log\",\"instance\":\"com.att\",\"action\":\"id\"}," + - " {\"type\":\"org.osaaf.aaf.myPerm\",\"instance\":\"myInstance\",\"action\":\"myAction\"}," + - " {\"type\":\"org.osaaf.aaf.ns\",\"instance\":\":com.att.*:ns\",\"action\":\"write\"}," + - " {\"type\":\"org.osaaf.aaf.ns\",\"instance\":\":com.att:ns\",\"action\":\"write\"}," + - " {\"type\":\"org.osaaf.aaf.password\",\"instance\":\"com.att\",\"action\":\"extend\"}," + - " {\"type\":\"org.osaaf.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.authz.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.authz.dev.access\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.authz.swm.star\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.cadi.access\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.chris.access\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.csid.lab.swm.node\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.myapp.access\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.myapp.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.sample.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.sample.swm.myPerm\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.temp.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"org.osaaf.test.access\",\"instance\":\"*\",\"action\":\"*\"}," + - " {\"type\":\"org.osaaf.test.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"com.test.access\",\"instance\":\"*\",\"action\":\"read\"}," + - " {\"type\":\"com.test.access\",\"instance\":\"*\",\"action\":\"read\"}" + - "]}"; - try { - LoadPermissions lp = new LoadPermissions(new StringReader(json)); - assertThat(lp.perms.size(), is(34)); - } catch (ParseException e) { - fail(e.getMessage()); - } - } + private static final byte[] hash = "hashstring".getBytes(); + + private static final String clientId = "clientId"; + private static final String username = "username"; + private static final String token = "token"; + private static final String scopes = "scopes"; + private static final String content = "content"; + + private static final long expires = 10000L; + + private static Path path; + + @Mock private Persist persistMock; + @Mock private RosettaDF dfMock; + @Mock private Introspect introspectMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + when(introspectMock.getExp()).thenReturn(expires); + when(introspectMock.getClientId()).thenReturn(clientId); + when(introspectMock.getUsername()).thenReturn(username); + when(introspectMock.getAccessToken()).thenReturn(token); + when(introspectMock.getScope()).thenReturn(scopes); + when(introspectMock.getExp()).thenReturn(expires); + + path = Files.createTempFile("fake", ".txt"); + } + + @Test + public void tokenTest() throws APIException { + TokenPerm tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path); + assertThat(tokenPerm.perms().size(), is(0)); + assertThat(tokenPerm.getClientId(), is(clientId)); + assertThat(tokenPerm.getUsername(), is(username)); + assertThat(tokenPerm.getToken(), is(token)); + assertThat(tokenPerm.getScopes(), is(scopes)); + assertThat(tokenPerm.getIntrospect(), is(introspectMock)); + + when(introspectMock.getContent()).thenReturn(content); + tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path); + } + + @Test + public void test() throws ParseException { + String json; + LoadPermissions lp; + Permission p; + + json = "{\"perm\":[" + + " {\"ns\":\"com\",\"type\":\"access\",\"instance\":\"*\",\"action\":\"read,approve\"}," + + "]}"; + + lp = new LoadPermissions(new StringReader(json)); + assertThat(lp.perms.size(), is(1)); + + p = lp.perms.get(0); + assertThat(p.getKey(), is("com|access|*|read,approve")); + assertThat(p.permType(), is("AAF")); + + // Extra closing braces for coverage + json = "{\"perm\":[" + + " {\"ns\":\"com\",\"type\":\"access\",\"instance\":\"*\",\"action\":\"read,approve\"}}," + + "]]}"; + + lp = new LoadPermissions(new StringReader(json)); + assertThat(lp.perms.size(), is(1)); + + p = lp.perms.get(0); + assertThat(p.getKey(), is("com|access|*|read,approve")); + assertThat(p.permType(), is("AAF")); + + // Test without a type + json = "{\"perm\":[" + + " {\"instance\":\"*\",\"action\":\"read,approve\"}," + + "]}"; + + lp = new LoadPermissions(new StringReader(json)); + assertThat(lp.perms.size(), is(0)); + + // Test without an instance + json = "{\"perm\":[" + + " {\"type\":\"com.access\",\"action\":\"read,approve\"}," + + "]}"; + + lp = new LoadPermissions(new StringReader(json)); + assertThat(lp.perms.size(), is(0)); + + // Test without an action + json = "{\"perm\":[" + + " {\"type\":\"com.access\",\"instance\":\"*\"}," + + "]}"; + + lp = new LoadPermissions(new StringReader(json)); + assertThat(lp.perms.size(), is(0)); + } + + @Test + public void redundancyTest() { + String json = "{\"perm\":[" + + " {\"type\":\"com.access\",\"instance\":\"*\",\"action\":\"read,approve\"}," + + " {\"type\":\"org.osaaf.aaf.access\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.aaf.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.aaf.attrib\",\"instance\":\":com.att.*:swm\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.aaf.bogus\",\"instance\":\"sample\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.aaf.ca\",\"instance\":\"aaf\",\"action\":\"ip\"}," + + " {\"type\":\"org.osaaf.aaf.ca\",\"instance\":\"local\",\"action\":\"domain\"}," + + " {\"type\":\"org.osaaf.aaf.cache\",\"instance\":\"*\",\"action\":\"clear\"}," + + " {\"type\":\"org.osaaf.aaf.cass\",\"instance\":\":mithril\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.aaf.certman\",\"instance\":\"local\",\"action\":\"read,request,showpass\"}," + + " {\"type\":\"org.osaaf.aaf.db\",\"instance\":\"pool\",\"action\":\"clear\"}," + + " {\"type\":\"org.osaaf.aaf.deny\",\"instance\":\"com.att\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.aaf.jenkins\",\"instance\":\"mithrilcsp.sbc.com\",\"action\":\"admin\"}," + + " {\"type\":\"org.osaaf.aaf.log\",\"instance\":\"com.att\",\"action\":\"id\"}," + + " {\"type\":\"org.osaaf.aaf.myPerm\",\"instance\":\"myInstance\",\"action\":\"myAction\"}," + + " {\"type\":\"org.osaaf.aaf.ns\",\"instance\":\":com.att.*:ns\",\"action\":\"write\"}," + + " {\"type\":\"org.osaaf.aaf.ns\",\"instance\":\":com.att:ns\",\"action\":\"write\"}," + + " {\"type\":\"org.osaaf.aaf.password\",\"instance\":\"com.att\",\"action\":\"extend\"}," + + " {\"type\":\"org.osaaf.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.authz.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.authz.dev.access\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.authz.swm.star\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.cadi.access\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.chris.access\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.csid.lab.swm.node\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.myapp.access\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.myapp.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.sample.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.sample.swm.myPerm\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.temp.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"org.osaaf.test.access\",\"instance\":\"*\",\"action\":\"*\"}," + + " {\"type\":\"org.osaaf.test.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"com.test.access\",\"instance\":\"*\",\"action\":\"read\"}," + + " {\"type\":\"com.test.access\",\"instance\":\"*\",\"action\":\"read\"}" + + "]}"; + try { + LoadPermissions lp = new LoadPermissions(new StringReader(json)); + assertThat(lp.perms.size(), is(34)); + } catch (ParseException e) { + fail(e.getMessage()); + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TzHClient.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TzHClient.java index bd2393e4..11dce825 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TzHClient.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TzHClient.java @@ -53,66 +53,66 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.config.SecurityInfoC; public class JU_TzHClient { - - @Mock private Retryable retryableMock; - @Mock private TimedToken tokenMock; - @Mock private SecurityInfoC siMock; - @Mock private Locator locMock; - @Mock private Item itemMock; - @Mock private Rcli clientMock; - - private PropAccess access; - - private ByteArrayOutputStream errStream; - - private final static String client_id = "id"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat - access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon } - - errStream = new ByteArrayOutputStream(); - System.setErr(new PrintStream(errStream)); - } - - @After - public void tearDown() { - System.setErr(System.err); - } + + @Mock private Retryable retryableMock; + @Mock private TimedToken tokenMock; + @Mock private SecurityInfoC siMock; + @Mock private Locator locMock; + @Mock private Item itemMock; + @Mock private Rcli clientMock; + + private PropAccess access; + + private ByteArrayOutputStream errStream; + + private final static String client_id = "id"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat + access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon } + + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } - @Test - public void test() throws CadiException, LocatorException, APIException, IOException { - TzHClient client; - try { - client = new TzHClient(access, "tag"); - } catch (Exception e) { - throw e; - } - try { - client.best(retryableMock); - fail("Should've thrown an exception"); - } catch (CadiException e) { - assertThat(e.getMessage(), is("OAuth2 Token has not been set")); - } - client.setToken(client_id, tokenMock); - when(tokenMock.expired()).thenReturn(true); - try { - client.best(retryableMock); - fail("Should've thrown an exception"); - } catch (CadiException e) { - assertThat(e.getMessage(), is("Expired Token")); - } + @Test + public void test() throws CadiException, LocatorException, APIException, IOException { + TzHClient client; + try { + client = new TzHClient(access, "tag"); + } catch (Exception e) { + throw e; + } + try { + client.best(retryableMock); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("OAuth2 Token has not been set")); + } + client.setToken(client_id, tokenMock); + when(tokenMock.expired()).thenReturn(true); + try { + client.best(retryableMock); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Expired Token")); + } - client = new TzHClient(access, siMock, locMock); - when(tokenMock.expired()).thenReturn(false); - doReturn(clientMock).when(retryableMock).lastClient(); + client = new TzHClient(access, siMock, locMock); + when(tokenMock.expired()).thenReturn(false); + doReturn(clientMock).when(retryableMock).lastClient(); - when(retryableMock.item()).thenReturn(itemMock); - client.setToken(client_id, tokenMock); - assertThat(client.best(retryableMock), is(nullValue())); - } + when(retryableMock.item()).thenReturn(itemMock); + client.setToken(client_id, tokenMock); + assertThat(client.best(retryableMock), is(nullValue())); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persist.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persist.java index f8d76a95..3e03eb73 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persist.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persist.java @@ -57,95 +57,95 @@ import org.onap.aaf.misc.rosetta.env.RosettaEnv; public class JU_Persist { - private static final String resourceDirString = "src/test/resources"; - private static final String tokenDirString = "tokenDir"; - private static final String key = "key"; - - private static final int data = 5; - - private static final byte[] cred = "password".getBytes(); - - private PropAccess access; - private Result> result; - - @Mock private RosettaEnv envMock; - @Mock private Persist persistMock; - @Mock private RosettaDF dfMock; - @Mock private RosettaData dataMock; - @Mock private Persistable ctMock1; - @Mock private Persisting ctMock2; - @Mock private Loader> loaderMock; - - @Before - public void setup() throws APIException, CadiException, LocatorException { - MockitoAnnotations.initMocks(this); - - doReturn(dfMock).when(envMock).newDataFactory((Class[]) any()); - when(dfMock.newData()).thenReturn(dataMock); - when(dataMock.load(data)).thenReturn(dataMock); - - - result = Result.ok(200, ctMock1); - when(loaderMock.load(key)).thenReturn(result); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); - } - - @After - public void tearDown() { - File dir = new File(resourceDirString + '/' + tokenDirString); - for (File f : dir.listFiles()) { - f.delete(); - } - dir.delete(); - } - - @Test - public void test() throws CadiException, APIException, LocatorException, InterruptedException { - Persist> persist = new PersistStub(access, envMock, null, tokenDirString); - // Second call for coverage - persist = new PersistStub(access, envMock, null, tokenDirString); - assertThat(persist.getDF(), is(dfMock)); - persist.put(key, ctMock2); - Result> output = persist.get(key, cred, loaderMock); - assertThat(output.code, is(200)); - assertThat(output.isOK(), is(true)); - - when(ctMock2.checkSyncTime()).thenReturn(true); - when(ctMock2.hasBeenTouched()).thenReturn(true); - output = persist.get(key, cred, loaderMock); - assertThat(output.code, is(200)); - assertThat(output.isOK(), is(true)); - - persist.delete(key); - - assertThat(persist.get(null, null, null), is(nullValue())); - - // Uncommenting this lets us begin to test the nested Clean class, but - // will dramatically slow down every build that runs tests - We need to - // either refactor or find a more creative way to test Clean -// Thread.sleep(25000); - - persist.close(); - } - - private class PersistStub extends Persist> { - public PersistStub(Access access, RosettaEnv env, Class cls, String sub_dir) - throws CadiException, APIException { super(access, env, cls, sub_dir); } - @Override - protected Persistable newCacheable(Integer t, long expires_secsFrom1970, byte[] hash, Path path) - throws APIException, IOException { return null; } - @Override - public Path writeDisk(final RosettaDF df, final T t, final byte[] cred, final Path target, final long expires) throws CadiException { - return null; - } - @SuppressWarnings("unchecked") - @Override - public T readDisk(final RosettaDF df, final byte[] cred, final String filename,final Holder hp, final Holder hl) throws CadiException { - return (T)new Integer(data); - } - - } + private static final String resourceDirString = "src/test/resources"; + private static final String tokenDirString = "tokenDir"; + private static final String key = "key"; + + private static final int data = 5; + + private static final byte[] cred = "password".getBytes(); + + private PropAccess access; + private Result> result; + + @Mock private RosettaEnv envMock; + @Mock private Persist persistMock; + @Mock private RosettaDF dfMock; + @Mock private RosettaData dataMock; + @Mock private Persistable ctMock1; + @Mock private Persisting ctMock2; + @Mock private Loader> loaderMock; + + @Before + public void setup() throws APIException, CadiException, LocatorException { + MockitoAnnotations.initMocks(this); + + doReturn(dfMock).when(envMock).newDataFactory((Class[]) any()); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.load(data)).thenReturn(dataMock); + + + result = Result.ok(200, ctMock1); + when(loaderMock.load(key)).thenReturn(result); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); + } + + @After + public void tearDown() { + File dir = new File(resourceDirString + '/' + tokenDirString); + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + + @Test + public void test() throws CadiException, APIException, LocatorException, InterruptedException { + Persist> persist = new PersistStub(access, envMock, null, tokenDirString); + // Second call for coverage + persist = new PersistStub(access, envMock, null, tokenDirString); + assertThat(persist.getDF(), is(dfMock)); + persist.put(key, ctMock2); + Result> output = persist.get(key, cred, loaderMock); + assertThat(output.code, is(200)); + assertThat(output.isOK(), is(true)); + + when(ctMock2.checkSyncTime()).thenReturn(true); + when(ctMock2.hasBeenTouched()).thenReturn(true); + output = persist.get(key, cred, loaderMock); + assertThat(output.code, is(200)); + assertThat(output.isOK(), is(true)); + + persist.delete(key); + + assertThat(persist.get(null, null, null), is(nullValue())); + + // Uncommenting this lets us begin to test the nested Clean class, but + // will dramatically slow down every build that runs tests - We need to + // either refactor or find a more creative way to test Clean +// Thread.sleep(25000); + + persist.close(); + } + + private class PersistStub extends Persist> { + public PersistStub(Access access, RosettaEnv env, Class cls, String sub_dir) + throws CadiException, APIException { super(access, env, cls, sub_dir); } + @Override + protected Persistable newCacheable(Integer t, long expires_secsFrom1970, byte[] hash, Path path) + throws APIException, IOException { return null; } + @Override + public Path writeDisk(final RosettaDF df, final T t, final byte[] cred, final Path target, final long expires) throws CadiException { + return null; + } + @SuppressWarnings("unchecked") + @Override + public T readDisk(final RosettaDF df, final byte[] cred, final String filename,final Holder hp, final Holder hl) throws CadiException { + return (T)new Integer(data); + } + + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_PersistFile.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_PersistFile.java index cbe865eb..25d8c474 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_PersistFile.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_PersistFile.java @@ -52,70 +52,70 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; public class JU_PersistFile { - private static final String resourceDirString = "src/test/resources"; - private static final String tokenDirString = "tokenDir"; - private static final String tokenFileName = "token"; - - private static final int data = 5; - private static final long expires = 10000; - - private static final byte[] cred = "password".getBytes(); - - private PropAccess access; - private Holder hp = new Holder(null); - private Holder hl = new Holder(null); - - @Mock private RosettaDF dfMock; - @Mock private RosettaData dataMock; - @Mock private Holder hpMock; - - @Before - public void setup() throws APIException { - MockitoAnnotations.initMocks(this); - - when(dfMock.newData()).thenReturn(dataMock); - when(dataMock.load(data)).thenReturn(dataMock); - when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); - } - - @After - public void tearDown() { - File dir = new File(resourceDirString + '/' + tokenDirString); - for (File f : dir.listFiles()) { - f.delete(); - } - dir.delete(); - } - - @Test - public void test() throws CadiException, APIException, IOException { - PersistFile persistFile = new PersistFile(access, tokenDirString); - // Second call is for coverage - persistFile = new PersistFile(access, tokenDirString); - Path filepath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires); - persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl); - assertThat(persistFile.readExpiration(filepath), is(expires)); - - FileTime ft1 = persistFile.getFileTime(tokenFileName, hp); - FileTime ft2 = persistFile.getFileTime(tokenFileName, hpMock); - assertThat(ft1.toMillis(), is(ft2.toMillis())); - - persistFile.deleteFromDisk(filepath); - persistFile.deleteFromDisk(resourceDirString + '/' + tokenDirString + '/' + tokenFileName); - assertThat(persistFile.readExpiration(filepath), is(0L)); - - persistFile.getPath(resourceDirString + '/' + tokenDirString + '/' + tokenFileName); - - persistFile.writeDisk(dfMock, data, null, tokenFileName, expires); - try { - persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl); - fail("Should've thrown an exception"); - } catch (CadiException e) { - assertThat(e.getMessage(), is(CadiException.class.getName() + ": Hash does not match in Persistence")); - } - } + private static final String resourceDirString = "src/test/resources"; + private static final String tokenDirString = "tokenDir"; + private static final String tokenFileName = "token"; + + private static final int data = 5; + private static final long expires = 10000; + + private static final byte[] cred = "password".getBytes(); + + private PropAccess access; + private Holder hp = new Holder(null); + private Holder hl = new Holder(null); + + @Mock private RosettaDF dfMock; + @Mock private RosettaData dataMock; + @Mock private Holder hpMock; + + @Before + public void setup() throws APIException { + MockitoAnnotations.initMocks(this); + + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.load(data)).thenReturn(dataMock); + when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); + } + + @After + public void tearDown() { + File dir = new File(resourceDirString + '/' + tokenDirString); + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + + @Test + public void test() throws CadiException, APIException, IOException { + PersistFile persistFile = new PersistFile(access, tokenDirString); + // Second call is for coverage + persistFile = new PersistFile(access, tokenDirString); + Path filepath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires); + persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl); + assertThat(persistFile.readExpiration(filepath), is(expires)); + + FileTime ft1 = persistFile.getFileTime(tokenFileName, hp); + FileTime ft2 = persistFile.getFileTime(tokenFileName, hpMock); + assertThat(ft1.toMillis(), is(ft2.toMillis())); + + persistFile.deleteFromDisk(filepath); + persistFile.deleteFromDisk(resourceDirString + '/' + tokenDirString + '/' + tokenFileName); + assertThat(persistFile.readExpiration(filepath), is(0L)); + + persistFile.getPath(resourceDirString + '/' + tokenDirString + '/' + tokenFileName); + + persistFile.writeDisk(dfMock, data, null, tokenFileName, expires); + try { + persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is(CadiException.class.getName() + ": Hash does not match in Persistence")); + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persisting.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persisting.java index bb2b918a..9e029f3b 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persisting.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persisting.java @@ -51,80 +51,80 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; public class JU_Persisting { - private static final String resourceDirString = "src/test/resources"; - private static final String tokenDirString = "tokenDir"; - private static final String tokenFileName = "token"; + private static final String resourceDirString = "src/test/resources"; + private static final String tokenDirString = "tokenDir"; + private static final String tokenFileName = "token"; - private static final int data = 5; - private static final long expires = 10000; + private static final int data = 5; + private static final long expires = 10000; - private static final byte[] cred = "password".getBytes(); + private static final byte[] cred = "password".getBytes(); - private PropAccess access; + private PropAccess access; - @Mock private Persist persistMock; - @Mock private RosettaDF dfMock; - @Mock private RosettaData dataMock; + @Mock private Persist persistMock; + @Mock private RosettaDF dfMock; + @Mock private RosettaData dataMock; - @Before - public void setup() throws APIException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws APIException { + MockitoAnnotations.initMocks(this); - when(dfMock.newData()).thenReturn(dataMock); - when(dataMock.load(data)).thenReturn(dataMock); - when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.load(data)).thenReturn(dataMock); + when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); - persistMock.access = access; - } + persistMock.access = access; + } - @After - public void tearDown() { - File dir = new File(resourceDirString + '/' + tokenDirString); - for (File f : dir.listFiles()) { - f.delete(); - } - dir.delete(); - } + @After + public void tearDown() { + File dir = new File(resourceDirString + '/' + tokenDirString); + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } - @Test - public void test() throws CadiException, APIException { - Path tokenPath = Paths.get(resourceDirString, tokenDirString); + @Test + public void test() throws CadiException, APIException { + Path tokenPath = Paths.get(resourceDirString, tokenDirString); - Persisting persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath); - assertThat(persisting.get(), is(data)); - assertThat(persisting.expires(), is(expires)); - assertThat(persisting.expired(), is(true)); - assertThat(persisting.hasBeenTouched(), is(true)); + Persisting persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath); + assertThat(persisting.get(), is(data)); + assertThat(persisting.expires(), is(expires)); + assertThat(persisting.expired(), is(true)); + assertThat(persisting.hasBeenTouched(), is(true)); - PersistFile persistFile = new PersistFile(access, tokenDirString); - tokenPath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires); - persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath); - assertThat(persisting.hasBeenTouched(), is(false)); + PersistFile persistFile = new PersistFile(access, tokenDirString); + tokenPath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires); + persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath); + assertThat(persisting.hasBeenTouched(), is(false)); - persisting = new Persisting<>(persistMock, data, expires * (int)10e9, cred, tokenPath); - assertThat(persisting.expired(), is(false)); + persisting = new Persisting<>(persistMock, data, expires * (int)10e9, cred, tokenPath); + assertThat(persisting.expired(), is(false)); - assertThat(persisting.checkSyncTime(), is(true)); - assertThat(persisting.checkSyncTime(), is(false)); + assertThat(persisting.checkSyncTime(), is(true)); + assertThat(persisting.checkSyncTime(), is(false)); - assertThat(persisting.checkReloadable(), is(false)); + assertThat(persisting.checkReloadable(), is(false)); - assertThat(persisting.getHash(), is(cred)); + assertThat(persisting.getHash(), is(cred)); - assertThat(persisting.match(null), is(false)); - assertThat(persisting.match("random!".getBytes()), is(false)); - assertThat(persisting.match("passwrod".getBytes()), is(false)); - assertThat(persisting.match(cred), is(true)); + assertThat(persisting.match(null), is(false)); + assertThat(persisting.match("random!".getBytes()), is(false)); + assertThat(persisting.match("passwrod".getBytes()), is(false)); + assertThat(persisting.match(cred), is(true)); - persisting.clearCount(); - assertThat(persisting.count(), is(0)); - persisting.inc(); - assertThat(persisting.count(), is(1)); + persisting.clearCount(); + assertThat(persisting.count(), is(0)); + persisting.inc(); + assertThat(persisting.count(), is(1)); - assertThat(persisting.path(), is(tokenPath)); - } + assertThat(persisting.path(), is(tokenPath)); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java index 7a64f71c..368a5e29 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java @@ -39,82 +39,82 @@ import org.onap.aaf.cadi.sso.AAFSSO; public class JU_AAFSSO { - private static final String resourceDirString = "src/test/resources"; - private static final String aafDir = resourceDirString + "/aaf"; - - private ByteArrayInputStream inStream; - - @Before - public void setup() { - System.setProperty("user.home", aafDir); - - // Simulate user input - inStream = new ByteArrayInputStream("test\npassword".getBytes()); - System.setIn(inStream); - } - - @After - public void tearDown() { - recursiveDelete(new File(aafDir)); - } - - @Test - public void test() throws IOException, CadiException { - AAFSSO sso; - String[] args; - - args = new String[] { - "-login", - "-noexit", - }; - sso = new AAFSSO(args); - - assertThat(new File(aafDir).exists(), is(true)); - assertThat(new File(aafDir + "/.aaf").exists(), is(true)); - assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(true)); - assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true)); - assertThat(sso.loginOnly(), is(true)); + private static final String resourceDirString = "src/test/resources"; + private static final String aafDir = resourceDirString + "/aaf"; + + private ByteArrayInputStream inStream; + + @Before + public void setup() { + System.setProperty("user.home", aafDir); + + // Simulate user input + inStream = new ByteArrayInputStream("test\npassword".getBytes()); + System.setIn(inStream); + } + + @After + public void tearDown() { + recursiveDelete(new File(aafDir)); + } + + @Test + public void test() throws IOException, CadiException { + AAFSSO sso; + String[] args; + + args = new String[] { + "-login", + "-noexit", + }; + sso = new AAFSSO(args); + + assertThat(new File(aafDir).exists(), is(true)); + assertThat(new File(aafDir + "/.aaf").exists(), is(true)); + assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(true)); + assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true)); + assertThat(sso.loginOnly(), is(true)); // Not necessarily true -// assertThat(new File(aafDir + "/.aaf/sso.props").exists(), is(true)); - - sso.setLogDefault(); - sso.setStdErrDefault(); - - inStream.reset(); - args = new String[] { - "-logout", - "\\*", - "-noexit", - }; - sso = new AAFSSO(args); - - assertThat(new File(aafDir).exists(), is(true)); - assertThat(new File(aafDir + "/.aaf").exists(), is(true)); - assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(false)); - assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true)); - assertThat(sso.loginOnly(), is(false)); - - PropAccess access = sso.access(); - assertThat(sso.enc_pass(), is(access.getProperty(Config.AAF_APPPASS))); - assertThat(sso.user(), is(access.getProperty(Config.AAF_APPID))); - - sso.addProp("key", "value"); - assertThat(sso.err(), is(nullValue())); - - assertThat(sso.useX509(), is(false)); - - sso.close(); - } - - private void recursiveDelete(File file) { - for (File f : file.listFiles()) { - if (f.isDirectory()) { - recursiveDelete(f); - } - f.delete(); - } - file.delete(); - } +// assertThat(new File(aafDir + "/.aaf/sso.props").exists(), is(true)); + + sso.setLogDefault(); + sso.setStdErrDefault(); + + inStream.reset(); + args = new String[] { + "-logout", + "\\*", + "-noexit", + }; + sso = new AAFSSO(args); + + assertThat(new File(aafDir).exists(), is(true)); + assertThat(new File(aafDir + "/.aaf").exists(), is(true)); + assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(false)); + assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true)); + assertThat(sso.loginOnly(), is(false)); + + PropAccess access = sso.access(); + assertThat(sso.enc_pass(), is(access.getProperty(Config.AAF_APPPASS))); + assertThat(sso.user(), is(access.getProperty(Config.AAF_APPID))); + + sso.addProp("key", "value"); + assertThat(sso.err(), is(nullValue())); + + assertThat(sso.useX509(), is(false)); + + sso.close(); + } + + private void recursiveDelete(File file) { + for (File f : file.listFiles()) { + if (f.isDirectory()) { + recursiveDelete(f); + } + f.delete(); + } + file.delete(); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java b/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java index 6c3c6118..8881e76e 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java @@ -40,137 +40,137 @@ import org.onap.aaf.cadi.util.Split; import org.onap.aaf.misc.env.APIException; public class Sample { - private static Sample singleton; - final private AAFConHttp aafcon; - final private AAFLurPerm aafLur; - final private AAFAuthn aafAuthn; - - /** - * This method is to emphasize the importance of not creating the AAFObjects over and over again. - * @return - */ - public static Sample singleton() { - return singleton; - } + private static Sample singleton; + final private AAFConHttp aafcon; + final private AAFLurPerm aafLur; + final private AAFAuthn aafAuthn; + + /** + * This method is to emphasize the importance of not creating the AAFObjects over and over again. + * @return + */ + public static Sample singleton() { + return singleton; + } - public Sample(Access myAccess) throws APIException, CadiException, LocatorException { - aafcon = new AAFConHttp(myAccess); - aafLur = aafcon.newLur(); - aafAuthn = aafcon.newAuthn(aafLur); - } - - /** - * Checking credentials outside of HTTP/S presents fewer options initially. There is not, for instance, - * the option of using 2-way TLS HTTP/S. - * - * However, Password Checks are still useful, and, if the Client Certificate could be obtained in other ways, the - * Interface can be expanded in the future to include Certificates. - * @throws CadiException - * @throws IOException - */ - public Principal checkUserPass(String fqi, String pass) throws IOException, CadiException { - String ok = aafAuthn.validate(fqi, pass); - if(ok==null) { - System.out.println("Success!"); - /* - UnAuthPrincipal means that it is not coming from the official Authorization chain. - This is useful for Security Plugins which don't use Principal as the tie between - Authentication and Authorization - - You can also use this if you want to check Authorization without actually Authenticating, as may - be the case with certain Onboarding Tooling. - */ - return new UnAuthPrincipal(fqi); - } else { - System.out.printf("Failure: %s\n",ok); - return null; - } - + public Sample(Access myAccess) throws APIException, CadiException, LocatorException { + aafcon = new AAFConHttp(myAccess); + aafLur = aafcon.newLur(); + aafAuthn = aafcon.newAuthn(aafLur); + } + + /** + * Checking credentials outside of HTTP/S presents fewer options initially. There is not, for instance, + * the option of using 2-way TLS HTTP/S. + * + * However, Password Checks are still useful, and, if the Client Certificate could be obtained in other ways, the + * Interface can be expanded in the future to include Certificates. + * @throws CadiException + * @throws IOException + */ + public Principal checkUserPass(String fqi, String pass) throws IOException, CadiException { + String ok = aafAuthn.validate(fqi, pass); + if(ok==null) { + System.out.println("Success!"); + /* + UnAuthPrincipal means that it is not coming from the official Authorization chain. + This is useful for Security Plugins which don't use Principal as the tie between + Authentication and Authorization + + You can also use this if you want to check Authorization without actually Authenticating, as may + be the case with certain Onboarding Tooling. + */ + return new UnAuthPrincipal(fqi); + } else { + System.out.printf("Failure: %s\n",ok); + return null; + } + - } + } - /** - * An example of looking for One Permission within all the permissions user has. CADI does cache these, - * so the call is not expensive. - * - * Note: If you are using "J2EE" (Servlets), CADI ties this function to the method: - * HttpServletRequest.isUserInRole(String user) - * - * The J2EE user can expect that his servlet will NOT be called without a Validated Principal, and that - * "isUserInRole()" will validate if the user has the Permission designated. - * - */ - public boolean oneAuthorization(Principal fqi, Permission p) { - return aafLur.fish(fqi, p); - } - - public List allAuthorization(Principal fqi) { - List pond = new ArrayList<>(); - aafLur.fishAll(fqi, pond); - return pond; - } - - - public static void main(String[] args) { - // Note: you can pick up Properties from Command line as well as VM Properties - // Code "user_fqi=... user_pass=..." (where user_pass can be encrypted) in the command line for this sample. - // Also code "perm=||" to test a specific Permission - PropAccess myAccess = new PropAccess(args); - try { - /* - * NOTE: Do NOT CREATE new aafcon, aafLur and aafAuthn each transaction. They are built to be - * reused! - * - * This is why this code demonstrates "Sample" as a singleton. - */ - singleton = new Sample(myAccess); - String user = myAccess.getProperty("user_fqi"); - String pass= myAccess.getProperty("user_pass"); - - if(user==null || pass==null) { - System.err.println("This Sample class requires properties user_fqi and user_pass"); - } else { - pass = myAccess.decrypt(pass, false); // Note, with "false", decryption will only happen if starts with "enc:" - // See the CODE for Java Methods used - Principal fqi = Sample.singleton().checkUserPass(user,pass); - - if(fqi==null) { - System.out.println("OK, normally, you would cease processing for an " - + "unauthenticated user, but for the purpose of Sample, we'll keep going.\n"); - fqi=new UnAuthPrincipal(user); - } - - // AGAIN, NOTE: If your client fails Authentication, the right behavior 99.9% - // of the time is to drop the transaction. We continue for sample only. - - // note, default String for perm - String permS = myAccess.getProperty("perm","org.osaaf.aaf.access|*|read"); - String[] permA = Split.splitTrim('|', permS); - if(permA.length>2) { - final Permission perm = new AAFPermission(null, permA[0],permA[1],permA[2]); - // See the CODE for Java Methods used - if(singleton().oneAuthorization(fqi, perm)) { - System.out.printf("Success: %s has %s\n",fqi.getName(),permS); - } else { - System.out.printf("%s does NOT have %s\n",fqi.getName(),permS); - } - } - - - // Another form, you can get ALL permissions in a list - // See the CODE for Java Methods used - List permL = singleton().allAuthorization(fqi); - if(permL.size()==0) { - System.out.printf("User %s has no Permissions THAT THE CALLER CAN SEE\n",fqi.getName()); - } else { - System.out.print("Success:\n"); - for(Permission p : permL) { - System.out.printf("\t%s has %s\n",fqi.getName(),p.getKey()); - } - } - } - } catch (APIException | CadiException | LocatorException | IOException e) { - e.printStackTrace(); - } - } + /** + * An example of looking for One Permission within all the permissions user has. CADI does cache these, + * so the call is not expensive. + * + * Note: If you are using "J2EE" (Servlets), CADI ties this function to the method: + * HttpServletRequest.isUserInRole(String user) + * + * The J2EE user can expect that his servlet will NOT be called without a Validated Principal, and that + * "isUserInRole()" will validate if the user has the Permission designated. + * + */ + public boolean oneAuthorization(Principal fqi, Permission p) { + return aafLur.fish(fqi, p); + } + + public List allAuthorization(Principal fqi) { + List pond = new ArrayList<>(); + aafLur.fishAll(fqi, pond); + return pond; + } + + + public static void main(String[] args) { + // Note: you can pick up Properties from Command line as well as VM Properties + // Code "user_fqi=... user_pass=..." (where user_pass can be encrypted) in the command line for this sample. + // Also code "perm=||" to test a specific Permission + PropAccess myAccess = new PropAccess(args); + try { + /* + * NOTE: Do NOT CREATE new aafcon, aafLur and aafAuthn each transaction. They are built to be + * reused! + * + * This is why this code demonstrates "Sample" as a singleton. + */ + singleton = new Sample(myAccess); + String user = myAccess.getProperty("user_fqi"); + String pass= myAccess.getProperty("user_pass"); + + if(user==null || pass==null) { + System.err.println("This Sample class requires properties user_fqi and user_pass"); + } else { + pass = myAccess.decrypt(pass, false); // Note, with "false", decryption will only happen if starts with "enc:" + // See the CODE for Java Methods used + Principal fqi = Sample.singleton().checkUserPass(user,pass); + + if(fqi==null) { + System.out.println("OK, normally, you would cease processing for an " + + "unauthenticated user, but for the purpose of Sample, we'll keep going.\n"); + fqi=new UnAuthPrincipal(user); + } + + // AGAIN, NOTE: If your client fails Authentication, the right behavior 99.9% + // of the time is to drop the transaction. We continue for sample only. + + // note, default String for perm + String permS = myAccess.getProperty("perm","org.osaaf.aaf.access|*|read"); + String[] permA = Split.splitTrim('|', permS); + if(permA.length>2) { + final Permission perm = new AAFPermission(null, permA[0],permA[1],permA[2]); + // See the CODE for Java Methods used + if(singleton().oneAuthorization(fqi, perm)) { + System.out.printf("Success: %s has %s\n",fqi.getName(),permS); + } else { + System.out.printf("%s does NOT have %s\n",fqi.getName(),permS); + } + } + + + // Another form, you can get ALL permissions in a list + // See the CODE for Java Methods used + List permL = singleton().allAuthorization(fqi); + if(permL.size()==0) { + System.out.printf("User %s has no Permissions THAT THE CALLER CAN SEE\n",fqi.getName()); + } else { + System.out.print("Success:\n"); + for(Permission p : permL) { + System.out.printf("\t%s has %s\n",fqi.getName(),p.getKey()); + } + } + } + } catch (APIException | CadiException | LocatorException | IOException e) { + e.printStackTrace(); + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java b/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java index e997378d..03dadb94 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java @@ -34,43 +34,43 @@ import aaf.v2_0.Error; public class JU_Content { - @Test - public void parseErrorJSON() throws Exception { - final String msg = "{\"messageId\":\"SVC2000\",\"text\":\"Select which cred to delete (or 0 to delete all):" + - "1) %1" + - "2) %2" + - "3) %3" + - "4) %4" + - "Run same command again with chosen entry as last parameter\"," + - "\"variables\":[" + - "\"m55555@jr583u.cred.test.com 1 Wed Oct 08 11:48:08 CDT 2014\"," + - "\"m55555@jr583u.cred.test.com 1 Thu Oct 09 12:54:46 CDT 2014\"," + - "\"m55555@jr583u.cred.test.com 1 Tue Jan 06 05:00:00 CST 2015\"," + - "\"m55555@jr583u.cred.test.com 1 Wed Jan 07 05:00:00 CST 2015\"]}"; - - Error err = new Error(); - err.setText("Hello"); - err.getVariables().add("I'm a teapot"); - err.setMessageId("12"); - - -// System.out.println(msg); - RosettaEnv env = new RosettaEnv(); - RosettaDF errDF = env.newDataFactory(aaf.v2_0.Error.class); - errDF.in(RosettaData.TYPE.JSON); - errDF.out(RosettaData.TYPE.JSON); - RosettaData data = errDF.newData(); - data.load(err); - - @SuppressWarnings("unused") - String output = data.asString(); -// System.out.println(output); - - data.load(new StringReader(msg)); - err = data.asObject(); - output = err.getText(); -// System.out.println(output); - } - + @Test + public void parseErrorJSON() throws Exception { + final String msg = "{\"messageId\":\"SVC2000\",\"text\":\"Select which cred to delete (or 0 to delete all):" + + "1) %1" + + "2) %2" + + "3) %3" + + "4) %4" + + "Run same command again with chosen entry as last parameter\"," + + "\"variables\":[" + + "\"m55555@jr583u.cred.test.com 1 Wed Oct 08 11:48:08 CDT 2014\"," + + "\"m55555@jr583u.cred.test.com 1 Thu Oct 09 12:54:46 CDT 2014\"," + + "\"m55555@jr583u.cred.test.com 1 Tue Jan 06 05:00:00 CST 2015\"," + + "\"m55555@jr583u.cred.test.com 1 Wed Jan 07 05:00:00 CST 2015\"]}"; + + Error err = new Error(); + err.setText("Hello"); + err.getVariables().add("I'm a teapot"); + err.setMessageId("12"); + + +// System.out.println(msg); + RosettaEnv env = new RosettaEnv(); + RosettaDF errDF = env.newDataFactory(aaf.v2_0.Error.class); + errDF.in(RosettaData.TYPE.JSON); + errDF.out(RosettaData.TYPE.JSON); + RosettaData data = errDF.newData(); + data.load(err); + + @SuppressWarnings("unused") + String output = data.asString(); +// System.out.println(output); + + data.load(new StringReader(msg)); + err = data.asObject(); + output = err.getText(); +// System.out.println(output); + } + } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java index 80e6dc40..cce7b5f3 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java @@ -41,90 +41,90 @@ import org.onap.aaf.cadi.config.SecurityInfoC; * @param */ public abstract class AbsAuthentication implements SecuritySetter { - // HTTP Header for Authentication is "Authorization". This was from an early stage of internet where - // Access by Credential "Authorized" you for everything on the site. Since those early days, it became - // clear that "full access" wasn't appropriate, so the split between Authentication and Authorization - // came into being... But the Header remains. - public static final String AUTHORIZATION = "Authorization"; - private static final Symm symm; + // HTTP Header for Authentication is "Authorization". This was from an early stage of internet where + // Access by Credential "Authorized" you for everything on the site. Since those early days, it became + // clear that "full access" wasn't appropriate, so the split between Authentication and Authorization + // came into being... But the Header remains. + public static final String AUTHORIZATION = "Authorization"; + private static final Symm symm; - protected static final String REPEAT_OFFENDER = "This call is aborted because of repeated usage of invalid Passwords"; - private static final int MAX_TEMP_COUNT = 10; - private static final int MAX_SPAM_COUNT = 10000; - private static final long WAIT_TIME = 1000*60*4L; - private final byte[] headValue; - private String user; - protected final SecurityInfoC securityInfo; - protected long lastMiss; - protected int count; - - static { - try { - symm = Symm.encrypt.obtain(); - } catch (IOException e) { - throw new RuntimeException("Cannot create critical internal encryption key",e); - } - - } + protected static final String REPEAT_OFFENDER = "This call is aborted because of repeated usage of invalid Passwords"; + private static final int MAX_TEMP_COUNT = 10; + private static final int MAX_SPAM_COUNT = 10000; + private static final long WAIT_TIME = 1000*60*4L; + private final byte[] headValue; + private String user; + protected final SecurityInfoC securityInfo; + protected long lastMiss; + protected int count; + + static { + try { + symm = Symm.encrypt.obtain(); + } catch (IOException e) { + throw new RuntimeException("Cannot create critical internal encryption key",e); + } + + } - public AbsAuthentication(final SecurityInfoC securityInfo, final String user, final byte[] headValue) throws IOException { - this.headValue = headValue==null?null:symm.encode(headValue); - this.user = user; - this.securityInfo = securityInfo; - lastMiss=0L; - count=0; - } + public AbsAuthentication(final SecurityInfoC securityInfo, final String user, final byte[] headValue) throws IOException { + this.headValue = headValue==null?null:symm.encode(headValue); + this.user = user; + this.securityInfo = securityInfo; + lastMiss=0L; + count=0; + } - protected String headValue() throws IOException { - if(headValue==null) { - return ""; - } else { - return new String(symm.decode(headValue)); - } - } - - protected void setUser(String id) { - user = id; - } - - @Override - public String getID() { - return user; - } + protected String headValue() throws IOException { + if(headValue==null) { + return ""; + } else { + return new String(symm.decode(headValue)); + } + } + + protected void setUser(String id) { + user = id; + } + + @Override + public String getID() { + return user; + } - public boolean isDenied() { - if(lastMiss>0 && lastMiss>System.currentTimeMillis()) { - return true; - } else { - lastMiss=0L; - return false; - } - } + public boolean isDenied() { + if(lastMiss>0 && lastMiss>System.currentTimeMillis()) { + return true; + } else { + lastMiss=0L; + return false; + } + } - public synchronized int setLastResponse(int httpcode) { - if(httpcode == 401) { - ++count; - if(lastMiss==0L && count>MAX_TEMP_COUNT) { - lastMiss=System.currentTimeMillis()+WAIT_TIME; - } - // if(count>MAX_SPAM_COUNT) { - // System.err.printf("Your service has %d consecutive bad service logins to AAF. \nIt will now exit\n", - // count); - // System.exit(401); - // } - if(count%1000==0) { - System.err.printf("Your service has %d consecutive bad service logins to AAF. AAF Access will be disabled after %d\n", - count,MAX_SPAM_COUNT); - } + public synchronized int setLastResponse(int httpcode) { + if(httpcode == 401) { + ++count; + if(lastMiss==0L && count>MAX_TEMP_COUNT) { + lastMiss=System.currentTimeMillis()+WAIT_TIME; + } + // if(count>MAX_SPAM_COUNT) { + // System.err.printf("Your service has %d consecutive bad service logins to AAF. \nIt will now exit\n", + // count); + // System.exit(401); + // } + if(count%1000==0) { + System.err.printf("Your service has %d consecutive bad service logins to AAF. AAF Access will be disabled after %d\n", + count,MAX_SPAM_COUNT); + } - } else { - lastMiss=0; - } - return count; - } + } else { + lastMiss=0; + } + return count; + } - public int count() { - return count; - } + public int count() { + return count; + } } \ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java index 3815bc67..0c38bd90 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java @@ -38,39 +38,39 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; * @param */ public abstract class AbsTransferSS implements SecuritySetter { - protected String value; - protected SecurityInfoC securityInfo; - protected SecuritySetter defSS; - private Principal principal; + protected String value; + protected SecurityInfoC securityInfo; + protected SecuritySetter defSS; + private Principal principal; - //Format:::[:AS][,::]* - public AbsTransferSS(TaggedPrincipal principal, String app) { - init(principal, app); - } + //Format:::[:AS][,::]* + public AbsTransferSS(TaggedPrincipal principal, String app) { + init(principal, app); + } - public AbsTransferSS(TaggedPrincipal principal, String app, SecurityInfoC si) { - init(principal,app); - securityInfo = si; - this.defSS = si.defSS; - } + public AbsTransferSS(TaggedPrincipal principal, String app, SecurityInfoC si) { + init(principal,app); + securityInfo = si; + this.defSS = si.defSS; + } - private void init(TaggedPrincipal principal, String app) { - this.principal=principal; - if(principal==null) { - return; - } else { - value = principal.getName() + ':' + - app + ':' + - principal.tag() + ':' + - "AS"; - } - } + private void init(TaggedPrincipal principal, String app) { + this.principal=principal; + if(principal==null) { + return; + } else { + value = principal.getName() + ':' + + app + ':' + + principal.tag() + ':' + + "AS"; + } + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.SecuritySetter#getID() - */ - @Override - public String getID() { - return principal==null?"":principal.getName(); - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.SecuritySetter#getID() + */ + @Override + public String getID() { + return principal==null?"":principal.getName(); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java index d5dfebf5..9aa9cad6 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java @@ -32,20 +32,20 @@ import org.onap.aaf.misc.rosetta.env.RosettaDF; public interface EClient { - public void setMethod(String meth); - public void setPathInfo(String pathinfo); - public void setPayload(Transfer transfer); - public void addHeader(String tag, String value); - public void setQueryParams(String q); - public void setFragment(String f); - public void send() throws APIException; - public Future futureCreate(Class t); - public Future futureReadString(); - public Future futureRead(RosettaDF df,Data.TYPE type); - public Future future(T t); - public Future future(HttpServletResponse resp, int expected) throws APIException; - - public interface Transfer { - public void transfer(OutputStream os) throws IOException, APIException; - } + public void setMethod(String meth); + public void setPathInfo(String pathinfo); + public void setPayload(Transfer transfer); + public void addHeader(String tag, String value); + public void setQueryParams(String q); + public void setFragment(String f); + public void send() throws APIException; + public Future futureCreate(Class t); + public Future futureReadString(); + public Future futureRead(RosettaDF df,Data.TYPE type); + public Future future(T t); + public Future future(HttpServletResponse resp, int expected) throws APIException; + + public interface Transfer { + public void transfer(OutputStream os) throws IOException, APIException; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java index 2579dc11..39f88687 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java @@ -24,10 +24,10 @@ package org.onap.aaf.cadi.client; import org.onap.aaf.cadi.CadiException; public abstract class Future { - public T value; - public abstract boolean get(int timeout) throws CadiException; - - public abstract int code(); - public abstract String body(); - public abstract String header(String tag); + public T value; + public abstract boolean get(int timeout) throws CadiException; + + public abstract int code(); + public abstract String body(); + public abstract String header(String tag); } \ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java index c13afc25..af97c465 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java @@ -28,19 +28,19 @@ package org.onap.aaf.cadi.client; * @param */ public class Holder { - private T value; - public Holder(T t) { - value = t; - } - public T set(T t) { - value = t; - return t; - } - - public T get() { - return value; - } - public String toString() { - return value.toString(); - } + private T value; + public Holder(T t) { + value = t; + } + public T set(T t) { + value = t; + return t; + } + + public T get() { + return value; + } + public String toString() { + return value.toString(); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java index 04075f29..b414487b 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java @@ -41,729 +41,729 @@ import org.onap.aaf.misc.env.util.Pool.Pooled; import org.onap.aaf.misc.rosetta.env.RosettaDF; public abstract class Rcli { - public static final String FORM_ENCODED = "application/x-www-form-urlencoded"; - public static final String APPL_JSON = "application/json"; - public static final String APPL_XML = "application/xml"; - public static final String BLANK = ""; - public static final String CONTENT_TYPE = "Content-Type"; - public static final String ACCEPT = "Accept"; - - protected static final String POST = "POST"; - protected static final String GET = "GET"; - protected static final String PUT = "PUT"; - protected static final String DELETE = "DELETE"; - protected TYPE type; - protected String apiVersion; - protected int readTimeout = 5000; - protected int connectionTimeout = 3000; - protected URI uri; - private String oneCallQueryParams; - public static Pool buffPool = new Pool(new Pool.Creator() { - @Override - public byte[] create() throws APIException { - return new byte[1024]; - } - - @Override - public void destroy(byte[] t) { - } - - @Override - public boolean isValid(byte[] t) { - return true; - } - - @Override - public void reuse(byte[] t) { - } - }); - - - public Rcli() { - super(); - } - - public abstract void setSecuritySetter(SecuritySetter ss); - public abstract SecuritySetter getSecuritySetter(); - - - public Rcli forUser(SecuritySetter ss) { - Rcli rv = clone(uri==null?this.uri:uri,ss); - setSecuritySetter(ss); - rv.type = type; - rv.apiVersion = apiVersion; - return rv; - } - - protected abstract Rcli clone(URI uri, SecuritySetter ss); - - public abstract void invalidate() throws CadiException; - - public Rcli readTimeout(int millis) { - readTimeout = millis; - return this; - } - - public Rcli connectionTimeout(int millis) { - connectionTimeout = millis; - return this; - } - - public Rcli type(TYPE type) { - this.type=type; - return this; - } - - public Rcli apiVersion(String apiVersion) { - this.apiVersion = apiVersion; - return this; - } - - public boolean isApiVersion(String prospective) { - return apiVersion.equals(prospective); - } - - - public String typeString(Class cls) { - return "application/"+cls.getSimpleName()+"+"+type.name().toLowerCase()+ - (apiVersion==null?BLANK:";version="+apiVersion); - } - - protected abstract EClient client() throws CadiException; - - - public Future create(final String pathinfo, final String contentType, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureCreate(df.getTypeClass()); - } - - public Future create(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureCreate(df.getTypeClass()); - } - - public Future create(String pathinfo, Class cls, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureCreate(df.getTypeClass()); - } - - public Future create(String pathinfo, Class cls) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(null); - client.send(); - return client.futureCreate(cls); - } - - public Future create(String pathinfo, String contentType) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(null); - client.send(); - return client.futureCreate(Void.class); - } - - public Future create(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(content); - client.send(); - return client.futureCreate(Void.class); - } - - - /** - * Post Data in WWW expected format, with the format tag1=value1&tag2=value2, etc - * Note Shortcut: - * Because typically, you will want to have a variable as value, you can type, as long as tag ends with "=" - * postForm(..., "tag1=value1","tag2=",var2); - * @param pathinfo - * @param df - * @param cls - * @param formParam - * @return - * @throws APIException - * @throws CadiException - */ - public Future postForm(String pathinfo, final RosettaDF df, final String ... formParam) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,FORM_ENCODED); - switch(type) { - case JSON: - client.addHeader(ACCEPT, APPL_JSON); - break; - case XML: - client.addHeader(ACCEPT, APPL_XML); - break; - default: - break; - } - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - PrintStream ps; - if(os instanceof PrintStream) { - ps = (PrintStream)os; - } else { - ps = new PrintStream(os); - } - boolean first = true; - for(String fp : formParam) { - if(fp!=null) { - if(first) { - first = false; - } else { - ps.print('&'); - } - if(fp.endsWith("=")) { - first = true; - } - ps.print(fp); - } - } - }}); - client.send(); - return client.futureRead(df,TYPE.JSON); - } - - /** - * Read String, using POST for keyInfo - * - * @param pathinfo - * @param df - * @param t - * @param resp - * @return - * @throws APIException - * @throws CadiException - */ - public Future readPost(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureReadString(); - } - - /** - * Read using POST for keyInfo, responding with marshaled Objects - * - * @param pathinfo - * @param df - * @param t - * @param resp - * @return - * @throws APIException - * @throws CadiException - */ - public Future readPost(String pathinfo, final RosettaDF df, final T t, final RosettaDF resp) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureRead(resp,resp.getOutType()); - } - - public Future readPost(String pathinfo, String contentType, String ... headers) throws CadiException, APIException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - }}); - client.send(); - return client.futureReadString(); - } - - public Future read(String pathinfo, String accept, String ... headers) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, accept); - - for(int i=1;i Future read(String pathinfo, String accept, RosettaDF df, String ... headers) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, accept); - for(int i=1;i Future read(String pathinfo, RosettaDF df,String ... headers) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, typeString(df.getTypeClass())); - for(int i=1;i Future read(String pathinfo, Class cls, RosettaDF df) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(null); - client.send(); - return client.futureRead(df,type); - } - - public Future update(String pathinfo, String contentType, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public Future updateRespondString(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - //String s = df.newData().out(type).load(t).asString(); - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureReadString(); - } - - public Future update(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(content); - client.send(); - return client.futureReadString(); - } - - - - - public Future update(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public Future update(String pathinfo, Class cls, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - - - /** - * A method to update with a VOID - * @param pathinfo - * @param resp - * @param expected - * @return - * @throws APIException - * @throws CadiException - */ - public Future update(String pathinfo) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(Void.class)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - -// client.setPayload(new EClient.Transfer() { -// @Override -// public void transfer(OutputStream os) throws IOException, APIException { -// } -// }); - client.send(); - return client.future(null); - } - - - public Future delete(String pathinfo, String contentType, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public Future delete(String pathinfo, Class cls, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public Future delete(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - - client.send(); - return client.future(t); - } - - - public Future delete(String pathinfo, Class cls) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(null); - client.send(); - return client.future((T)null); - } - - public Future delete(String pathinfo, String contentType) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(null); - client.send(); - return client.future(null); - } - - public Future transfer(final HttpServletRequest req, final HttpServletResponse resp, final String pathParam, final int expected) throws CadiException, APIException { - EClient client = client(); - URI uri; - try { - uri = new URI(req.getRequestURI()); - } catch (Exception e) { - throw new CadiException("Invalid incoming URI",e); - } - String name; - for(Enumeration en = req.getHeaderNames();en.hasMoreElements();) { - name = en.nextElement(); - client.addHeader(name,req.getHeader(name)); - } - client.setQueryParams(req.getQueryString()); - client.setFragment(uri.getFragment()); - client.setPathInfo(pathParam); - String meth = req.getMethod(); - client.setMethod(meth); - if(!"GET".equals(meth)) { - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - final ServletInputStream is = req.getInputStream(); - int read; - // reuse Buffers - Pooled pbuff = buffPool.get(); - try { - while((read=is.read(pbuff.content))>=0) { - os.write(pbuff.content,0,read); - } - } finally { - pbuff.done(); - } - } - }); - } - client.send(); - return client.future(resp, expected); - } - - private class ParsePath { - private final String path; - private final int query; - private final int queryEnd; - private final int pound; - private final String queryParams; - - public ParsePath(final String origPath) { - path = origPath; - if(origPath==null) { - query=queryEnd=pound=-1; - queryParams=null; - } else { - query = origPath.indexOf('?'); - pound = origPath.indexOf('#'); - queryEnd = pound>=0?pound:path.length(); - if(oneCallQueryParams==null) { - if(query>=0) { - queryParams = path.substring(query+1,queryEnd); - } else { - queryParams=null; - } - } else { - if(query>=0) { - queryParams = oneCallQueryParams + '&' + path.substring(query+1,queryEnd); - } else { - queryParams = oneCallQueryParams; - } - oneCallQueryParams = null; - } - } - } - - public String path() { - if(query>=0) { - if(pound>=0) { - return path.substring(pound+1); - } - return path.substring(0,query); - } else if(pound>=0) { - return path.substring(0,pound); - } else { - return path; - } - } - - public String query() { - return queryParams; - } - - public String frag() { - if(pound>=0) { - return path.substring(pound+1); - } else { - return null; - } - } - } - - public String toString() { - return uri.toString(); - } - - public URI getURI() { - return uri; - } - - public void setQueryParams(final String queryParams) { - oneCallQueryParams=queryParams; - } + public static final String FORM_ENCODED = "application/x-www-form-urlencoded"; + public static final String APPL_JSON = "application/json"; + public static final String APPL_XML = "application/xml"; + public static final String BLANK = ""; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String ACCEPT = "Accept"; + + protected static final String POST = "POST"; + protected static final String GET = "GET"; + protected static final String PUT = "PUT"; + protected static final String DELETE = "DELETE"; + protected TYPE type; + protected String apiVersion; + protected int readTimeout = 5000; + protected int connectionTimeout = 3000; + protected URI uri; + private String oneCallQueryParams; + public static Pool buffPool = new Pool(new Pool.Creator() { + @Override + public byte[] create() throws APIException { + return new byte[1024]; + } + + @Override + public void destroy(byte[] t) { + } + + @Override + public boolean isValid(byte[] t) { + return true; + } + + @Override + public void reuse(byte[] t) { + } + }); + + + public Rcli() { + super(); + } + + public abstract void setSecuritySetter(SecuritySetter ss); + public abstract SecuritySetter getSecuritySetter(); + + + public Rcli forUser(SecuritySetter ss) { + Rcli rv = clone(uri==null?this.uri:uri,ss); + setSecuritySetter(ss); + rv.type = type; + rv.apiVersion = apiVersion; + return rv; + } + + protected abstract Rcli clone(URI uri, SecuritySetter ss); + + public abstract void invalidate() throws CadiException; + + public Rcli readTimeout(int millis) { + readTimeout = millis; + return this; + } + + public Rcli connectionTimeout(int millis) { + connectionTimeout = millis; + return this; + } + + public Rcli type(TYPE type) { + this.type=type; + return this; + } + + public Rcli apiVersion(String apiVersion) { + this.apiVersion = apiVersion; + return this; + } + + public boolean isApiVersion(String prospective) { + return apiVersion.equals(prospective); + } + + + public String typeString(Class cls) { + return "application/"+cls.getSimpleName()+"+"+type.name().toLowerCase()+ + (apiVersion==null?BLANK:";version="+apiVersion); + } + + protected abstract EClient client() throws CadiException; + + + public Future create(final String pathinfo, final String contentType, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureCreate(df.getTypeClass()); + } + + public Future create(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureCreate(df.getTypeClass()); + } + + public Future create(String pathinfo, Class cls, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureCreate(df.getTypeClass()); + } + + public Future create(String pathinfo, Class cls) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(null); + client.send(); + return client.futureCreate(cls); + } + + public Future create(String pathinfo, String contentType) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(null); + client.send(); + return client.futureCreate(Void.class); + } + + public Future create(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(content); + client.send(); + return client.futureCreate(Void.class); + } + + + /** + * Post Data in WWW expected format, with the format tag1=value1&tag2=value2, etc + * Note Shortcut: + * Because typically, you will want to have a variable as value, you can type, as long as tag ends with "=" + * postForm(..., "tag1=value1","tag2=",var2); + * @param pathinfo + * @param df + * @param cls + * @param formParam + * @return + * @throws APIException + * @throws CadiException + */ + public Future postForm(String pathinfo, final RosettaDF df, final String ... formParam) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,FORM_ENCODED); + switch(type) { + case JSON: + client.addHeader(ACCEPT, APPL_JSON); + break; + case XML: + client.addHeader(ACCEPT, APPL_XML); + break; + default: + break; + } + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + PrintStream ps; + if(os instanceof PrintStream) { + ps = (PrintStream)os; + } else { + ps = new PrintStream(os); + } + boolean first = true; + for(String fp : formParam) { + if(fp!=null) { + if(first) { + first = false; + } else { + ps.print('&'); + } + if(fp.endsWith("=")) { + first = true; + } + ps.print(fp); + } + } + }}); + client.send(); + return client.futureRead(df,TYPE.JSON); + } + + /** + * Read String, using POST for keyInfo + * + * @param pathinfo + * @param df + * @param t + * @param resp + * @return + * @throws APIException + * @throws CadiException + */ + public Future readPost(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureReadString(); + } + + /** + * Read using POST for keyInfo, responding with marshaled Objects + * + * @param pathinfo + * @param df + * @param t + * @param resp + * @return + * @throws APIException + * @throws CadiException + */ + public Future readPost(String pathinfo, final RosettaDF df, final T t, final RosettaDF resp) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureRead(resp,resp.getOutType()); + } + + public Future readPost(String pathinfo, String contentType, String ... headers) throws CadiException, APIException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + }}); + client.send(); + return client.futureReadString(); + } + + public Future read(String pathinfo, String accept, String ... headers) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, accept); + + for(int i=1;i Future read(String pathinfo, String accept, RosettaDF df, String ... headers) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, accept); + for(int i=1;i Future read(String pathinfo, RosettaDF df,String ... headers) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, typeString(df.getTypeClass())); + for(int i=1;i Future read(String pathinfo, Class cls, RosettaDF df) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(null); + client.send(); + return client.futureRead(df,type); + } + + public Future update(String pathinfo, String contentType, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public Future updateRespondString(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + //String s = df.newData().out(type).load(t).asString(); + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureReadString(); + } + + public Future update(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(content); + client.send(); + return client.futureReadString(); + } + + + + + public Future update(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public Future update(String pathinfo, Class cls, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + + + /** + * A method to update with a VOID + * @param pathinfo + * @param resp + * @param expected + * @return + * @throws APIException + * @throws CadiException + */ + public Future update(String pathinfo) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(Void.class)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + +// client.setPayload(new EClient.Transfer() { +// @Override +// public void transfer(OutputStream os) throws IOException, APIException { +// } +// }); + client.send(); + return client.future(null); + } + + + public Future delete(String pathinfo, String contentType, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public Future delete(String pathinfo, Class cls, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public Future delete(String pathinfo, final RosettaDF df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + + client.send(); + return client.future(t); + } + + + public Future delete(String pathinfo, Class cls) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(null); + client.send(); + return client.future((T)null); + } + + public Future delete(String pathinfo, String contentType) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(null); + client.send(); + return client.future(null); + } + + public Future transfer(final HttpServletRequest req, final HttpServletResponse resp, final String pathParam, final int expected) throws CadiException, APIException { + EClient client = client(); + URI uri; + try { + uri = new URI(req.getRequestURI()); + } catch (Exception e) { + throw new CadiException("Invalid incoming URI",e); + } + String name; + for(Enumeration en = req.getHeaderNames();en.hasMoreElements();) { + name = en.nextElement(); + client.addHeader(name,req.getHeader(name)); + } + client.setQueryParams(req.getQueryString()); + client.setFragment(uri.getFragment()); + client.setPathInfo(pathParam); + String meth = req.getMethod(); + client.setMethod(meth); + if(!"GET".equals(meth)) { + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + final ServletInputStream is = req.getInputStream(); + int read; + // reuse Buffers + Pooled pbuff = buffPool.get(); + try { + while((read=is.read(pbuff.content))>=0) { + os.write(pbuff.content,0,read); + } + } finally { + pbuff.done(); + } + } + }); + } + client.send(); + return client.future(resp, expected); + } + + private class ParsePath { + private final String path; + private final int query; + private final int queryEnd; + private final int pound; + private final String queryParams; + + public ParsePath(final String origPath) { + path = origPath; + if(origPath==null) { + query=queryEnd=pound=-1; + queryParams=null; + } else { + query = origPath.indexOf('?'); + pound = origPath.indexOf('#'); + queryEnd = pound>=0?pound:path.length(); + if(oneCallQueryParams==null) { + if(query>=0) { + queryParams = path.substring(query+1,queryEnd); + } else { + queryParams=null; + } + } else { + if(query>=0) { + queryParams = oneCallQueryParams + '&' + path.substring(query+1,queryEnd); + } else { + queryParams = oneCallQueryParams; + } + oneCallQueryParams = null; + } + } + } + + public String path() { + if(query>=0) { + if(pound>=0) { + return path.substring(pound+1); + } + return path.substring(0,query); + } else if(pound>=0) { + return path.substring(0,pound); + } else { + return path; + } + } + + public String query() { + return queryParams; + } + + public String frag() { + if(pound>=0) { + return path.substring(pound+1); + } else { + return null; + } + } + } + + public String toString() { + return uri.toString(); + } + + public URI getURI() { + return uri; + } + + public void setQueryParams(final String queryParams) { + oneCallQueryParams=queryParams; + } } \ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java index fecb847b..e9de27e7 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java @@ -22,39 +22,39 @@ package org.onap.aaf.cadi.client; public class Result { - public final int code; - public final T value; - public final String error; + public final int code; + public final T value; + public final String error; - private Result(int code, T value, String error) { - this.code = code; - this.value = value; - this.error = error; - } + private Result(int code, T value, String error) { + this.code = code; + this.value = value; + this.error = error; + } - public static Result ok(int code,T t) { - return new Result(code,t,null); - } - - public static Result err(int code,String body) { - return new Result(code,null,body); - } + public static Result ok(int code,T t) { + return new Result(code,t,null); + } + + public static Result err(int code,String body) { + return new Result(code,null,body); + } - public static Result err(Result r) { - return new Result(r.code,null,r.error); - } + public static Result err(Result r) { + return new Result(r.code,null,r.error); + } - public boolean isOK() { - return error==null; - } - - public String toString() { - StringBuilder sb = new StringBuilder("Code: "); - sb.append(code); - if(error!=null) { - sb.append(" = "); - sb.append(error); - } - return sb.toString(); - } + public boolean isOK() { + return error==null; + } + + public String toString() { + StringBuilder sb = new StringBuilder("Code: "); + sb.append(code); + if(error!=null) { + sb.append(" = "); + sb.append(error); + } + return sb.toString(); + } } \ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java index 8208efe1..58e7718d 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java @@ -35,37 +35,37 @@ import org.onap.aaf.misc.env.APIException; * @param */ public abstract class Retryable { - // be able to hold state for consistent Connections. Not required for all connection types. - public Rcli lastClient; - private Locator.Item item; - - public Retryable() { - lastClient = null; - item = null; - } + // be able to hold state for consistent Connections. Not required for all connection types. + public Rcli lastClient; + private Locator.Item item; + + public Retryable() { + lastClient = null; + item = null; + } - public Retryable(Retryable ret) { - lastClient = ret.lastClient; - item = ret.item; - } + public Retryable(Retryable ret) { + lastClient = ret.lastClient; + item = ret.item; + } - public Locator.Item item(Locator.Item item) { - lastClient = null; - this.item = item; - return item; - } - public Locator.Item item() { - return item; - } - - public abstract RET code(Rcli client) throws CadiException, ConnectException, APIException; + public Locator.Item item(Locator.Item item) { + lastClient = null; + this.item = item; + return item; + } + public Locator.Item item() { + return item; + } + + public abstract RET code(Rcli client) throws CadiException, ConnectException, APIException; - /** - * Note, Retryable is tightly coupled to the Client Utilizing. It will not be the wrong type. - * @return - */ - @SuppressWarnings("unchecked") - public Rcli lastClient() { - return (Rcli)lastClient; - } + /** + * Note, Retryable is tightly coupled to the Client Utilizing. It will not be the wrong type. + * @return + */ + @SuppressWarnings("unchecked") + public Rcli lastClient() { + return (Rcli)lastClient; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java index 787c5c29..3c38ff8d 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java @@ -31,24 +31,24 @@ import org.onap.aaf.cadi.client.AbsAuthentication; import org.onap.aaf.cadi.config.SecurityInfoC; public class HAuthorizationHeader extends AbsAuthentication { - - public HAuthorizationHeader(SecurityInfoC si, String user, String headValue) throws IOException { - super(si,user,headValue==null?null:headValue.getBytes()); - } + + public HAuthorizationHeader(SecurityInfoC si, String user, String headValue) throws IOException { + super(si,user,headValue==null?null:headValue.getBytes()); + } - @Override - public void setSecurity(HttpURLConnection huc) throws CadiException { - if(isDenied()) { - throw new CadiException(REPEAT_OFFENDER); - } - try { - huc.addRequestProperty(AUTHORIZATION , headValue()); - } catch (IOException e) { - throw new CadiException(e); - } - if(securityInfo!=null && huc instanceof HttpsURLConnection) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); - } - } + @Override + public void setSecurity(HttpURLConnection huc) throws CadiException { + if(isDenied()) { + throw new CadiException(REPEAT_OFFENDER); + } + try { + huc.addRequestProperty(AUTHORIZATION , headValue()); + } catch (IOException e) { + throw new CadiException(e); + } + if(securityInfo!=null && huc instanceof HttpsURLConnection) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); + } + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java index 9e86c7fb..e4ab6d72 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java @@ -31,38 +31,38 @@ import org.onap.aaf.cadi.config.SecurityInfoC; import org.onap.aaf.cadi.principal.BasicPrincipal; public class HBasicAuthSS extends HAuthorizationHeader implements BasicAuth { - public HBasicAuthSS(SecurityInfoC si, String user, String password) throws IOException { - super(si, user, "Basic " + Symm.base64noSplit.encode(user + ':' + password)); - } + public HBasicAuthSS(SecurityInfoC si, String user, String password) throws IOException { + super(si, user, "Basic " + Symm.base64noSplit.encode(user + ':' + password)); + } - public HBasicAuthSS(SecurityInfoC si) throws IOException { - this(si,si.access.getProperty(Config.AAF_APPID, null), - si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false)); - } - - public HBasicAuthSS(SecurityInfoC si, boolean setDefault) throws IOException { - this(si,si.access.getProperty(Config.AAF_APPID, null), - si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false),setDefault); - } - + public HBasicAuthSS(SecurityInfoC si) throws IOException { + this(si,si.access.getProperty(Config.AAF_APPID, null), + si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false)); + } + + public HBasicAuthSS(SecurityInfoC si, boolean setDefault) throws IOException { + this(si,si.access.getProperty(Config.AAF_APPID, null), + si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false),setDefault); + } + - public HBasicAuthSS(SecurityInfoC si, String user, String pass, boolean asDefault) throws IOException { - this(si, user,pass); - if(asDefault) { - si.set(this); - } - } - - public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC si) throws IOException { - this(si, bp.getName(),new String(bp.getCred())); - } - - public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC si, boolean asDefault) throws IOException { - this(si, bp.getName(),new String(bp.getCred())); - if(asDefault) { - si.set(this); - } - } + public HBasicAuthSS(SecurityInfoC si, String user, String pass, boolean asDefault) throws IOException { + this(si, user,pass); + if(asDefault) { + si.set(this); + } + } + + public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC si) throws IOException { + this(si, bp.getName(),new String(bp.getCred())); + } + + public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC si, boolean asDefault) throws IOException { + this(si, bp.getName(),new String(bp.getCred())); + if(asDefault) { + si.set(this); + } + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java index a3dac7da..1d3d9547 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java @@ -54,388 +54,388 @@ import org.onap.aaf.misc.rosetta.env.RosettaDF; * */ public class HClient implements EClient { - private URI uri; - private ArrayList
    headers; - private String meth; - private String pathinfo; - private String query; - private String fragment; - private Transfer transfer; - private SecuritySetter ss; - private HttpURLConnection huc; - private int connectTimeout; + private URI uri; + private ArrayList
    headers; + private String meth; + private String pathinfo; + private String query; + private String fragment; + private Transfer transfer; + private SecuritySetter ss; + private HttpURLConnection huc; + private int connectTimeout; - public HClient(SecuritySetter ss, URI uri,int connectTimeout) throws LocatorException { - if (uri == null) { - throw new LocatorException("No Service available to call"); - } - this.uri = uri; - this.ss = ss; - this.connectTimeout = connectTimeout; - pathinfo = query = fragment = null; - } + public HClient(SecuritySetter ss, URI uri,int connectTimeout) throws LocatorException { + if (uri == null) { + throw new LocatorException("No Service available to call"); + } + this.uri = uri; + this.ss = ss; + this.connectTimeout = connectTimeout; + pathinfo = query = fragment = null; + } - @Override - public void setMethod(String meth) { - this.meth = meth; - } + @Override + public void setMethod(String meth) { + this.meth = meth; + } - @Override - public void setPathInfo(String pathinfo) { - this.pathinfo = pathinfo; - } + @Override + public void setPathInfo(String pathinfo) { + this.pathinfo = pathinfo; + } - @Override - public void setPayload(Transfer transfer) { - this.transfer = transfer; - } - - @Override - public void addHeader(String tag, String value) { - if (headers == null) - headers = new ArrayList<>(); - headers.add(new Header(tag, value)); - } + @Override + public void setPayload(Transfer transfer) { + this.transfer = transfer; + } + + @Override + public void addHeader(String tag, String value) { + if (headers == null) + headers = new ArrayList<>(); + headers.add(new Header(tag, value)); + } - @Override - public void setQueryParams(String q) { - query = q; - } + @Override + public void setQueryParams(String q) { + query = q; + } - @Override - public void setFragment(String f) { - fragment = f; - } + @Override + public void setFragment(String f) { + fragment = f; + } - @Override - public void send() throws APIException { - try { - // Build URL from given URI plus current Settings - if(uri.getPath()==null) { - throw new APIException("Invalid URL entered for HClient"); - } - StringBuilder pi=null; - if(pathinfo!=null) { // additional pathinfo - pi = new StringBuilder(uri.getPath()); - if(!pathinfo.startsWith("/")) { - pi.append('/'); - } - pi.append(pathinfo); - } - URI sendURI = new URI( - uri.getScheme(), - uri.getUserInfo(), - uri.getHost(), - uri.getPort(), - pi==null?uri.getPath():pi.toString(), - query==null?uri.getQuery():query, - fragment==null?uri.getFragment():fragment - ); - huc = getConnection(sendURI, pi); - huc.setRequestMethod(meth); - if(ss!=null) { - ss.setSecurity(huc); - } - if (headers != null) - for (Header d : headers) { - huc.addRequestProperty(d.tag, d.value); - } - huc.setDoInput(true); - huc.setDoOutput(true); - huc.setUseCaches(false); - huc.setConnectTimeout(connectTimeout); - huc.connect(); - if (transfer != null) { - transfer.transfer(huc.getOutputStream()); - } - // TODO other settings? There's a bunch here. - } catch (Exception e) { - throw new APIException(e); - } finally { // ensure all these are reset after sends - meth=pathinfo=null; - if(headers!=null) { - headers.clear(); - } - pathinfo = query = fragment = ""; - } - } - - public URI getURI() { - return uri; - } + @Override + public void send() throws APIException { + try { + // Build URL from given URI plus current Settings + if(uri.getPath()==null) { + throw new APIException("Invalid URL entered for HClient"); + } + StringBuilder pi=null; + if(pathinfo!=null) { // additional pathinfo + pi = new StringBuilder(uri.getPath()); + if(!pathinfo.startsWith("/")) { + pi.append('/'); + } + pi.append(pathinfo); + } + URI sendURI = new URI( + uri.getScheme(), + uri.getUserInfo(), + uri.getHost(), + uri.getPort(), + pi==null?uri.getPath():pi.toString(), + query==null?uri.getQuery():query, + fragment==null?uri.getFragment():fragment + ); + huc = getConnection(sendURI, pi); + huc.setRequestMethod(meth); + if(ss!=null) { + ss.setSecurity(huc); + } + if (headers != null) + for (Header d : headers) { + huc.addRequestProperty(d.tag, d.value); + } + huc.setDoInput(true); + huc.setDoOutput(true); + huc.setUseCaches(false); + huc.setConnectTimeout(connectTimeout); + huc.connect(); + if (transfer != null) { + transfer.transfer(huc.getOutputStream()); + } + // TODO other settings? There's a bunch here. + } catch (Exception e) { + throw new APIException(e); + } finally { // ensure all these are reset after sends + meth=pathinfo=null; + if(headers!=null) { + headers.clear(); + } + pathinfo = query = fragment = ""; + } + } + + public URI getURI() { + return uri; + } - public int timeout() { - return connectTimeout; - } - - protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException { - URL url = new URI( - uri.getScheme(), - uri.getUserInfo(), - uri.getHost(), - uri.getPort(), - pi==null?uri.getPath():pi.toString(), - query, - fragment).toURL(); - return (HttpURLConnection) url.openConnection(); - } - - public abstract class HFuture extends Future { - protected HttpURLConnection huc; - protected int respCode; - protected IOException exception; - protected StringBuilder errContent; - - public HFuture(final HttpURLConnection huc) { - this.huc = huc; - } - - protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{ - return respCode == 200; - }; - - @Override - public final boolean get(int timeout) throws CadiException { - try { - huc.setReadTimeout(timeout); - respCode = huc.getResponseCode(); - ss.setLastResponse(respCode); - if(evalInfo(huc)) { - return true; - } else { - extractError(); - return false; - } - } catch (IOException | APIException e) { - throw new CadiException(e); - } finally { - close(); - } - } - - private void extractError() { - InputStream is = huc.getErrorStream(); - try { - if(is==null) { - is = huc.getInputStream(); - } - if(is!=null) { - errContent = new StringBuilder(); - int c; - while((c=is.read())>=0) { - errContent.append((char)c); - } - } - } catch (IOException e) { - exception = e; - } - } - - // Typically only used by Read - public StringBuilder inputStreamToString(InputStream is) { - // Avoids Carriage returns, and is reasonably efficient, given - // the buffer reads. - try { - StringBuilder sb = new StringBuilder(); - Reader rdr = new InputStreamReader(is); - try { - char[] buf = new char[256]; - int read; - while ((read = rdr.read(buf)) >= 0) { - sb.append(buf, 0, read); - } - } finally { - rdr.close(); - } - return sb; - } catch (IOException e) { - exception = e; - return null; - } - } - - - @Override - public int code() { - return respCode; - } - - public HttpURLConnection huc() { - return huc; - } - - public IOException exception() { - return exception; - } - - @Override - public String header(String tag) { - return huc.getHeaderField(tag); - } - - public void close() { - if(huc!=null) { - huc.disconnect(); - } - } - } + public int timeout() { + return connectTimeout; + } + + protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException { + URL url = new URI( + uri.getScheme(), + uri.getUserInfo(), + uri.getHost(), + uri.getPort(), + pi==null?uri.getPath():pi.toString(), + query, + fragment).toURL(); + return (HttpURLConnection) url.openConnection(); + } + + public abstract class HFuture extends Future { + protected HttpURLConnection huc; + protected int respCode; + protected IOException exception; + protected StringBuilder errContent; + + public HFuture(final HttpURLConnection huc) { + this.huc = huc; + } + + protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{ + return respCode == 200; + }; + + @Override + public final boolean get(int timeout) throws CadiException { + try { + huc.setReadTimeout(timeout); + respCode = huc.getResponseCode(); + ss.setLastResponse(respCode); + if(evalInfo(huc)) { + return true; + } else { + extractError(); + return false; + } + } catch (IOException | APIException e) { + throw new CadiException(e); + } finally { + close(); + } + } + + private void extractError() { + InputStream is = huc.getErrorStream(); + try { + if(is==null) { + is = huc.getInputStream(); + } + if(is!=null) { + errContent = new StringBuilder(); + int c; + while((c=is.read())>=0) { + errContent.append((char)c); + } + } + } catch (IOException e) { + exception = e; + } + } + + // Typically only used by Read + public StringBuilder inputStreamToString(InputStream is) { + // Avoids Carriage returns, and is reasonably efficient, given + // the buffer reads. + try { + StringBuilder sb = new StringBuilder(); + Reader rdr = new InputStreamReader(is); + try { + char[] buf = new char[256]; + int read; + while ((read = rdr.read(buf)) >= 0) { + sb.append(buf, 0, read); + } + } finally { + rdr.close(); + } + return sb; + } catch (IOException e) { + exception = e; + return null; + } + } + + + @Override + public int code() { + return respCode; + } + + public HttpURLConnection huc() { + return huc; + } + + public IOException exception() { + return exception; + } + + @Override + public String header(String tag) { + return huc.getHeaderField(tag); + } + + public void close() { + if(huc!=null) { + huc.disconnect(); + } + } + } - @Override - public Future futureCreate(Class t) { - return new HFuture(huc) { - public boolean evalInfo(HttpURLConnection huc) { - return respCode==201; - } + @Override + public Future futureCreate(Class t) { + return new HFuture(huc) { + public boolean evalInfo(HttpURLConnection huc) { + return respCode==201; + } - @Override - public String body() { - if (errContent != null) { - return errContent.toString(); - } - return ""; - } - }; - } + @Override + public String body() { + if (errContent != null) { + return errContent.toString(); + } + return ""; + } + }; + } - @Override - public Future futureReadString() { - return new HFuture(huc) { - public boolean evalInfo(HttpURLConnection huc) throws IOException { - if (respCode == 200) { - StringBuilder sb = inputStreamToString(huc.getInputStream()); - if (sb != null) { - value = sb.toString(); - } - return true; - } - return false; - } + @Override + public Future futureReadString() { + return new HFuture(huc) { + public boolean evalInfo(HttpURLConnection huc) throws IOException { + if (respCode == 200) { + StringBuilder sb = inputStreamToString(huc.getInputStream()); + if (sb != null) { + value = sb.toString(); + } + return true; + } + return false; + } - @Override - public String body() { - if (value != null) { - return value; - } else if (errContent != null) { - return errContent.toString(); - } - return ""; - } + @Override + public String body() { + if (value != null) { + return value; + } else if (errContent != null) { + return errContent.toString(); + } + return ""; + } - }; - } + }; + } - @Override - public Future futureRead(final RosettaDF df, final TYPE type) { - return new HFuture(huc) { - private Data data; + @Override + public Future futureRead(final RosettaDF df, final TYPE type) { + return new HFuture(huc) { + private Data data; - public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException { - if (respCode == 200) { - data = df.newData().in(type).load(huc.getInputStream()); - value = data.asObject(); - return true; - } - return false; - } + public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException { + if (respCode == 200) { + data = df.newData().in(type).load(huc.getInputStream()); + value = data.asObject(); + return true; + } + return false; + } - @Override - public String body() { - if (data != null) { - try { - return data.asString(); - } catch (APIException e) { - } - } else if (errContent != null) { - return errContent.toString(); - } - return ""; - } - }; - } + @Override + public String body() { + if (data != null) { + try { + return data.asString(); + } catch (APIException e) { + } + } else if (errContent != null) { + return errContent.toString(); + } + return ""; + } + }; + } - @Override - public Future future(final T t) { - return new HFuture(huc) { - public boolean evalInfo(HttpURLConnection huc) { - if (respCode == 200) { - value = t; - return true; - } - return false; - } + @Override + public Future future(final T t) { + return new HFuture(huc) { + public boolean evalInfo(HttpURLConnection huc) { + if (respCode == 200) { + value = t; + return true; + } + return false; + } - @Override - public String body() { - if (errContent != null) { - return errContent.toString(); - } - return Integer.toString(respCode); - } - }; - } + @Override + public String body() { + if (errContent != null) { + return errContent.toString(); + } + return Integer.toString(respCode); + } + }; + } - @Override - public Future future(final HttpServletResponse resp, final int expected) throws APIException { - return new HFuture(huc) { - public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException { - resp.setStatus(respCode); - int read; - InputStream is; - OutputStream os = resp.getOutputStream(); - if(respCode==expected) { - is = huc.getInputStream(); - // reuse Buffers - Pooled pbuff = Rcli.buffPool.get(); - try { - while((read=is.read(pbuff.content))>=0) { - os.write(pbuff.content,0,read); - } - } finally { - pbuff.done(); - } - return true; - } else { - is = huc.getErrorStream(); - if(is==null) { - is = huc.getInputStream(); - } - if(is!=null) { - errContent = new StringBuilder(); - Pooled pbuff = Rcli.buffPool.get(); - try { - while((read=is.read(pbuff.content))>=0) { - os.write(pbuff.content,0,read); - } - } finally { - pbuff.done(); - } - } - } - return false; - } + @Override + public Future future(final HttpServletResponse resp, final int expected) throws APIException { + return new HFuture(huc) { + public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException { + resp.setStatus(respCode); + int read; + InputStream is; + OutputStream os = resp.getOutputStream(); + if(respCode==expected) { + is = huc.getInputStream(); + // reuse Buffers + Pooled pbuff = Rcli.buffPool.get(); + try { + while((read=is.read(pbuff.content))>=0) { + os.write(pbuff.content,0,read); + } + } finally { + pbuff.done(); + } + return true; + } else { + is = huc.getErrorStream(); + if(is==null) { + is = huc.getInputStream(); + } + if(is!=null) { + errContent = new StringBuilder(); + Pooled pbuff = Rcli.buffPool.get(); + try { + while((read=is.read(pbuff.content))>=0) { + os.write(pbuff.content,0,read); + } + } finally { + pbuff.done(); + } + } + } + return false; + } - @Override - public String body() { - return errContent==null?null:errContent.toString(); - } - }; - } + @Override + public String body() { + return errContent==null?null:errContent.toString(); + } + }; + } - private static class Header { - public final String tag; - public final String value; + private static class Header { + public final String tag; + public final String value; - public Header(String t, String v) { - this.tag = t; - this.value = v; - } - - public String toString() { - return tag + '=' + value; - } - } - - public String toString() { - return "HttpURLConnection Client configured to " + uri.toString(); - } + public Header(String t, String v) { + this.tag = t; + this.value = v; + } + + public String toString() { + return tag + '=' + value; + } + } + + public String toString() { + return "HttpURLConnection Client configured to " + uri.toString(); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java index 772a499c..da349efc 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java @@ -41,202 +41,202 @@ import org.onap.aaf.cadi.client.Retryable; import org.onap.aaf.misc.env.APIException; public class HMangr { - private String apiVersion; - private int readTimeout, connectionTimeout; - public final Locator loc; - private Access access; - - public HMangr(Access access, Locator loc) throws LocatorException { - readTimeout = 10000; - connectionTimeout=3000; - if(loc == null) { - throw new LocatorException("Null Locator passed"); - } - this.loc = loc; - this.access = access; - } + private String apiVersion; + private int readTimeout, connectionTimeout; + public final Locator loc; + private Access access; + + public HMangr(Access access, Locator loc) throws LocatorException { + readTimeout = 10000; + connectionTimeout=3000; + if(loc == null) { + throw new LocatorException("Null Locator passed"); + } + this.loc = loc; + this.access = access; + } - /** - * Reuse the same service. This is helpful for multiple calls that change service side cached data so that - * there is not a speed issue. - * - * If the service goes down, another service will be substituted, if available. - * - * @param access - * @param loc - * @param ss - * @param item - * @param retryable - * @return - * @throws URISyntaxException - * @throws Exception - */ - public RET same(SecuritySetter ss, Retryable retryable) throws APIException, CadiException, LocatorException { - RET ret = null; - boolean retry = true; - Rcli client = retryable.lastClient(); - try { - do { - Item item; - // if no previous state, get the best - if(retryable.item()==null) { - item = loc.best(); - if(item==null) { - throw new LocatorException("No Services Found for " + loc); - } - retryable.item(item); - retryable.lastClient = null; - } - if(client==null) { - item = retryable.item(); - URI uri=loc.get(item); - if(uri==null) { - loc.invalidate(retryable.item()); - if(loc.hasItems()) { - retryable.item(loc.next(retryable.item())); - continue; - } else { - throw new LocatorException("No clients available for " + loc.toString()); - } - } - client = new HRcli(this, uri,item,ss) - .connectionTimeout(connectionTimeout) - .readTimeout(readTimeout) - .apiVersion(apiVersion); - } else { - client.setSecuritySetter(ss); - } - - retry = false; - try { - ret = retryable.code(client); - } catch (APIException | CadiException e) { - item = retryable.item(); - loc.invalidate(item); - retryable.item(loc.next(item)); - try { - Throwable ec = e.getCause(); - if(ec instanceof java.net.ConnectException) { - if(client!=null && loc.hasItems()) { - access.log(Level.WARN,"Connection refused, trying next available service"); - retry = true; - } else { - throw new CadiException("Connection refused, no more services to try"); - } - } else if(ec instanceof java.net.SocketException) { - if(client!=null && loc.hasItems()) { - access.log(Level.WARN,"Socket prematurely closed, trying next available service"); - retry = true; - } else { - throw new CadiException("Socket prematurely closed, no more services to try"); - } - } else if(ec instanceof SocketException) { - if("java.net.SocketException: Connection reset".equals(ec.getMessage())) { - access.log(Level.ERROR, ec.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); - } - retryable.item(null); - throw e; - } else { - retryable.item(null); - throw e; - } - } finally { - client = null; - } - } catch (ConnectException e) { - item = retryable.item(); - loc.invalidate(item); - retryable.item(loc.next(item)); - } - } while(retry); - } finally { - retryable.lastClient = client; - } - return ret; - } - - - public RET best(SecuritySetter ss, Retryable retryable) throws LocatorException, CadiException, APIException { - retryable.item(loc.best()); - return same(ss,retryable); - } - public RET all(SecuritySetter ss, Retryable retryable) throws LocatorException, CadiException, APIException { - return oneOf(ss,retryable,true,null); - } + /** + * Reuse the same service. This is helpful for multiple calls that change service side cached data so that + * there is not a speed issue. + * + * If the service goes down, another service will be substituted, if available. + * + * @param access + * @param loc + * @param ss + * @param item + * @param retryable + * @return + * @throws URISyntaxException + * @throws Exception + */ + public RET same(SecuritySetter ss, Retryable retryable) throws APIException, CadiException, LocatorException { + RET ret = null; + boolean retry = true; + Rcli client = retryable.lastClient(); + try { + do { + Item item; + // if no previous state, get the best + if(retryable.item()==null) { + item = loc.best(); + if(item==null) { + throw new LocatorException("No Services Found for " + loc); + } + retryable.item(item); + retryable.lastClient = null; + } + if(client==null) { + item = retryable.item(); + URI uri=loc.get(item); + if(uri==null) { + loc.invalidate(retryable.item()); + if(loc.hasItems()) { + retryable.item(loc.next(retryable.item())); + continue; + } else { + throw new LocatorException("No clients available for " + loc.toString()); + } + } + client = new HRcli(this, uri,item,ss) + .connectionTimeout(connectionTimeout) + .readTimeout(readTimeout) + .apiVersion(apiVersion); + } else { + client.setSecuritySetter(ss); + } + + retry = false; + try { + ret = retryable.code(client); + } catch (APIException | CadiException e) { + item = retryable.item(); + loc.invalidate(item); + retryable.item(loc.next(item)); + try { + Throwable ec = e.getCause(); + if(ec instanceof java.net.ConnectException) { + if(client!=null && loc.hasItems()) { + access.log(Level.WARN,"Connection refused, trying next available service"); + retry = true; + } else { + throw new CadiException("Connection refused, no more services to try"); + } + } else if(ec instanceof java.net.SocketException) { + if(client!=null && loc.hasItems()) { + access.log(Level.WARN,"Socket prematurely closed, trying next available service"); + retry = true; + } else { + throw new CadiException("Socket prematurely closed, no more services to try"); + } + } else if(ec instanceof SocketException) { + if("java.net.SocketException: Connection reset".equals(ec.getMessage())) { + access.log(Level.ERROR, ec.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); + } + retryable.item(null); + throw e; + } else { + retryable.item(null); + throw e; + } + } finally { + client = null; + } + } catch (ConnectException e) { + item = retryable.item(); + loc.invalidate(item); + retryable.item(loc.next(item)); + } + } while(retry); + } finally { + retryable.lastClient = client; + } + return ret; + } + + + public RET best(SecuritySetter ss, Retryable retryable) throws LocatorException, CadiException, APIException { + retryable.item(loc.best()); + return same(ss,retryable); + } + public RET all(SecuritySetter ss, Retryable retryable) throws LocatorException, CadiException, APIException { + return oneOf(ss,retryable,true,null); + } - public RET all(SecuritySetter ss, Retryable retryable,boolean notify) throws LocatorException, CadiException, APIException { - return oneOf(ss,retryable,notify,null); - } - - public RET oneOf(SecuritySetter ss, Retryable retryable,boolean notify,String host) throws LocatorException, CadiException, APIException { - RET ret = null; - // make sure we have all current references: - loc.refresh(); - for(Item li=loc.first();li!=null;li=loc.next(li)) { - URI uri=loc.get(li); - if(host!=null && !host.equals(uri.getHost())) { - break; - } - try { - ret = retryable.code(new HRcli(this,uri,li,ss)); - access.log(Level.DEBUG,"Success calling",uri,"during call to all services"); - } catch (APIException | CadiException e) { - Throwable t = e.getCause(); - if(t!=null && t instanceof ConnectException) { - loc.invalidate(li); - access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); - } else if(t instanceof SSLHandshakeException) { - access.log(Level.ERROR,t.getMessage()); - loc.invalidate(li); - } else if(t instanceof SocketException) { - if("java.net.SocketException: Connection reset".equals(t.getMessage())) { - access.log(Level.ERROR, t.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); - } - retryable.item(null); - throw e; - } else { - throw e; - } - } catch (ConnectException e) { - loc.invalidate(li); - access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); - } - } - - if(ret == null && notify) - throw new LocatorException("No available clients to call"); - return ret; - } - + public RET all(SecuritySetter ss, Retryable retryable,boolean notify) throws LocatorException, CadiException, APIException { + return oneOf(ss,retryable,notify,null); + } + + public RET oneOf(SecuritySetter ss, Retryable retryable,boolean notify,String host) throws LocatorException, CadiException, APIException { + RET ret = null; + // make sure we have all current references: + loc.refresh(); + for(Item li=loc.first();li!=null;li=loc.next(li)) { + URI uri=loc.get(li); + if(host!=null && !host.equals(uri.getHost())) { + break; + } + try { + ret = retryable.code(new HRcli(this,uri,li,ss)); + access.log(Level.DEBUG,"Success calling",uri,"during call to all services"); + } catch (APIException | CadiException e) { + Throwable t = e.getCause(); + if(t!=null && t instanceof ConnectException) { + loc.invalidate(li); + access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); + } else if(t instanceof SSLHandshakeException) { + access.log(Level.ERROR,t.getMessage()); + loc.invalidate(li); + } else if(t instanceof SocketException) { + if("java.net.SocketException: Connection reset".equals(t.getMessage())) { + access.log(Level.ERROR, t.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); + } + retryable.item(null); + throw e; + } else { + throw e; + } + } catch (ConnectException e) { + loc.invalidate(li); + access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); + } + } + + if(ret == null && notify) + throw new LocatorException("No available clients to call"); + return ret; + } + - public void close() { - // TODO Anything here? - } + public void close() { + // TODO Anything here? + } - public HMangr readTimeout(int timeout) { - this.readTimeout = timeout; - return this; - } + public HMangr readTimeout(int timeout) { + this.readTimeout = timeout; + return this; + } - public int readTimeout() { - return readTimeout; - } - - public void connectionTimeout(int t) { - connectionTimeout = t; - } + public int readTimeout() { + return readTimeout; + } + + public void connectionTimeout(int t) { + connectionTimeout = t; + } - public int connectionTimeout() { - return connectionTimeout; - } + public int connectionTimeout() { + return connectionTimeout; + } - public HMangr apiVersion(String version) { - apiVersion = version; - return this; - } + public HMangr apiVersion(String version) { + apiVersion = version; + return this; + } - public String apiVersion() { - return apiVersion; - } + public String apiVersion() { + return apiVersion; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java index b857f3ad..0f1c8b41 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java @@ -31,15 +31,15 @@ import org.onap.aaf.cadi.client.AbsAuthentication; import org.onap.aaf.cadi.config.SecurityInfoC; public class HNoAuthSS extends AbsAuthentication { - public HNoAuthSS(SecurityInfoC si) throws IOException { - super(si,"noauth",null); - } + public HNoAuthSS(SecurityInfoC si) throws IOException { + super(si,"noauth",null); + } - @Override - public void setSecurity(HttpURLConnection client) throws CadiException { - if(securityInfo!=null && client instanceof HttpsURLConnection) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)client); - } - } + @Override + public void setSecurity(HttpURLConnection client) throws CadiException { + if(securityInfo!=null && client instanceof HttpsURLConnection) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)client); + } + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java index 908b895b..674936d7 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java @@ -44,87 +44,87 @@ import org.onap.aaf.misc.env.Data.TYPE; * @param */ public class HRcli extends Rcli { - private HMangr hman; - private Item item; - private SecuritySetter ss; + private HMangr hman; + private Item item; + private SecuritySetter ss; - public HRcli(HMangr hman, Item locItem, SecuritySetter secSet) throws URISyntaxException, LocatorException { - item=locItem; - uri=hman.loc.get(locItem); - this.hman = hman; - ss=secSet; - type = TYPE.JSON; - apiVersion = hman.apiVersion(); - } + public HRcli(HMangr hman, Item locItem, SecuritySetter secSet) throws URISyntaxException, LocatorException { + item=locItem; + uri=hman.loc.get(locItem); + this.hman = hman; + ss=secSet; + type = TYPE.JSON; + apiVersion = hman.apiVersion(); + } - public HRcli(HMangr hman, URI uri, Item locItem, SecuritySetter secSet) { - item=locItem; - this.uri = uri; - this.hman = hman; - ss=secSet; - type = TYPE.JSON; - apiVersion = hman.apiVersion(); - } + public HRcli(HMangr hman, URI uri, Item locItem, SecuritySetter secSet) { + item=locItem; + this.uri = uri; + this.hman = hman; + ss=secSet; + type = TYPE.JSON; + apiVersion = hman.apiVersion(); + } - @Override - protected HRcli clone(URI uri, SecuritySetter ss) { - return new HRcli(hman,uri,item,ss); - } + @Override + protected HRcli clone(URI uri, SecuritySetter ss) { + return new HRcli(hman,uri,item,ss); + } - /** - * - * @return - * @throws APIException - * @throws DME2Exception - */ - protected EClient client() throws CadiException { - try { - if(uri==null) { - Item item = hman.loc.best(); - if(item==null) { - throw new CadiException("No service available for " + hman.loc.toString()); - } - uri = hman.loc.get(item); - } - return new HClient(ss,uri,connectionTimeout); - } catch (Exception e) { - throw new CadiException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.client.Rcli#setSecuritySetter(org.onap.aaf.cadi.SecuritySetter) - */ - @Override - public void setSecuritySetter(SecuritySetter ss) { - this.ss = ss; - } + /** + * + * @return + * @throws APIException + * @throws DME2Exception + */ + protected EClient client() throws CadiException { + try { + if(uri==null) { + Item item = hman.loc.best(); + if(item==null) { + throw new CadiException("No service available for " + hman.loc.toString()); + } + uri = hman.loc.get(item); + } + return new HClient(ss,uri,connectionTimeout); + } catch (Exception e) { + throw new CadiException(e); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.client.Rcli#setSecuritySetter(org.onap.aaf.cadi.SecuritySetter) + */ + @Override + public void setSecuritySetter(SecuritySetter ss) { + this.ss = ss; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.client.Rcli#getSecuritySetter() - */ - @Override - public SecuritySetter getSecuritySetter() { - return ss; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.client.Rcli#getSecuritySetter() + */ + @Override + public SecuritySetter getSecuritySetter() { + return ss; + } - public void invalidate() throws CadiException { - try { - hman.loc.invalidate(item); - } catch (Exception e) { - throw new CadiException(e); - } - } - - public HRcli setManager(HMangr hman) { - this.hman = hman; - return this; - } + public void invalidate() throws CadiException { + try { + hman.loc.invalidate(item); + } catch (Exception e) { + throw new CadiException(e); + } + } + + public HRcli setManager(HMangr hman) { + this.hman = hman; + return this; + } - public String toString() { - return uri.toString(); - } - + public String toString() { + return uri.toString(); + } + } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java index 8eb2dec3..d792be49 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java @@ -38,19 +38,19 @@ import org.onap.aaf.misc.env.APIException; */ public class HSecurityInfoInit implements SecurityInfoInit { - @Override - public SecuritySetter bestDefault(SecurityInfoC si) throws CadiException { - try { - if(si.defaultAlias!=null) { - si.set(new HX509SS(si)); - } else if(si.access.getProperty(Config.AAF_APPID, null)!=null && - si.access.getProperty(Config.AAF_APPPASS, null)!=null) { - si.set(new HBasicAuthSS(si)); - } - } catch (APIException | IOException e) { - throw new CadiException(e); - } - return si.defSS; - } + @Override + public SecuritySetter bestDefault(SecurityInfoC si) throws CadiException { + try { + if(si.defaultAlias!=null) { + si.set(new HX509SS(si)); + } else if(si.access.getProperty(Config.AAF_APPID, null)!=null && + si.access.getProperty(Config.AAF_APPPASS, null)!=null) { + si.set(new HBasicAuthSS(si)); + } + } catch (APIException | IOException e) { + throw new CadiException(e); + } + return si.defSS; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java index 873e0fe7..cd20585f 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java @@ -27,8 +27,8 @@ import java.net.HttpURLConnection; import org.onap.aaf.cadi.config.SecurityInfoC; public class HTokenSS extends HAuthorizationHeader { - public HTokenSS(final SecurityInfoC si, final String client_id, final String token) throws IOException { - super(si, client_id,"Bearer " + token); - } + public HTokenSS(final SecurityInfoC si, final String client_id, final String token) throws IOException { + super(si, client_id,"Bearer " + token); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java index d19c42e9..c527ed02 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java @@ -34,31 +34,31 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class HTransferSS extends AbsTransferSS { - public HTransferSS(TaggedPrincipal principal, String app) throws IOException { - super(principal, app); - } - - public HTransferSS(TaggedPrincipal principal, String app, SecurityInfoC si) { - super(principal, app, si); - } + public HTransferSS(TaggedPrincipal principal, String app) throws IOException { + super(principal, app); + } + + public HTransferSS(TaggedPrincipal principal, String app, SecurityInfoC si) { + super(principal, app, si); + } - @Override - public void setSecurity(HttpURLConnection huc) throws CadiException { - if(defSS==null) { - throw new CadiException("Need App Credentials to send message"); - } - defSS.setSecurity(huc); - if(value!=null) { - huc.addRequestProperty(Config.CADI_USER_CHAIN, value); - } - if(securityInfo!=null) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); - } - } - - @Override - public int setLastResponse(int respCode) { - return 0; - } + @Override + public void setSecurity(HttpURLConnection huc) throws CadiException { + if(defSS==null) { + throw new CadiException("Need App Credentials to send message"); + } + defSS.setSecurity(huc); + if(value!=null) { + huc.addRequestProperty(Config.CADI_USER_CHAIN, value); + } + if(securityInfo!=null) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); + } + } + + @Override + public int setLastResponse(int respCode) { + return 0; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java index c9ff59db..cb8e6ce0 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java @@ -45,108 +45,108 @@ import org.onap.aaf.misc.env.util.Chrono; public class HX509SS implements SecuritySetter { - private static final byte[] X509 = "x509 ".getBytes(); - private PrivateKey priv; - private byte[] pub; - private String cert; - private SecurityInfoC securityInfo; - private String algo; - private String alias; - private static int count = new SecureRandom().nextInt(); + private static final byte[] X509 = "x509 ".getBytes(); + private PrivateKey priv; + private byte[] pub; + private String cert; + private SecurityInfoC securityInfo; + private String algo; + private String alias; + private static int count = new SecureRandom().nextInt(); - public HX509SS(SecurityInfoC si) throws APIException, CadiException { - this(null,si,false); - } - - public HX509SS(SecurityInfoC si, boolean asDefault) throws APIException, CadiException { - this(null,si,asDefault); - } - - public HX509SS(final String sendAlias, SecurityInfoC si) throws APIException, CadiException { - this(sendAlias, si, false); - } + public HX509SS(SecurityInfoC si) throws APIException, CadiException { + this(null,si,false); + } + + public HX509SS(SecurityInfoC si, boolean asDefault) throws APIException, CadiException { + this(null,si,asDefault); + } + + public HX509SS(final String sendAlias, SecurityInfoC si) throws APIException, CadiException { + this(sendAlias, si, false); + } - public HX509SS(final String sendAlias, SecurityInfoC si, boolean asDefault) throws APIException, CadiException { - securityInfo = si; - if((alias=sendAlias) == null) { - if(si.defaultAlias == null) { - throw new APIException("JKS Alias is required to use X509SS Security. Use " + Config.CADI_ALIAS +" to set default alias"); - } else { - alias = si.defaultAlias; - } - } - - priv=null; - X509KeyManager[] xkms = si.getKeyManagers(); - if(xkms==null || xkms.length==0) { - throw new APIException("There are no valid keys available in given Keystores. Wrong Keypass? Expired?"); - } - for(int i=0;priv==null&&i0) { - algo = chain[0].getSigAlgName(); - pub = chain[0].getEncoded(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(pub.length*2); - ByteArrayInputStream bais = new ByteArrayInputStream(pub); - Symm.base64noSplit.encode(bais,baos,X509); - cert = baos.toString(); - } - } - } catch (CertificateEncodingException | IOException e) { - throw new CadiException(e); - } - if(algo==null) { - throw new APIException("X509 Security Setter not configured"); - } - } + public HX509SS(final String sendAlias, SecurityInfoC si, boolean asDefault) throws APIException, CadiException { + securityInfo = si; + if((alias=sendAlias) == null) { + if(si.defaultAlias == null) { + throw new APIException("JKS Alias is required to use X509SS Security. Use " + Config.CADI_ALIAS +" to set default alias"); + } else { + alias = si.defaultAlias; + } + } + + priv=null; + X509KeyManager[] xkms = si.getKeyManagers(); + if(xkms==null || xkms.length==0) { + throw new APIException("There are no valid keys available in given Keystores. Wrong Keypass? Expired?"); + } + for(int i=0;priv==null&&i0) { + algo = chain[0].getSigAlgName(); + pub = chain[0].getEncoded(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(pub.length*2); + ByteArrayInputStream bais = new ByteArrayInputStream(pub); + Symm.base64noSplit.encode(bais,baos,X509); + cert = baos.toString(); + } + } + } catch (CertificateEncodingException | IOException e) { + throw new CadiException(e); + } + if(algo==null) { + throw new APIException("X509 Security Setter not configured"); + } + } - @Override - public void setSecurity(HttpURLConnection huc) throws CadiException { - if(huc instanceof HttpsURLConnection) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); - } - if(alias==null) { // must be a one-way - huc.setRequestProperty(AbsAuthentication.AUTHORIZATION, cert); - - // Test Signed content - try { - String data = "SignedContent["+ inc() + ']' + Chrono.dateTime(); - huc.setRequestProperty("Data", data); - - Signature sig = Signature.getInstance(algo); - sig.initSign(priv); - sig.update(data.getBytes()); - byte[] signature = sig.sign(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(signature.length*1.3)); - ByteArrayInputStream bais = new ByteArrayInputStream(signature); - Symm.base64noSplit.encode(bais, baos); - huc.setRequestProperty("Signature", new String(baos.toByteArray())); - - } catch (Exception e) { - throw new CadiException(e); - } - } - } - - private synchronized int inc() { - return ++count; - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.SecuritySetter#getID() - */ - @Override - public String getID() { - return alias; - } - - @Override - public int setLastResponse(int respCode) { - return 0; - } + @Override + public void setSecurity(HttpURLConnection huc) throws CadiException { + if(huc instanceof HttpsURLConnection) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); + } + if(alias==null) { // must be a one-way + huc.setRequestProperty(AbsAuthentication.AUTHORIZATION, cert); + + // Test Signed content + try { + String data = "SignedContent["+ inc() + ']' + Chrono.dateTime(); + huc.setRequestProperty("Data", data); + + Signature sig = Signature.getInstance(algo); + sig.initSign(priv); + sig.update(data.getBytes()); + byte[] signature = sig.sign(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(signature.length*1.3)); + ByteArrayInputStream bais = new ByteArrayInputStream(signature); + Symm.base64noSplit.encode(bais, baos); + huc.setRequestProperty("Signature", new String(baos.toByteArray())); + + } catch (Exception e) { + throw new CadiException(e); + } + } + } + + private synchronized int inc() { + return ++count; + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.SecuritySetter#getID() + */ + @Override + public String getID() { + return alias; + } + + @Override + public int setLastResponse(int respCode) { + return 0; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java index ed60b877..1fc4b83e 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java @@ -32,192 +32,192 @@ import org.onap.aaf.cadi.LocatorException; import org.onap.aaf.cadi.Access.Level; public class DNSLocator implements Locator { - private static enum Status {UNTRIED, OK, INVALID, SLOW}; - private static final int CHECK_TIME = 3000; - - private String host, protocol; - private Access access; - private Host[] hosts; - private int startPort, endPort; - private String suffix; - - public DNSLocator(Access access, String protocol, String host, String range) { - this.host = host; - this.protocol = protocol; - this.access = access; - int dash = range.indexOf('-'); - if(dash<0) { - startPort = endPort = Integer.parseInt(range); - } else { - startPort = Integer.parseInt(range.substring(0,dash)); - endPort = Integer.parseInt(range.substring(dash + 1)); - } - refresh(); - } + private static enum Status {UNTRIED, OK, INVALID, SLOW}; + private static final int CHECK_TIME = 3000; + + private String host, protocol; + private Access access; + private Host[] hosts; + private int startPort, endPort; + private String suffix; + + public DNSLocator(Access access, String protocol, String host, String range) { + this.host = host; + this.protocol = protocol; + this.access = access; + int dash = range.indexOf('-'); + if(dash<0) { + startPort = endPort = Integer.parseInt(range); + } else { + startPort = Integer.parseInt(range.substring(0,dash)); + endPort = Integer.parseInt(range.substring(dash + 1)); + } + refresh(); + } - public DNSLocator(Access access, String aaf_locate) throws LocatorException { - this.access = access; - if(aaf_locate==null) { - throw new LocatorException("Null passed into DNSLocator constructor"); - } - int start, port; - if(aaf_locate.startsWith("https:")) { - protocol = "https:"; - start = 9; // https:// - port = 443; - } else if(aaf_locate.startsWith("http:")) { - protocol = "http:"; - start = 8; // http:// - port = 80; - } else { - throw new LocatorException("DNSLocator accepts only https or http protocols. (requested URL " + aaf_locate + ')'); - } - - parsePorts(aaf_locate.substring(start), port); - } + public DNSLocator(Access access, String aaf_locate) throws LocatorException { + this.access = access; + if(aaf_locate==null) { + throw new LocatorException("Null passed into DNSLocator constructor"); + } + int start, port; + if(aaf_locate.startsWith("https:")) { + protocol = "https:"; + start = 9; // https:// + port = 443; + } else if(aaf_locate.startsWith("http:")) { + protocol = "http:"; + start = 8; // http:// + port = 80; + } else { + throw new LocatorException("DNSLocator accepts only https or http protocols. (requested URL " + aaf_locate + ')'); + } + + parsePorts(aaf_locate.substring(start), port); + } - @Override - public URI get(Item item) throws LocatorException { - return hosts[((DLItem)item).cnt].uri; - } + @Override + public URI get(Item item) throws LocatorException { + return hosts[((DLItem)item).cnt].uri; + } - @Override - public boolean hasItems() { - for(Host h : hosts) { - if(h.status==Status.OK) { - return true; - } - } - return false; - } + @Override + public boolean hasItems() { + for(Host h : hosts) { + if(h.status==Status.OK) { + return true; + } + } + return false; + } - @Override - public void invalidate(Item item) { - DLItem di = (DLItem)item; - hosts[di.cnt].status = Status.INVALID; - } + @Override + public void invalidate(Item item) { + DLItem di = (DLItem)item; + hosts[di.cnt].status = Status.INVALID; + } - @Override - public Item best() throws LocatorException { - // not a good "best" - for(int i=0;i 0) { - start = colon + 1; - int left = aaf_locate.indexOf('[', start); - if(left > 0) { - int right = aaf_locate.indexOf(']', left + 1); - if (right < 0) { - throw new LocatorException("Missing closing bracket in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } else if (right == (left + 1)) { - throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } - int dash = aaf_locate.indexOf('-', left + 1); - if (dash == (right - 1) || dash == (left + 1)) { - throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } - if(dash < 0) { - startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right)); - } else { - startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash)); - endPort = Integer.parseInt(aaf_locate.substring(dash + 1, right)); - } - - } else { - slash = aaf_locate.indexOf('/', start); - if (slash == start) { - throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } - if(slash < 0) { - startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); - } else { - startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash)); - } - } - } else { - startPort = endPort = defaultPort; - } - } + @Override + public boolean refresh() { + try { + InetAddress[] ias = InetAddress.getAllByName(host); + Host[] temp = new Host[ias.length * (1 + endPort - startPort)]; + int cnt = -1; + for(int j=startPort; j<=endPort; ++j) { + for(int i=0;i 0) { + start = colon + 1; + int left = aaf_locate.indexOf('[', start); + if(left > 0) { + int right = aaf_locate.indexOf(']', left + 1); + if (right < 0) { + throw new LocatorException("Missing closing bracket in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } else if (right == (left + 1)) { + throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + int dash = aaf_locate.indexOf('-', left + 1); + if (dash == (right - 1) || dash == (left + 1)) { + throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + if(dash < 0) { + startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right)); + } else { + startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash)); + endPort = Integer.parseInt(aaf_locate.substring(dash + 1, right)); + } + + } else { + slash = aaf_locate.indexOf('/', start); + if (slash == start) { + throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + if(slash < 0) { + startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); + } else { + startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash)); + } + } + } else { + startPort = endPort = defaultPort; + } + } - private class Host { - private URI uri; - private InetAddress ia; - private Status status; - - public Host(InetAddress inetAddress, int port, String suffix) throws URISyntaxException { - ia = inetAddress; - uri = new URI(protocol,null,inetAddress.getHostAddress(),port,suffix,null,null); - status = Status.UNTRIED; - } - } - - private class DLItem implements Item { - public DLItem(int i) { - cnt = i; - } + private class Host { + private URI uri; + private InetAddress ia; + private Status status; + + public Host(InetAddress inetAddress, int port, String suffix) throws URISyntaxException { + ia = inetAddress; + uri = new URI(protocol,null,inetAddress.getHostAddress(),port,suffix,null,null); + status = Status.UNTRIED; + } + } + + private class DLItem implements Item { + public DLItem(int i) { + cnt = i; + } - private int cnt; - } - - public void destroy() {} + private int cnt; + } + + public void destroy() {} } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java index b97768a6..488d35d5 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java @@ -30,31 +30,31 @@ import org.onap.aaf.cadi.http.HClient; import org.onap.aaf.cadi.http.HX509SS; public class HClientHotPeerLocator extends HotPeerLocator { - private final HX509SS ss; - - public HClientHotPeerLocator(Access access, String urlstr, long invalidateTime, String localLatitude, - String localLongitude, HX509SS ss) throws LocatorException { - super(access, urlstr, invalidateTime, localLatitude, localLongitude); - - this.ss = ss; - } - - @Override - protected HClient _newClient(String clientInfo) throws LocatorException { - try { - int idx = clientInfo.indexOf('/'); - return new HClient(ss,new URI("https://"+(idx<0?clientInfo:clientInfo.substring(0, idx))),3000); - } catch (URISyntaxException e) { - throw new LocatorException(e); - } - } - - @Override - protected HClient _invalidate(HClient client) { - return null; - } - - @Override - protected void _destroy(HClient client) { - } + private final HX509SS ss; + + public HClientHotPeerLocator(Access access, String urlstr, long invalidateTime, String localLatitude, + String localLongitude, HX509SS ss) throws LocatorException { + super(access, urlstr, invalidateTime, localLatitude, localLongitude); + + this.ss = ss; + } + + @Override + protected HClient _newClient(String clientInfo) throws LocatorException { + try { + int idx = clientInfo.indexOf('/'); + return new HClient(ss,new URI("https://"+(idx<0?clientInfo:clientInfo.substring(0, idx))),3000); + } catch (URISyntaxException e) { + throw new LocatorException(e); + } + } + + @Override + protected HClient _invalidate(HClient client) { + return null; + } + + @Override + protected void _destroy(HClient client) { + } } \ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java index fd8e99dc..26b8817b 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java @@ -30,8 +30,8 @@ import org.onap.aaf.misc.env.util.Split; /** * This Locator is to handle Hot Peer load protection, when the Servers are - * 1) Static - * 2) Well known client URL + * 1) Static + * 2) Well known client URL * * The intention is to change traffic over to the Hot Peer, if a server goes down, and reinstate * when it is back up. @@ -43,259 +43,259 @@ import org.onap.aaf.misc.env.util.Split; * @param */ public abstract class HotPeerLocator implements Locator { - private final String[] urlstrs; - private final CLIENT[] clients; - private final long[] failures; - private final double[] distances; - private int preferred; - private long invalidateTime; - private Thread refreshThread; - protected Access access; + private final String[] urlstrs; + private final CLIENT[] clients; + private final long[] failures; + private final double[] distances; + private int preferred; + private long invalidateTime; + private Thread refreshThread; + protected Access access; - /** - * Construct: Expect one or more Strings in the form: - * 192.555.112.223:39/38.88087/-77.30122 - * separated by commas - * - * @param trans - * @param urlstr - * @param invalidateTime - * @param localLatitude - * @param localLongitude - * @throws LocatorException - */ - @SuppressWarnings("unchecked") - protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException { - this.access = access; - urlstrs = Split.split(',', urlstr); - clients = (CLIENT[])new Object[urlstrs.length]; - failures = new long[urlstrs.length]; - distances= new double[urlstrs.length]; - this.invalidateTime = invalidateTime; + /** + * Construct: Expect one or more Strings in the form: + * 192.555.112.223:39/38.88087/-77.30122 + * separated by commas + * + * @param trans + * @param urlstr + * @param invalidateTime + * @param localLatitude + * @param localLongitude + * @throws LocatorException + */ + @SuppressWarnings("unchecked") + protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException { + this.access = access; + urlstrs = Split.split(',', urlstr); + clients = (CLIENT[])new Object[urlstrs.length]; + failures = new long[urlstrs.length]; + distances= new double[urlstrs.length]; + this.invalidateTime = invalidateTime; - double distance = Double.MAX_VALUE; - for(int i=0;iSystem.currentTimeMillis()) { - throw new LocatorException("Client requested is invalid"); - } else { - synchronized(clients) { - c = _newClient(urlstrs[hpi.idx]); - failures[hpi.idx]=0L; - } - } - } else if(failures[hpi.idx]>0){ - throw new LocatorException("Client requested is invalid"); - } - return c; - } + @Override + public CLIENT get(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + CLIENT c = clients[hpi.idx]; + if(c==null) { + if(failures[hpi.idx]>System.currentTimeMillis()) { + throw new LocatorException("Client requested is invalid"); + } else { + synchronized(clients) { + c = _newClient(urlstrs[hpi.idx]); + failures[hpi.idx]=0L; + } + } + } else if(failures[hpi.idx]>0){ + throw new LocatorException("Client requested is invalid"); + } + return c; + } - public String info(Item item) { - HPItem hpi = (HPItem)item; - if(hpi!=null && hpi.idx=clients.length) { - return null; - } - return hpi; - } + @Override + public Item next(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + if(++hpi.idx>=clients.length) { + return null; + } + return hpi; + } - @Override - public boolean refresh() { - boolean force = !hasItems(); // If no Items at all, reset - boolean rv = true; - long now = System.currentTimeMillis(); - for(int i=0;i0L && (failures[i]0L && (failures[i] { - private final URI [] orig; - private PLItem[] current; - private int end; - private final SecureRandom random; - private URI[] resolved; - private long lastRefreshed; - private long minRefresh; - private long backgroundRefresh; + private final URI [] orig; + private PLItem[] current; + private int end; + private final SecureRandom random; + private URI[] resolved; + private long lastRefreshed; + private long minRefresh; + private long backgroundRefresh; - public PropertyLocator(String locList) throws LocatorException { - this(locList,10000L, 1000*60*20L); // defaults, do not refresh more than once in 10 seconds, Refresh Locator every 20 mins. - } - /** - * comma delimited root url list - * - * @param locList - * @throws LocatorException - */ - public PropertyLocator(String locList, long minRefreshMillis, long backgroundRefreshMillis) throws LocatorException { - minRefresh = minRefreshMillis; - backgroundRefresh = backgroundRefreshMillis; - lastRefreshed=0L; - if(locList==null) { - throw new LocatorException("No Location List given for PropertyLocator"); - } - String[] locarray = Split.split(',',locList); - List uriList = new ArrayList<>(); - - random = new SecureRandom(); - - for(int i=0;i=0?locarray[i].substring(slash):""))); - } - } - } catch (NumberFormatException nf) { - throw new LocatorException("Invalid URI format: " + locarray[i]); - } catch (URISyntaxException e) { - throw new LocatorException(e); - } - } - orig = new URI[uriList.size()]; - uriList.toArray(orig); + public PropertyLocator(String locList) throws LocatorException { + this(locList,10000L, 1000*60*20L); // defaults, do not refresh more than once in 10 seconds, Refresh Locator every 20 mins. + } + /** + * comma delimited root url list + * + * @param locList + * @throws LocatorException + */ + public PropertyLocator(String locList, long minRefreshMillis, long backgroundRefreshMillis) throws LocatorException { + minRefresh = minRefreshMillis; + backgroundRefresh = backgroundRefreshMillis; + lastRefreshed=0L; + if(locList==null) { + throw new LocatorException("No Location List given for PropertyLocator"); + } + String[] locarray = Split.split(',',locList); + List uriList = new ArrayList<>(); + + random = new SecureRandom(); + + for(int i=0;i=0?locarray[i].substring(slash):""))); + } + } + } catch (NumberFormatException nf) { + throw new LocatorException("Invalid URI format: " + locarray[i]); + } catch (URISyntaxException e) { + throw new LocatorException(e); + } + } + orig = new URI[uriList.size()]; + uriList.toArray(orig); - refresh(); - new Timer("PropertyLocator Refresh Timer",true).scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - refresh(); - } - }, backgroundRefresh,backgroundRefresh); - } + refresh(); + new Timer("PropertyLocator Refresh Timer",true).scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + refresh(); + } + }, backgroundRefresh,backgroundRefresh); + } - @Override - public URI get(Item item) throws LocatorException { - synchronized(orig) { - if(item==null) { - return null; - } else { - return resolved[((PLItem)item).idx]; - } - } - } + @Override + public URI get(Item item) throws LocatorException { + synchronized(orig) { + if(item==null) { + return null; + } else { + return resolved[((PLItem)item).idx]; + } + } + } - @Override - public Item first() throws LocatorException { - return end>0?current[0]:null; - } + @Override + public Item first() throws LocatorException { + return end>0?current[0]:null; + } - @Override - public boolean hasItems() { - return end>0; - } + @Override + public boolean hasItems() { + return end>0; + } - @Override - public Item next(Item item) throws LocatorException { - if(item==null) { - return null; - } else { - int spot; - if((spot=(((PLItem)item).order+1))>=end)return null; - return current[spot]; - } - } + @Override + public Item next(Item item) throws LocatorException { + if(item==null) { + return null; + } else { + int spot; + if((spot=(((PLItem)item).order+1))>=end)return null; + return current[spot]; + } + } - @Override - public synchronized void invalidate(Item item) throws LocatorException { - if(--end<0) { - refresh(); - return; - } - if(item==null) { - return; - } - PLItem pli = (PLItem)item; - int i,order; - for(i=0;ilastRefreshed) { - // Build up list - List resolve = new ArrayList<>(); - String realname; - for(int i = 0; i < orig.length ; ++i) { - try { - InetAddress ia[] = InetAddress.getAllByName(orig[i].getHost()); + @Override + public synchronized boolean refresh() { + if(System.currentTimeMillis()>lastRefreshed) { + // Build up list + List resolve = new ArrayList<>(); + String realname; + for(int i = 0; i < orig.length ; ++i) { + try { + InetAddress ia[] = InetAddress.getAllByName(orig[i].getHost()); - URI o,n; - for(int j=0;j { - private final URI uri; - private final static Item item = new Item() {}; - private Date noRetryUntil; - - public SingleEndpointLocator(final URI uri) { - this.uri = uri; - } - - public SingleEndpointLocator(final String endpoint) throws URISyntaxException { - this.uri = new URI(endpoint); - } + private final URI uri; + private final static Item item = new Item() {}; + private Date noRetryUntil; + + public SingleEndpointLocator(final URI uri) { + this.uri = uri; + } + + public SingleEndpointLocator(final String endpoint) throws URISyntaxException { + this.uri = new URI(endpoint); + } - @Override - public URI get(Item item) throws LocatorException { - return uri; - } + @Override + public URI get(Item item) throws LocatorException { + return uri; + } - @Override - public boolean hasItems() { - if(noRetryUntil!=null) { - if(new Date().after(noRetryUntil)) { - noRetryUntil = null; - } else { - return false; - } - } - return true; - } + @Override + public boolean hasItems() { + if(noRetryUntil!=null) { + if(new Date().after(noRetryUntil)) { + noRetryUntil = null; + } else { + return false; + } + } + return true; + } - @Override - public void invalidate(Item item) throws LocatorException { - // one minute timeout, because there is no other item - noRetryUntil = new Date(System.currentTimeMillis()+60000); - } + @Override + public void invalidate(Item item) throws LocatorException { + // one minute timeout, because there is no other item + noRetryUntil = new Date(System.currentTimeMillis()+60000); + } - @Override - public Item best() throws LocatorException { - return item; - } + @Override + public Item best() throws LocatorException { + return item; + } - @Override - public Item first() throws LocatorException { - return item; - } + @Override + public Item first() throws LocatorException { + return item; + } - @Override - public Item next(Item inItem) throws LocatorException { - // only one item - return null; - } + @Override + public Item next(Item inItem) throws LocatorException { + // only one item + return null; + } - @Override - public boolean refresh() { - // Never refreshed - return true; - } + @Override + public boolean refresh() { + // Never refreshed + return true; + } - @Override - public void destroy() { - // Nothing to do here - } + @Override + public void destroy() { + // Nothing to do here + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java b/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java index 36906188..3bce5245 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java @@ -24,101 +24,101 @@ package org.onap.aaf.cadi.routing; import org.onap.aaf.misc.env.util.Split; public class GreatCircle { - // Note: multiplying by this constant is faster than calling Math equivalent function - private static final double DEGREES_2_RADIANS = Math.PI/180.0; - - public static final double DEGREES_2_NM = 60; - public static final double DEGREES_2_KM = DEGREES_2_NM * 1.852; // 1.852 is exact ratio per 1929 Standard Treaty, adopted US 1954 - public static final double DEGREES_2_MI = DEGREES_2_NM * 1.1507795; - - /** - * - * Calculate the length of an arc on a perfect sphere based on Latitude and Longitudes of two points - * Parameters are in Degrees (i.e. the coordinate system you get from GPS, Mapping WebSites, Phones, etc) - * - * L1 = Latitude of point A - * G1 = Longitude of point A - * L2 = Latitude of point B - * G2 = Longitude of point B - * - * d = acos (sin(L1)*sin(L2) + cos(L1)*cos(L2)*cos(G1 - G2)) - * - * Returns answer in Degrees - * - * Since there are 60 degrees per nautical miles, you can convert to NM by multiplying by 60 - * - * Essential formula from a Princeton website, the "Law of Cosines" method. - * - * Refactored cleaned up for speed Jonathan 3/8/2013 - * - * @param latA - * @param lonA - * @param latB - * @param lonB - * @return - */ - public static double calc(double latA, double lonA, double latB, double lonB) { - // Formula requires Radians. Expect Params to be Coordinates (Degrees) - // Simple ratio, quicker than calling Math.toRadians() - latA *= DEGREES_2_RADIANS; - lonA *= DEGREES_2_RADIANS; - latB *= DEGREES_2_RADIANS; - lonB *= DEGREES_2_RADIANS; + // Note: multiplying by this constant is faster than calling Math equivalent function + private static final double DEGREES_2_RADIANS = Math.PI/180.0; + + public static final double DEGREES_2_NM = 60; + public static final double DEGREES_2_KM = DEGREES_2_NM * 1.852; // 1.852 is exact ratio per 1929 Standard Treaty, adopted US 1954 + public static final double DEGREES_2_MI = DEGREES_2_NM * 1.1507795; + + /** + * + * Calculate the length of an arc on a perfect sphere based on Latitude and Longitudes of two points + * Parameters are in Degrees (i.e. the coordinate system you get from GPS, Mapping WebSites, Phones, etc) + * + * L1 = Latitude of point A + * G1 = Longitude of point A + * L2 = Latitude of point B + * G2 = Longitude of point B + * + * d = acos (sin(L1)*sin(L2) + cos(L1)*cos(L2)*cos(G1 - G2)) + * + * Returns answer in Degrees + * + * Since there are 60 degrees per nautical miles, you can convert to NM by multiplying by 60 + * + * Essential formula from a Princeton website, the "Law of Cosines" method. + * + * Refactored cleaned up for speed Jonathan 3/8/2013 + * + * @param latA + * @param lonA + * @param latB + * @param lonB + * @return + */ + public static double calc(double latA, double lonA, double latB, double lonB) { + // Formula requires Radians. Expect Params to be Coordinates (Degrees) + // Simple ratio, quicker than calling Math.toRadians() + latA *= DEGREES_2_RADIANS; + lonA *= DEGREES_2_RADIANS; + latB *= DEGREES_2_RADIANS; + lonB *= DEGREES_2_RADIANS; - return Math.acos( - Math.sin(latA) * Math.sin(latB) + - Math.cos(latA) * Math.cos(latB) * Math.cos(lonA-lonB) - ) - / DEGREES_2_RADIANS; - } - - /** - * Convert from "Lat,Long Lat,Long" String format - * "Lat,Long,Lat,Long" Format - * or all four entries "Lat Long Lat Long" - * - * (Convenience function) - * - * Since Distance is positive, a "-1" indicates an error in String formatting - */ - public static double calc(String ... coords) { - try { - String [] array; - switch(coords.length) { - case 1: - array = Split.split(',',coords[0]); - if(array.length!=4)return -1; - return calc( - Double.parseDouble(array[0]), - Double.parseDouble(array[1]), - Double.parseDouble(array[2]), - Double.parseDouble(array[3]) - ); - case 2: - array = Split.split(',',coords[0]); - String [] array2 = Split.split(',',coords[1]); - if(array.length!=2 || array2.length!=2)return -1; - return calc( - Double.parseDouble(array[0]), - Double.parseDouble(array[1]), - Double.parseDouble(array2[0]), - Double.parseDouble(array2[1]) - ); - case 4: - return calc( - Double.parseDouble(coords[0]), - Double.parseDouble(coords[1]), - Double.parseDouble(coords[2]), - Double.parseDouble(coords[3]) - ); - - default: - return -1; - } - } catch (NumberFormatException e) { - return -1; - } - } + return Math.acos( + Math.sin(latA) * Math.sin(latB) + + Math.cos(latA) * Math.cos(latB) * Math.cos(lonA-lonB) + ) + / DEGREES_2_RADIANS; + } + + /** + * Convert from "Lat,Long Lat,Long" String format + * "Lat,Long,Lat,Long" Format + * or all four entries "Lat Long Lat Long" + * + * (Convenience function) + * + * Since Distance is positive, a "-1" indicates an error in String formatting + */ + public static double calc(String ... coords) { + try { + String [] array; + switch(coords.length) { + case 1: + array = Split.split(',',coords[0]); + if(array.length!=4)return -1; + return calc( + Double.parseDouble(array[0]), + Double.parseDouble(array[1]), + Double.parseDouble(array[2]), + Double.parseDouble(array[3]) + ); + case 2: + array = Split.split(',',coords[0]); + String [] array2 = Split.split(',',coords[1]); + if(array.length!=2 || array2.length!=2)return -1; + return calc( + Double.parseDouble(array[0]), + Double.parseDouble(array[1]), + Double.parseDouble(array2[0]), + Double.parseDouble(array2[1]) + ); + case 4: + return calc( + Double.parseDouble(coords[0]), + Double.parseDouble(coords[1]), + Double.parseDouble(coords[2]), + Double.parseDouble(coords[3]) + ); + + default: + return -1; + } + } catch (NumberFormatException e) { + return -1; + } + } } @@ -132,30 +132,30 @@ public class GreatCircle { //* @return //*/ //public static double calc3(double alat, double alon, double blat, double blon) { -// alat *= DEGREES_2_RADIANS; -// alon *= DEGREES_2_RADIANS; -// blat *= DEGREES_2_RADIANS; -// blon *= DEGREES_2_RADIANS; -// return 2 * Math.asin( -// Math.min(1, Math.sqrt( -// Math.pow(Math.sin((blat-alat)/2), 2) + -// (Math.cos(alat)*Math.cos(blat)* -// Math.pow( -// Math.sin((blon-alon)/2),2) -// ) -// ) -// ) -// ) -// / DEGREES_2_RADIANS; +// alat *= DEGREES_2_RADIANS; +// alon *= DEGREES_2_RADIANS; +// blat *= DEGREES_2_RADIANS; +// blon *= DEGREES_2_RADIANS; +// return 2 * Math.asin( +// Math.min(1, Math.sqrt( +// Math.pow(Math.sin((blat-alat)/2), 2) + +// (Math.cos(alat)*Math.cos(blat)* +// Math.pow( +// Math.sin((blon-alon)/2),2) +// ) +// ) +// ) +// ) +// / DEGREES_2_RADIANS; //} // //This is a MEAN radius. The Earth is not perfectly spherical -// public static final double EARTH_RADIUS_KM = 6371.0; -// public static final double EARTH_RADIUS_NM = 3440.07; -// public static final double KM_2_MILES_RATIO = 0.621371192; +// public static final double EARTH_RADIUS_KM = 6371.0; +// public static final double EARTH_RADIUS_NM = 3440.07; +// public static final double KM_2_MILES_RATIO = 0.621371192; ///** //* Code on Internet based on Unknown book. Lat/Long is in Degrees //* @param alat @@ -165,20 +165,20 @@ public class GreatCircle { //* @return //*/ //public static double calc1(double alat, double alon, double blat, double blon) { -// alat *= DEGREES_2_RADIANS; -// alon *= DEGREES_2_RADIANS; -// blat *= DEGREES_2_RADIANS; -// blon *= DEGREES_2_RADIANS; -// -// // Reused values -// double cosAlat,cosBlat; -// -// return Math.acos( -// ((cosAlat=Math.cos(alat))*Math.cos(alon)*(cosBlat=Math.cos(blat))*Math.cos(blon)) + -// (cosAlat*Math.sin(alon)*cosBlat*Math.sin(blon)) + -// (Math.sin(alat)*Math.sin(blat)) -// )/DEGREES_2_RADIANS; -// +// alat *= DEGREES_2_RADIANS; +// alon *= DEGREES_2_RADIANS; +// blat *= DEGREES_2_RADIANS; +// blon *= DEGREES_2_RADIANS; +// +// // Reused values +// double cosAlat,cosBlat; +// +// return Math.acos( +// ((cosAlat=Math.cos(alat))*Math.cos(alon)*(cosBlat=Math.cos(blat))*Math.cos(blon)) + +// (cosAlat*Math.sin(alon)*cosBlat*Math.sin(blon)) + +// (Math.sin(alat)*Math.sin(blat)) +// )/DEGREES_2_RADIANS; +// //} /* diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java index cc67946e..65daa7b6 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java @@ -34,70 +34,70 @@ import java.io.PrintStream; import java.net.HttpURLConnection; public class JU_AbsAuthentication { - - private final static String ID = "id"; - private final static String PASSWORD = "password"; - private final static String WARNING = "Your service has 1000 consecutive bad service " + - "logins to AAF. AAF Access will be disabled after 10000\n"; - - private static ByteArrayOutputStream errStream; - - @Before - public void setup() { - errStream = new ByteArrayOutputStream(); - System.setErr(new PrintStream(errStream)); - } - - @After - public void tearDown() { - System.setErr(System.err); - } + + private final static String ID = "id"; + private final static String PASSWORD = "password"; + private final static String WARNING = "Your service has 1000 consecutive bad service " + + "logins to AAF. AAF Access will be disabled after 10000\n"; + + private static ByteArrayOutputStream errStream; + + @Before + public void setup() { + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } - @Test - public void test() throws IOException, InterruptedException { - AuthStub stub = new AuthStub(null, null, null); - assertThat(stub.getID(), is(nullValue())); - assertThat(stub.headValue(), is("")); - assertThat(stub.count(), is(0)); - - stub.setUser(ID); - assertThat(stub.getID(), is(ID)); + @Test + public void test() throws IOException, InterruptedException { + AuthStub stub = new AuthStub(null, null, null); + assertThat(stub.getID(), is(nullValue())); + assertThat(stub.headValue(), is("")); + assertThat(stub.count(), is(0)); + + stub.setUser(ID); + assertThat(stub.getID(), is(ID)); - stub = new AuthStub(null, ID, PASSWORD.getBytes()); - assertThat(stub.getID(), is(ID)); - assertThat(stub.headValue(), is(PASSWORD)); - assertThat(stub.count(), is(0)); - - assertThat(stub.setLastResponse(200), is(0)); - assertThat(stub.isDenied(), is(false)); + stub = new AuthStub(null, ID, PASSWORD.getBytes()); + assertThat(stub.getID(), is(ID)); + assertThat(stub.headValue(), is(PASSWORD)); + assertThat(stub.count(), is(0)); + + assertThat(stub.setLastResponse(200), is(0)); + assertThat(stub.isDenied(), is(false)); - for (int i = 1; i <= 10; i++) { - assertThat(stub.setLastResponse(401), is(i)); - assertThat(stub.isDenied(), is(false)); - } - assertThat(stub.setLastResponse(401), is(11)); - assertThat(stub.isDenied(), is(true)); + for (int i = 1; i <= 10; i++) { + assertThat(stub.setLastResponse(401), is(i)); + assertThat(stub.isDenied(), is(false)); + } + assertThat(stub.setLastResponse(401), is(11)); + assertThat(stub.isDenied(), is(true)); - stub.setCount(999); - assertThat(stub.setLastResponse(401), is(1000)); - assertThat(errStream.toString(), is(WARNING)); - - // coverage... - stub.setLastMiss(1); - assertThat(stub.isDenied(), is(false)); - } - - private class AuthStub extends AbsAuthentication { + stub.setCount(999); + assertThat(stub.setLastResponse(401), is(1000)); + assertThat(errStream.toString(), is(WARNING)); + + // coverage... + stub.setLastMiss(1); + assertThat(stub.isDenied(), is(false)); + } + + private class AuthStub extends AbsAuthentication { - public AuthStub(SecurityInfoC securityInfo, String user, byte[] headValue) - throws IOException { super(securityInfo, user, headValue); } + public AuthStub(SecurityInfoC securityInfo, String user, byte[] headValue) + throws IOException { super(securityInfo, user, headValue); } - @Override public void setSecurity(HttpURLConnection client) throws CadiException { } - @Override public void setUser(String id) { super.setUser(id); } - @Override public String headValue() throws IOException { return super.headValue(); } - - public void setLastMiss(long lastMiss) { this.lastMiss = lastMiss; } - public void setCount(int count) { this.count = count; } - } + @Override public void setSecurity(HttpURLConnection client) throws CadiException { } + @Override public void setUser(String id) { super.setUser(id); } + @Override public String headValue() throws IOException { return super.headValue(); } + + public void setLastMiss(long lastMiss) { this.lastMiss = lastMiss; } + public void setCount(int count) { this.count = count; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java index 507f90f4..c7720775 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java @@ -34,39 +34,39 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; import java.net.HttpURLConnection; public class JU_AbsTransferSS { - - @Mock TaggedPrincipal princMock; - @Mock SecurityInfoC siMock; - - private static final String princName = "name"; - private static final String princTag = "tag"; - private static final String app = "app"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - when(princMock.getName()).thenReturn(princName); - when(princMock.tag()).thenReturn(princTag); - } + + @Mock TaggedPrincipal princMock; + @Mock SecurityInfoC siMock; + + private static final String princName = "name"; + private static final String princTag = "tag"; + private static final String app = "app"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + when(princMock.getName()).thenReturn(princName); + when(princMock.tag()).thenReturn(princTag); + } - @Test - public void test() { - TransferSSStub stub = new TransferSSStub(princMock, app); - assertThat(stub.getID(), is(princName)); - assertThat(stub.getValue(), is(princName + ':' + app + ':' + princTag + ':' + "AS")); - - stub = new TransferSSStub(null, app, siMock); - assertThat(stub.getID(), is("")); - assertThat(stub.getValue(), is(nullValue())); - } - - private class TransferSSStub extends AbsTransferSS { - public TransferSSStub(TaggedPrincipal principal, String app) { super(principal, app); } - public TransferSSStub(TaggedPrincipal principal, String app, SecurityInfoC si) { super(principal, app, si); } - @Override public void setSecurity(HttpURLConnection client) throws CadiException { } - @Override public int setLastResponse(int respCode) { return 0; } - public String getValue() { return value; } - } + @Test + public void test() { + TransferSSStub stub = new TransferSSStub(princMock, app); + assertThat(stub.getID(), is(princName)); + assertThat(stub.getValue(), is(princName + ':' + app + ':' + princTag + ':' + "AS")); + + stub = new TransferSSStub(null, app, siMock); + assertThat(stub.getID(), is("")); + assertThat(stub.getValue(), is(nullValue())); + } + + private class TransferSSStub extends AbsTransferSS { + public TransferSSStub(TaggedPrincipal principal, String app) { super(principal, app); } + public TransferSSStub(TaggedPrincipal principal, String app, SecurityInfoC si) { super(principal, app, si); } + @Override public void setSecurity(HttpURLConnection client) throws CadiException { } + @Override public int setLastResponse(int respCode) { return 0; } + public String getValue() { return value; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java index ad0bd535..97fa9d21 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java @@ -29,17 +29,17 @@ import org.onap.aaf.cadi.client.Future; public class JU_Future { - @Test - public void test() { - @SuppressWarnings("unused") - Future f = new FutureStub(); - } - - private class FutureStub extends Future { - @Override public boolean get(int timeout) throws CadiException { return false; } - @Override public int code() { return 0; } - @Override public String body() { return null; } - @Override public String header(String tag) { return null; } - } + @Test + public void test() { + @SuppressWarnings("unused") + Future f = new FutureStub(); + } + + private class FutureStub extends Future { + @Override public boolean get(int timeout) throws CadiException { return false; } + @Override public int code() { return 0; } + @Override public String body() { return null; } + @Override public String header(String tag) { return null; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java index 079951f5..dd9b0539 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java @@ -29,17 +29,17 @@ import org.onap.aaf.cadi.client.Holder; public class JU_Holder { - @Test - public void test() { - String str1 = "a string"; - String str2 = "another string"; - Holder holder = new Holder(str1); - assertThat(holder.get(), is(str1)); - assertThat(holder.toString(), is(str1)); - - holder.set(str2); - assertThat(holder.get(), is(str2)); - assertThat(holder.toString(), is(str2)); - } + @Test + public void test() { + String str1 = "a string"; + String str2 = "another string"; + Holder holder = new Holder(str1); + assertThat(holder.get(), is(str1)); + assertThat(holder.toString(), is(str1)); + + holder.set(str2); + assertThat(holder.get(), is(str2)); + assertThat(holder.toString(), is(str2)); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java index 886c5d84..d33811e3 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java @@ -55,228 +55,228 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; public class JU_Rcli { - @Mock RosettaDF dfMock; - @Mock RosettaData dataMock; - @Mock HttpURLConnection conMock; - @Mock HttpServletRequest reqMock; - @Mock HttpServletResponse respMock; - @Mock ServletInputStream isMock; - - private final static String uriString = "example.com"; - private final static String apiVersion = "v1.0"; - private final static String contentType = "contentType"; - - private static URI uri; - private static Enumeration enumeration; - - private Client client; - - @Before - public void setup() throws URISyntaxException, IOException { - MockitoAnnotations.initMocks(this); - - when(dfMock.getTypeClass()).thenReturn(HttpURLConnection.class); - when(dfMock.newData()).thenReturn(dataMock); - when(dataMock.out((TYPE) any())).thenReturn(dataMock); - - when(reqMock.getInputStream()).thenReturn(isMock); - when(isMock.read((byte[]) any())).thenReturn(-1); - - uri = new URI(uriString); - enumeration = new CustomEnumeration(); - client = new Client(); - } - - @Test - public void createTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.XML); - - rcli.create(null, contentType, dfMock, conMock); - rcli.create("No question mark", contentType, dfMock, conMock); - rcli.create("question?mark", contentType, dfMock, conMock); - - rcli.create(null, dfMock, conMock); - rcli.create("No question mark", dfMock, conMock); - rcli.create("question?mark", dfMock, conMock); - - rcli.create(null, HttpURLConnection.class, dfMock, conMock); - rcli.create("No question mark", HttpURLConnection.class, dfMock, conMock); - rcli.create("question?mark", HttpURLConnection.class, dfMock, conMock); - - rcli.create(null, HttpURLConnection.class); - rcli.create("No question mark", HttpURLConnection.class); - rcli.create("question?mark", HttpURLConnection.class); - - rcli.create(null, contentType); - rcli.create("No question mark", contentType); - rcli.create("question?mark", contentType); - } - - @Test - public void postFormTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - - rcli.type(Data.TYPE.DEFAULT); - rcli.postForm(null, dfMock); - rcli.postForm("No question mark", dfMock); - rcli.postForm("question?mark", dfMock); - - rcli.type(Data.TYPE.JSON); - rcli.postForm("question?mark", dfMock); - - rcli.type(Data.TYPE.XML); - rcli.postForm("question?mark", dfMock); - - } - - @Test - public void readPostTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.readPost(null, dfMock, conMock); - rcli.readPost("No question mark", dfMock, conMock); - rcli.readPost("question?mark", dfMock, conMock); - - rcli.readPost(null, dfMock, conMock, dfMock); - rcli.readPost("No question mark", dfMock, conMock, dfMock); - rcli.readPost("question?mark", dfMock, conMock, dfMock); - - rcli.readPost("First string", "Second string"); - } - - @Test - public void readTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.read("First string", "Second string", "Third string", "Fourth string"); - rcli.read("First string", "Second string", dfMock, "Third string", "Fourth string"); - rcli.read("First string", dfMock, "Third string", "Fourth string"); - rcli.read("First string", HttpURLConnection.class ,dfMock); - } - - @Test - public void updateTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.update("First string", "Second string", dfMock, conMock); - rcli.update("First string", dfMock, conMock); - rcli.update("First string", HttpURLConnection.class, dfMock, conMock); - rcli.update("First string"); - rcli.updateRespondString("First string", dfMock, conMock); - } - - @Test - public void deleteTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.delete("First string", "Second string", dfMock, conMock); - rcli.delete("First string", dfMock, conMock); - rcli.delete("First string", HttpURLConnection.class, dfMock, conMock); - rcli.delete("First string", HttpURLConnection.class); - rcli.delete("First string", "Second string"); - } - - @Test - public void transferTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - when(reqMock.getRequestURI()).thenReturn(uriString); - when(reqMock.getHeaderNames()).thenReturn(enumeration); - rcli.transfer(reqMock, respMock, "string", 200); - - // coverage... - when(reqMock.getMethod()).thenReturn("GET"); - rcli.transfer(reqMock, respMock, "string", 200); - } - - @Test(expected = CadiException.class) - public void transferThrowsTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.transfer(reqMock, respMock, "string", 200); - } - - @Test - public void accessorMutatorTest() throws URISyntaxException { - RcliStub rcli = new RcliStub(); - Rcli rcliClone = rcli.forUser(null); - - rcli = new RcliStub(uri); - assertThat(rcli.toString(), is(uriString)); - assertThat(rcli.getURI(), is(uri)); - assertThat(rcli.getReadTimeout(), is(5000)); - assertThat(rcli.getConnectionTimeout(), is(3000)); - - rcli.connectionTimeout(3001); - assertThat(rcli.getConnectionTimeout(), is(3001)); - rcli.readTimeout(5001); - assertThat(rcli.getReadTimeout(), is(5001)); - rcli.apiVersion(apiVersion); - assertThat(rcli.isApiVersion(apiVersion), is(true)); - rcli.type(Data.TYPE.XML); - assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml;version=" + apiVersion)); - rcli.apiVersion(null); - assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml")); - - rcliClone = rcli.forUser(null); - assertThat(rcliClone.toString(), is(uriString)); - } - - private class RcliStub extends Rcli { - public RcliStub() { super(); } - public RcliStub(URI uri) { this.uri = uri; } - @Override public void setSecuritySetter(SecuritySetter ss) { } - @Override public SecuritySetter getSecuritySetter() { return null; } - @Override protected Rcli clone(URI uri, SecuritySetter ss) { return this; } - @Override public void invalidate() throws CadiException { } - @Override protected EClient client() throws CadiException { return client; } - public int getReadTimeout() { return readTimeout; } - public int getConnectionTimeout() { return connectionTimeout; } - } - - private class CustomEnumeration implements Enumeration { - private int idx = 0; - private final String[] elements = {"This", "is", "a", "test"}; - @Override - public String nextElement() { - return idx >= elements.length ? null : elements[idx++]; - } - @Override - public boolean hasMoreElements() { - return idx < elements.length; - } - } - - private class Client implements EClient { - private Transfer transfer; - @Override public void setPayload(Transfer transfer) { this.transfer = transfer; } - @Override public void setMethod(String meth) { } - @Override public void setPathInfo(String pathinfo) { } - @Override public void addHeader(String tag, String value) { } - @Override public void setQueryParams(String q) { } - @Override public void setFragment(String f) { } - @Override public void send() throws APIException { - try { - if (transfer != null) { - transfer.transfer(new PrintStream(new ByteArrayOutputStream())); - } - } catch (IOException e) { - } - } - @Override public Future futureCreate(Class t) { return null; } - @Override public Future futureReadString() { return null; } - @Override public Future futureRead(RosettaDF df, TYPE type) { return null; } - @Override public Future future(T t) { return null; } - @Override public Future future(HttpServletResponse resp, int expected) throws APIException { return null; } - } - - //private class FutureStub implements Future { - //} + @Mock RosettaDF dfMock; + @Mock RosettaData dataMock; + @Mock HttpURLConnection conMock; + @Mock HttpServletRequest reqMock; + @Mock HttpServletResponse respMock; + @Mock ServletInputStream isMock; + + private final static String uriString = "example.com"; + private final static String apiVersion = "v1.0"; + private final static String contentType = "contentType"; + + private static URI uri; + private static Enumeration enumeration; + + private Client client; + + @Before + public void setup() throws URISyntaxException, IOException { + MockitoAnnotations.initMocks(this); + + when(dfMock.getTypeClass()).thenReturn(HttpURLConnection.class); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.out((TYPE) any())).thenReturn(dataMock); + + when(reqMock.getInputStream()).thenReturn(isMock); + when(isMock.read((byte[]) any())).thenReturn(-1); + + uri = new URI(uriString); + enumeration = new CustomEnumeration(); + client = new Client(); + } + + @Test + public void createTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.XML); + + rcli.create(null, contentType, dfMock, conMock); + rcli.create("No question mark", contentType, dfMock, conMock); + rcli.create("question?mark", contentType, dfMock, conMock); + + rcli.create(null, dfMock, conMock); + rcli.create("No question mark", dfMock, conMock); + rcli.create("question?mark", dfMock, conMock); + + rcli.create(null, HttpURLConnection.class, dfMock, conMock); + rcli.create("No question mark", HttpURLConnection.class, dfMock, conMock); + rcli.create("question?mark", HttpURLConnection.class, dfMock, conMock); + + rcli.create(null, HttpURLConnection.class); + rcli.create("No question mark", HttpURLConnection.class); + rcli.create("question?mark", HttpURLConnection.class); + + rcli.create(null, contentType); + rcli.create("No question mark", contentType); + rcli.create("question?mark", contentType); + } + + @Test + public void postFormTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + + rcli.type(Data.TYPE.DEFAULT); + rcli.postForm(null, dfMock); + rcli.postForm("No question mark", dfMock); + rcli.postForm("question?mark", dfMock); + + rcli.type(Data.TYPE.JSON); + rcli.postForm("question?mark", dfMock); + + rcli.type(Data.TYPE.XML); + rcli.postForm("question?mark", dfMock); + + } + + @Test + public void readPostTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.readPost(null, dfMock, conMock); + rcli.readPost("No question mark", dfMock, conMock); + rcli.readPost("question?mark", dfMock, conMock); + + rcli.readPost(null, dfMock, conMock, dfMock); + rcli.readPost("No question mark", dfMock, conMock, dfMock); + rcli.readPost("question?mark", dfMock, conMock, dfMock); + + rcli.readPost("First string", "Second string"); + } + + @Test + public void readTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.read("First string", "Second string", "Third string", "Fourth string"); + rcli.read("First string", "Second string", dfMock, "Third string", "Fourth string"); + rcli.read("First string", dfMock, "Third string", "Fourth string"); + rcli.read("First string", HttpURLConnection.class ,dfMock); + } + + @Test + public void updateTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.update("First string", "Second string", dfMock, conMock); + rcli.update("First string", dfMock, conMock); + rcli.update("First string", HttpURLConnection.class, dfMock, conMock); + rcli.update("First string"); + rcli.updateRespondString("First string", dfMock, conMock); + } + + @Test + public void deleteTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.delete("First string", "Second string", dfMock, conMock); + rcli.delete("First string", dfMock, conMock); + rcli.delete("First string", HttpURLConnection.class, dfMock, conMock); + rcli.delete("First string", HttpURLConnection.class); + rcli.delete("First string", "Second string"); + } + + @Test + public void transferTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + when(reqMock.getRequestURI()).thenReturn(uriString); + when(reqMock.getHeaderNames()).thenReturn(enumeration); + rcli.transfer(reqMock, respMock, "string", 200); + + // coverage... + when(reqMock.getMethod()).thenReturn("GET"); + rcli.transfer(reqMock, respMock, "string", 200); + } + + @Test(expected = CadiException.class) + public void transferThrowsTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.transfer(reqMock, respMock, "string", 200); + } + + @Test + public void accessorMutatorTest() throws URISyntaxException { + RcliStub rcli = new RcliStub(); + Rcli rcliClone = rcli.forUser(null); + + rcli = new RcliStub(uri); + assertThat(rcli.toString(), is(uriString)); + assertThat(rcli.getURI(), is(uri)); + assertThat(rcli.getReadTimeout(), is(5000)); + assertThat(rcli.getConnectionTimeout(), is(3000)); + + rcli.connectionTimeout(3001); + assertThat(rcli.getConnectionTimeout(), is(3001)); + rcli.readTimeout(5001); + assertThat(rcli.getReadTimeout(), is(5001)); + rcli.apiVersion(apiVersion); + assertThat(rcli.isApiVersion(apiVersion), is(true)); + rcli.type(Data.TYPE.XML); + assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml;version=" + apiVersion)); + rcli.apiVersion(null); + assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml")); + + rcliClone = rcli.forUser(null); + assertThat(rcliClone.toString(), is(uriString)); + } + + private class RcliStub extends Rcli { + public RcliStub() { super(); } + public RcliStub(URI uri) { this.uri = uri; } + @Override public void setSecuritySetter(SecuritySetter ss) { } + @Override public SecuritySetter getSecuritySetter() { return null; } + @Override protected Rcli clone(URI uri, SecuritySetter ss) { return this; } + @Override public void invalidate() throws CadiException { } + @Override protected EClient client() throws CadiException { return client; } + public int getReadTimeout() { return readTimeout; } + public int getConnectionTimeout() { return connectionTimeout; } + } + + private class CustomEnumeration implements Enumeration { + private int idx = 0; + private final String[] elements = {"This", "is", "a", "test"}; + @Override + public String nextElement() { + return idx >= elements.length ? null : elements[idx++]; + } + @Override + public boolean hasMoreElements() { + return idx < elements.length; + } + } + + private class Client implements EClient { + private Transfer transfer; + @Override public void setPayload(Transfer transfer) { this.transfer = transfer; } + @Override public void setMethod(String meth) { } + @Override public void setPathInfo(String pathinfo) { } + @Override public void addHeader(String tag, String value) { } + @Override public void setQueryParams(String q) { } + @Override public void setFragment(String f) { } + @Override public void send() throws APIException { + try { + if (transfer != null) { + transfer.transfer(new PrintStream(new ByteArrayOutputStream())); + } + } catch (IOException e) { + } + } + @Override public Future futureCreate(Class t) { return null; } + @Override public Future futureReadString() { return null; } + @Override public Future futureRead(RosettaDF df, TYPE type) { return null; } + @Override public Future future(T t) { return null; } + @Override public Future future(HttpServletResponse resp, int expected) throws APIException { return null; } + } + + //private class FutureStub implements Future { + //} } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java index 05ca27f3..41570980 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java @@ -28,24 +28,24 @@ import org.junit.*; import org.onap.aaf.cadi.client.Result; public class JU_Result { - - private static final int OK = 200; - private static final int NOT_FOUND = 404; + + private static final int OK = 200; + private static final int NOT_FOUND = 404; - @Test - public void test() { - Result result; - result = Result.ok(OK, 10); - assertThat(result.toString(), is("Code: 200")); - assertThat(result.isOK(), is(true)); - - result = Result.err(NOT_FOUND, "File not found"); - assertThat(result.toString(), is("Code: 404 = File not found")); - assertThat(result.isOK(), is(false)); + @Test + public void test() { + Result result; + result = Result.ok(OK, 10); + assertThat(result.toString(), is("Code: 200")); + assertThat(result.isOK(), is(true)); + + result = Result.err(NOT_FOUND, "File not found"); + assertThat(result.toString(), is("Code: 404 = File not found")); + assertThat(result.isOK(), is(false)); - result = Result.err(result); - assertThat(result.toString(), is("Code: 404 = File not found")); - assertThat(result.isOK(), is(false)); - } - + result = Result.err(result); + assertThat(result.toString(), is("Code: 404 = File not found")); + assertThat(result.isOK(), is(false)); + } + } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java index 84863744..200b393d 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java @@ -35,25 +35,25 @@ import org.onap.aaf.misc.env.APIException; public class JU_Retryable { - @Test - public void test() { - RetryableStub retry = new RetryableStub(); - assertThat(retry.item(), is(nullValue())); - assertThat(retry.lastClient(), is(nullValue())); - - Locator.Item item = null; - assertThat(retry.item(item), is(item)); - - retry = new RetryableStub(retry); - assertThat(retry.item(), is(nullValue())); - assertThat(retry.lastClient(), is(nullValue())); - assertThat(retry.item(item), is(item)); - } - - private class RetryableStub extends Retryable { - public RetryableStub() { super(); } - public RetryableStub(Retryable ret) { super(ret); } - @Override public Integer code(Rcli client) throws CadiException, ConnectException, APIException { return null; } - } + @Test + public void test() { + RetryableStub retry = new RetryableStub(); + assertThat(retry.item(), is(nullValue())); + assertThat(retry.lastClient(), is(nullValue())); + + Locator.Item item = null; + assertThat(retry.item(item), is(item)); + + retry = new RetryableStub(retry); + assertThat(retry.item(), is(nullValue())); + assertThat(retry.lastClient(), is(nullValue())); + assertThat(retry.item(item), is(item)); + } + + private class RetryableStub extends Retryable { + public RetryableStub() { super(); } + public RetryableStub(Retryable ret) { super(ret); } + @Override public Integer code(Rcli client) throws CadiException, ConnectException, APIException { return null; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java index be12e7ac..4bb44e10 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java @@ -36,44 +36,44 @@ import org.onap.aaf.cadi.http.HAuthorizationHeader; public class JU_HAuthorizationHeader { - @Mock - SecurityInfoC siMock; + @Mock + SecurityInfoC siMock; - @Mock - HttpsURLConnection hucsMock; - - @Mock - HttpURLConnection hucMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } + @Mock + HttpsURLConnection hucsMock; + + @Mock + HttpURLConnection hucMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } - @Test - public void test() throws IOException, CadiException { - HAuthorizationHeader header = new HAuthorizationHeader(siMock, null, null); - header.setSecurity(hucsMock); - header.setSecurity(hucMock); + @Test + public void test() throws IOException, CadiException { + HAuthorizationHeader header = new HAuthorizationHeader(siMock, null, null); + header.setSecurity(hucsMock); + header.setSecurity(hucMock); - header = new HAuthorizationHeader(null, null, null); - header.setSecurity(hucsMock); - } - - @Test(expected = CadiException.class) - public void throwsWhenDeniedTest() throws CadiException, IOException { - HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { - @Override public boolean isDenied() { return true; } - }; - header.setSecurity(null); - } + header = new HAuthorizationHeader(null, null, null); + header.setSecurity(hucsMock); + } + + @Test(expected = CadiException.class) + public void throwsWhenDeniedTest() throws CadiException, IOException { + HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { + @Override public boolean isDenied() { return true; } + }; + header.setSecurity(null); + } - @Test(expected = CadiException.class) - public void throwsTest() throws CadiException, IOException { - HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { - @Override public String headValue() throws IOException { throw new IOException(); } - }; - header.setSecurity(null); - } + @Test(expected = CadiException.class) + public void throwsTest() throws CadiException, IOException { + HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { + @Override public String headValue() throws IOException { throw new IOException(); } + }; + header.setSecurity(null); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java index fa0a673f..d0655979 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java @@ -39,57 +39,57 @@ import org.onap.aaf.cadi.http.HSecurityInfoInit; import org.onap.aaf.cadi.principal.BasicPrincipal; public class JU_HBasicAuthSS { - - @Mock - BasicPrincipal bpMock; - - private SecurityInfoC si; - private PropAccess access; - - private final static String id = "id"; - private final static String password = "password"; - - @Before - public void setup() throws CadiException, IOException { - MockitoAnnotations.initMocks(this); - - when(bpMock.getName()).thenReturn(id); - when(bpMock.getCred()).thenReturn(password.getBytes()); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.AAF_APPID, id); - access.setProperty(Config.AAF_APPPASS, access.encrypt(password)); + + @Mock + BasicPrincipal bpMock; + + private SecurityInfoC si; + private PropAccess access; + + private final static String id = "id"; + private final static String password = "password"; + + @Before + public void setup() throws CadiException, IOException { + MockitoAnnotations.initMocks(this); + + when(bpMock.getName()).thenReturn(id); + when(bpMock.getCred()).thenReturn(password.getBytes()); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.AAF_APPID, id); + access.setProperty(Config.AAF_APPPASS, access.encrypt(password)); - si = SecurityInfoC.instance(access, HttpURLConnection.class); - } + si = SecurityInfoC.instance(access, HttpURLConnection.class); + } - @Test - public void test() throws IOException { - // All the constructors accomplish the same thing - @SuppressWarnings("unused") - HBasicAuthSS auth = new HBasicAuthSS(si); - - // TODO: While these test _should_ pass, and they _do_ pass on my local machine, they won't - // pass when then onap jobbuilder runs them. Good luck! -// assertThat(auth.getID(), is(id)); + @Test + public void test() throws IOException { + // All the constructors accomplish the same thing + @SuppressWarnings("unused") + HBasicAuthSS auth = new HBasicAuthSS(si); + + // TODO: While these test _should_ pass, and they _do_ pass on my local machine, they won't + // pass when then onap jobbuilder runs them. Good luck! +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(si, false); -// assertThat(auth.getID(), is(id)); + auth = new HBasicAuthSS(si, false); +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(si, id, password, false); -// assertThat(auth.getID(), is(id)); + auth = new HBasicAuthSS(si, id, password, false); +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(si, id, password, true); -// assertThat(auth.getID(), is(id)); + auth = new HBasicAuthSS(si, id, password, true); +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(bpMock, si); -// assertThat(auth.getID(), is(id)); - - auth = new HBasicAuthSS(bpMock, si, false); -// assertThat(auth.getID(), is(id)); - - auth = new HBasicAuthSS(bpMock, si, true); -// assertThat(auth.getID(), is(id)); - } + auth = new HBasicAuthSS(bpMock, si); +// assertThat(auth.getID(), is(id)); + + auth = new HBasicAuthSS(bpMock, si, false); +// assertThat(auth.getID(), is(id)); + + auth = new HBasicAuthSS(bpMock, si, true); +// assertThat(auth.getID(), is(id)); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java index 646d63fa..c32abe43 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java @@ -51,270 +51,270 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; public class JU_HClient { - @Mock private SecuritySetter ssMock; - @Mock private Transfer transferMock; - @Mock private HttpURLConnection hucMock; - @Mock private HttpServletResponse respMock; - @Mock private RosettaDF dfMock; - @Mock private RosettaData dataMock; - - private static final String uriString = "http://example.com:8080/path/to/a/file.txt"; - private static final String fragment = "fragment"; - private static final String method = "method"; - private static final String pathinfo = "pathinfo"; - private static final String queryParams = "queryParams"; - - private static final String errorString = "error string"; - private static final String successString = "success string"; - - private static final String tag1 = "tag1"; - private static final String tag2 = "tag2"; - private static final String value1 = "value1"; - private static final String value2 = "value2"; - - private URI uri; - - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); - - uri = new URI(uriString); - } - - @Test - public void accessorsMutatorsTest() throws LocatorException { - HClient client = new HClient(ssMock, uri, 0); - client.setFragment(fragment); - client.setMethod(method); - client.setPathInfo(pathinfo); - client.setPayload(transferMock); - client.setQueryParams(queryParams); - assertThat(client.getURI(), is(uri)); - assertThat(client.timeout(), is(0)); - assertThat(client.toString(), is("HttpURLConnection Client configured to " + uri.toString())); - } - - @Test - public void sendTest() throws LocatorException, APIException, URISyntaxException { - HClientStub client; - client = new HClientStub(ssMock, uri, 0, null); - client.send(); - - client.setPathInfo("/pathinfo"); - client.send(); - - client.setPathInfo("pathinfo"); - client.send(); - - client = new HClientStub(null, uri, 0, null); - client.send(); - - client.addHeader(tag1, value1); - client.addHeader(tag2, value2); - client.send(); - - client.setPayload(transferMock); - client.send(); - } - - @Test(expected = APIException.class) - public void sendThrows1Test() throws APIException, LocatorException, URISyntaxException { - HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); - client.send(); - } - - @Test(expected = APIException.class) - public void sendThrows2Test() throws APIException, LocatorException, URISyntaxException { - HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); - client.addHeader(tag1, value1); - client.addHeader(tag2, value2); - client.send(); - } - - @Test - public void futureCreateTest() throws LocatorException, CadiException, IOException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - HFuture future = (HFuture) client.futureCreate(HttpURLConnection.class); - - // Test a bad response code (default 0) without output - assertThat(future.get(0), is(false)); - assertThat(future.body().length(), is(0)); - - // Test a bad response code (default 0) with output - ByteArrayInputStream bais = new ByteArrayInputStream(errorString.getBytes()); - when(hucMock.getInputStream()).thenReturn(bais); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - - // Test a good response code - when(hucMock.getResponseCode()).thenReturn(201); - assertThat(future.get(0), is(true)); - } - - @Test - public void futureReadStringTest() throws LocatorException, CadiException, IOException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future future = client.futureReadString(); - - // Test a bad response code (default 0) without output - assertThat(future.get(0), is(false)); - assertThat(future.body().length(), is(0)); - - // Test a bad response code (default 0) with output - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is(successString)); - } - - @Test - public void futureReadTest() throws LocatorException, CadiException, IOException, APIException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future future = client.futureRead(dfMock, null); - - // Test a bad response code (default 0) without output - assertThat(future.get(0), is(false)); - assertThat(future.body().length(), is(0)); - - // Test a bad response code (default 0) with output - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(dfMock.newData()).thenReturn(dataMock); - when(dataMock.in(null)).thenReturn(dataMock); - when(dataMock.load((InputStream)any())).thenReturn(dataMock); - when(dataMock.asObject()).thenReturn(hucMock); - when(dataMock.asString()).thenReturn(successString); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is(successString)); - } - - @Test - public void future1Test() throws LocatorException, CadiException, IOException, APIException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future future = client.future(hucMock); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is("200")); - - // Test a bad response code - when(hucMock.getResponseCode()).thenReturn(0); - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - } - - @Test - public void future2Test() throws LocatorException, CadiException, IOException, APIException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future future = client.future(respMock, 200); - - ServletOutputStream sos = new ServletOutputStream() { - @Override public void write(int arg0) throws IOException { } - }; - when(respMock.getOutputStream()).thenReturn(sos); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is(nullValue())); - - // Test a bad response code - when(hucMock.getResponseCode()).thenReturn(0); - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is("")); - } - - @Test - public void hfutureTest() throws CadiException, IOException, LocatorException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - HFutureStub future = new HFutureStub(client, hucMock); - assertThat(future.get(0), is(false)); - - // Test a bad response code (default 0) with output - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - - assertThat(future.get(0), is(false)); - - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - - StringBuilder sb = future.inputStreamToString(new ByteArrayInputStream(errorString.getBytes())); - assertThat(sb.toString(), is(errorString)); - - assertThat(future.code(), is(200)); - assertThat(future.huc(), is(hucMock)); - - assertThat(future.exception(), is(nullValue())); - assertThat(future.header("string"), is(nullValue())); - - // coverage... - future.setHuc(null); - future.close(); - } - - @Test - public void headerTest() throws LocatorException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - String tag1 = "tag1"; - String tag2 = "tag2"; - String value1 = "value1"; - String value2 = "value2"; - client.addHeader(tag1, value1); - client.addHeader(tag2, value2); - } - - @Test(expected = LocatorException.class) - public void throws1Test() throws LocatorException { - @SuppressWarnings("unused") - HClient client = new HClient(ssMock, null, 0); - } - - private class HClientStub extends HClient { - public HClientStub(SecuritySetter ss, URI uri, int connectTimeout, HttpURLConnection huc) throws LocatorException { - super(ss, uri, connectTimeout); - setHuc(huc); - } - public void setHuc(HttpURLConnection huc) { - Field field; - try { - field = HClient.class.getDeclaredField("huc"); - field.setAccessible(true); - field.set(this, huc); - field.setAccessible(false); - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - fail("Caught an exception: " + e.getMessage()); - } - } - @Override - public HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException { - return hucMock; - } - } - - private class HFutureStub extends HFuture { - public HFutureStub(HClient hClient, HttpURLConnection huc) { - hClient.super(huc); - } - - @Override public String body() { return null; } - public void setHuc(HttpURLConnection huc) { this.huc = huc; } - } + @Mock private SecuritySetter ssMock; + @Mock private Transfer transferMock; + @Mock private HttpURLConnection hucMock; + @Mock private HttpServletResponse respMock; + @Mock private RosettaDF dfMock; + @Mock private RosettaData dataMock; + + private static final String uriString = "http://example.com:8080/path/to/a/file.txt"; + private static final String fragment = "fragment"; + private static final String method = "method"; + private static final String pathinfo = "pathinfo"; + private static final String queryParams = "queryParams"; + + private static final String errorString = "error string"; + private static final String successString = "success string"; + + private static final String tag1 = "tag1"; + private static final String tag2 = "tag2"; + private static final String value1 = "value1"; + private static final String value2 = "value2"; + + private URI uri; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + uri = new URI(uriString); + } + + @Test + public void accessorsMutatorsTest() throws LocatorException { + HClient client = new HClient(ssMock, uri, 0); + client.setFragment(fragment); + client.setMethod(method); + client.setPathInfo(pathinfo); + client.setPayload(transferMock); + client.setQueryParams(queryParams); + assertThat(client.getURI(), is(uri)); + assertThat(client.timeout(), is(0)); + assertThat(client.toString(), is("HttpURLConnection Client configured to " + uri.toString())); + } + + @Test + public void sendTest() throws LocatorException, APIException, URISyntaxException { + HClientStub client; + client = new HClientStub(ssMock, uri, 0, null); + client.send(); + + client.setPathInfo("/pathinfo"); + client.send(); + + client.setPathInfo("pathinfo"); + client.send(); + + client = new HClientStub(null, uri, 0, null); + client.send(); + + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + client.send(); + + client.setPayload(transferMock); + client.send(); + } + + @Test(expected = APIException.class) + public void sendThrows1Test() throws APIException, LocatorException, URISyntaxException { + HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); + client.send(); + } + + @Test(expected = APIException.class) + public void sendThrows2Test() throws APIException, LocatorException, URISyntaxException { + HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + client.send(); + } + + @Test + public void futureCreateTest() throws LocatorException, CadiException, IOException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + HFuture future = (HFuture) client.futureCreate(HttpURLConnection.class); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + ByteArrayInputStream bais = new ByteArrayInputStream(errorString.getBytes()); + when(hucMock.getInputStream()).thenReturn(bais); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getResponseCode()).thenReturn(201); + assertThat(future.get(0), is(true)); + } + + @Test + public void futureReadStringTest() throws LocatorException, CadiException, IOException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future future = client.futureReadString(); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(successString)); + } + + @Test + public void futureReadTest() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future future = client.futureRead(dfMock, null); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.in(null)).thenReturn(dataMock); + when(dataMock.load((InputStream)any())).thenReturn(dataMock); + when(dataMock.asObject()).thenReturn(hucMock); + when(dataMock.asString()).thenReturn(successString); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(successString)); + } + + @Test + public void future1Test() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future future = client.future(hucMock); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is("200")); + + // Test a bad response code + when(hucMock.getResponseCode()).thenReturn(0); + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + } + + @Test + public void future2Test() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future future = client.future(respMock, 200); + + ServletOutputStream sos = new ServletOutputStream() { + @Override public void write(int arg0) throws IOException { } + }; + when(respMock.getOutputStream()).thenReturn(sos); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(nullValue())); + + // Test a bad response code + when(hucMock.getResponseCode()).thenReturn(0); + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is("")); + } + + @Test + public void hfutureTest() throws CadiException, IOException, LocatorException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + HFutureStub future = new HFutureStub(client, hucMock); + assertThat(future.get(0), is(false)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + + assertThat(future.get(0), is(false)); + + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + + StringBuilder sb = future.inputStreamToString(new ByteArrayInputStream(errorString.getBytes())); + assertThat(sb.toString(), is(errorString)); + + assertThat(future.code(), is(200)); + assertThat(future.huc(), is(hucMock)); + + assertThat(future.exception(), is(nullValue())); + assertThat(future.header("string"), is(nullValue())); + + // coverage... + future.setHuc(null); + future.close(); + } + + @Test + public void headerTest() throws LocatorException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + String tag1 = "tag1"; + String tag2 = "tag2"; + String value1 = "value1"; + String value2 = "value2"; + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + } + + @Test(expected = LocatorException.class) + public void throws1Test() throws LocatorException { + @SuppressWarnings("unused") + HClient client = new HClient(ssMock, null, 0); + } + + private class HClientStub extends HClient { + public HClientStub(SecuritySetter ss, URI uri, int connectTimeout, HttpURLConnection huc) throws LocatorException { + super(ss, uri, connectTimeout); + setHuc(huc); + } + public void setHuc(HttpURLConnection huc) { + Field field; + try { + field = HClient.class.getDeclaredField("huc"); + field.setAccessible(true); + field.set(this, huc); + field.setAccessible(false); + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + fail("Caught an exception: " + e.getMessage()); + } + } + @Override + public HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException { + return hucMock; + } + } + + private class HFutureStub extends HFuture { + public HFutureStub(HClient hClient, HttpURLConnection huc) { + hClient.super(huc); + } + + @Override public String body() { return null; } + public void setHuc(HttpURLConnection huc) { this.huc = huc; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java index b7415a52..9d87d699 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java @@ -50,216 +50,216 @@ import org.onap.aaf.cadi.http.HMangr; import org.onap.aaf.misc.env.APIException; public class JU_HMangr { - - @Mock Locator locMock; - @Mock SecuritySetter ssMock; - @Mock Retryable retryableMock; - @Mock Retryable goodRetry; - @Mock Locator.Item itemMock; - @Mock Rcli clientMock; - - private PropAccess access; - private URI uri; - private final static String uriString = "http://example.com"; - - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - uri = new URI(uriString); - } - - @Test - public void sameTest() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - //coverage... - when(retryableMock.lastClient()).thenReturn(clientMock); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - CadiException cadiException; - - ConnectException connectException = new ConnectException(); - cadiException = new CadiException(connectException); - doThrow(cadiException).when(retryableMock).code(clientMock); - when(locMock.hasItems()).thenReturn(true).thenReturn(false); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - SocketException socketException = new SocketException(); - cadiException = new CadiException(socketException); - doThrow(cadiException).when(retryableMock).code(clientMock); - when(locMock.hasItems()).thenReturn(true).thenReturn(false); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - doThrow(connectException).when(retryableMock).code(clientMock); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - } - - @Test(expected = LocatorException.class) - public void throwsLocatorException1Test() throws LocatorException { - @SuppressWarnings("unused") - HMangr hman = new HMangr(access, null); - } - - @Test(expected = LocatorException.class) - public void throwsLocatorException2Test() throws LocatorException, APIException, CadiException { - HMangr hman = new HMangr(access, locMock); - hman.same(ssMock, retryableMock); - } - - @Test(expected = LocatorException.class) - public void throwsLocatorException3Test() throws LocatorException, APIException, CadiException { - HMangr hman = new HMangr(access, locMock); - when(locMock.best()).thenReturn(itemMock); - when(locMock.hasItems()).thenReturn(true).thenReturn(false); - hman.same(ssMock, retryableMock); - } - - @SuppressWarnings("unchecked") - @Test(expected = CadiException.class) - public void throwsCadiException1Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - when(retryableMock.code(clientMock)).thenThrow(CadiException.class); - hman.same(ssMock, retryableMock); - } - - @Test(expected = CadiException.class) - public void throwsCadiException2Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - - ConnectException connectException = new ConnectException(); - CadiException cadiException = new CadiException(connectException); - doThrow(cadiException).when(retryableMock).code(clientMock); - hman.same(ssMock, retryableMock); - } - - @Test(expected = CadiException.class) - public void throwsCadiException3Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - - SocketException socketException = new SocketException(); - CadiException cadiException = new CadiException(socketException); - doThrow(cadiException).when(retryableMock).code(clientMock); - hman.same(ssMock, retryableMock); - } - - @Test(expected = CadiException.class) - public void throwsCadiException4Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - - Exception e = new Exception(); - CadiException cadiException = new CadiException(e); - doThrow(cadiException).when(retryableMock).code(clientMock); - hman.same(ssMock, retryableMock); - } - - @Test - public void allTest() throws LocatorException, CadiException, APIException { - HManagerStub hman = new HManagerStub(access, locMock); - assertThat(hman.best(ssMock, retryableMock), is(nullValue())); - assertThat(hman.all(ssMock, retryableMock), is(nullValue())); - assertThat(hman.all(ssMock, retryableMock, true), is(nullValue())); - } - - @Test - public void oneOfTest() throws LocatorException, CadiException, APIException, ConnectException { - HMangr hman = new HMangr(access, locMock); - assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); - - try { - hman.oneOf(ssMock, retryableMock, true, "host"); - fail("Should've thrown an exception"); - } catch (LocatorException e) { - } - - when(locMock.first()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - - // Branching coverage... - assertThat(hman.oneOf(ssMock, retryableMock, false, null), is(nullValue())); - assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); - - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - CadiException cadiException; - - cadiException = new CadiException(new ConnectException()); - doThrow(cadiException).when(retryableMock).code((Rcli) any()); - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - cadiException = new CadiException(new SSLHandshakeException(null)); - doThrow(cadiException).when(retryableMock).code((Rcli) any()); - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - cadiException = new CadiException(new SocketException()); - doThrow(cadiException).when(retryableMock).code((Rcli) any()); - try { - hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); - fail("Should've thrown an exception"); - } catch (CadiException e) { - } - - cadiException = new CadiException(new SocketException("java.net.SocketException: Connection reset")); - doThrow(cadiException).when(retryableMock).code((Rcli) any()); - try { - hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); - fail("Should've thrown an exception"); - } catch (CadiException e) { - } - - cadiException = new CadiException(); - doThrow(cadiException).when(retryableMock).code((Rcli) any()); - try { - hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); - fail("Should've thrown an exception"); - } catch (CadiException e) { - } - - doThrow(new ConnectException()).when(retryableMock).code((Rcli) any()); - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - when(goodRetry.code((Rcli) any())).thenReturn(5); - assertThat(hman.oneOf(ssMock, goodRetry, false, uriString.substring(7)), is(5)); - } - - @Test - public void coverageTest() throws LocatorException { - HMangr hman = new HMangr(access, locMock); - hman.readTimeout(5); - assertThat(hman.readTimeout(), is(5)); - hman.connectionTimeout(5); - assertThat(hman.connectionTimeout(), is(5)); - hman.apiVersion("v1.0"); - assertThat(hman.apiVersion(), is("v1.0")); - hman.close(); - - } - - private class HManagerStub extends HMangr { - public HManagerStub(Access access, Locator loc) throws LocatorException { super(access, loc); } - @Override public RET same(SecuritySetter ss, Retryable retryable) { - return null; - } - @Override public RET oneOf(SecuritySetter ss, Retryable retryable, boolean notify, String host) { - return null; - } - } - + + @Mock Locator locMock; + @Mock SecuritySetter ssMock; + @Mock Retryable retryableMock; + @Mock Retryable goodRetry; + @Mock Locator.Item itemMock; + @Mock Rcli clientMock; + + private PropAccess access; + private URI uri; + private final static String uriString = "http://example.com"; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + uri = new URI(uriString); + } + + @Test + public void sameTest() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + //coverage... + when(retryableMock.lastClient()).thenReturn(clientMock); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + CadiException cadiException; + + ConnectException connectException = new ConnectException(); + cadiException = new CadiException(connectException); + doThrow(cadiException).when(retryableMock).code(clientMock); + when(locMock.hasItems()).thenReturn(true).thenReturn(false); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + SocketException socketException = new SocketException(); + cadiException = new CadiException(socketException); + doThrow(cadiException).when(retryableMock).code(clientMock); + when(locMock.hasItems()).thenReturn(true).thenReturn(false); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + doThrow(connectException).when(retryableMock).code(clientMock); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + } + + @Test(expected = LocatorException.class) + public void throwsLocatorException1Test() throws LocatorException { + @SuppressWarnings("unused") + HMangr hman = new HMangr(access, null); + } + + @Test(expected = LocatorException.class) + public void throwsLocatorException2Test() throws LocatorException, APIException, CadiException { + HMangr hman = new HMangr(access, locMock); + hman.same(ssMock, retryableMock); + } + + @Test(expected = LocatorException.class) + public void throwsLocatorException3Test() throws LocatorException, APIException, CadiException { + HMangr hman = new HMangr(access, locMock); + when(locMock.best()).thenReturn(itemMock); + when(locMock.hasItems()).thenReturn(true).thenReturn(false); + hman.same(ssMock, retryableMock); + } + + @SuppressWarnings("unchecked") + @Test(expected = CadiException.class) + public void throwsCadiException1Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + when(retryableMock.code(clientMock)).thenThrow(CadiException.class); + hman.same(ssMock, retryableMock); + } + + @Test(expected = CadiException.class) + public void throwsCadiException2Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + + ConnectException connectException = new ConnectException(); + CadiException cadiException = new CadiException(connectException); + doThrow(cadiException).when(retryableMock).code(clientMock); + hman.same(ssMock, retryableMock); + } + + @Test(expected = CadiException.class) + public void throwsCadiException3Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + + SocketException socketException = new SocketException(); + CadiException cadiException = new CadiException(socketException); + doThrow(cadiException).when(retryableMock).code(clientMock); + hman.same(ssMock, retryableMock); + } + + @Test(expected = CadiException.class) + public void throwsCadiException4Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + + Exception e = new Exception(); + CadiException cadiException = new CadiException(e); + doThrow(cadiException).when(retryableMock).code(clientMock); + hman.same(ssMock, retryableMock); + } + + @Test + public void allTest() throws LocatorException, CadiException, APIException { + HManagerStub hman = new HManagerStub(access, locMock); + assertThat(hman.best(ssMock, retryableMock), is(nullValue())); + assertThat(hman.all(ssMock, retryableMock), is(nullValue())); + assertThat(hman.all(ssMock, retryableMock, true), is(nullValue())); + } + + @Test + public void oneOfTest() throws LocatorException, CadiException, APIException, ConnectException { + HMangr hman = new HMangr(access, locMock); + assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); + + try { + hman.oneOf(ssMock, retryableMock, true, "host"); + fail("Should've thrown an exception"); + } catch (LocatorException e) { + } + + when(locMock.first()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + + // Branching coverage... + assertThat(hman.oneOf(ssMock, retryableMock, false, null), is(nullValue())); + assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); + + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + CadiException cadiException; + + cadiException = new CadiException(new ConnectException()); + doThrow(cadiException).when(retryableMock).code((Rcli) any()); + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + cadiException = new CadiException(new SSLHandshakeException(null)); + doThrow(cadiException).when(retryableMock).code((Rcli) any()); + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + cadiException = new CadiException(new SocketException()); + doThrow(cadiException).when(retryableMock).code((Rcli) any()); + try { + hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); + fail("Should've thrown an exception"); + } catch (CadiException e) { + } + + cadiException = new CadiException(new SocketException("java.net.SocketException: Connection reset")); + doThrow(cadiException).when(retryableMock).code((Rcli) any()); + try { + hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); + fail("Should've thrown an exception"); + } catch (CadiException e) { + } + + cadiException = new CadiException(); + doThrow(cadiException).when(retryableMock).code((Rcli) any()); + try { + hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); + fail("Should've thrown an exception"); + } catch (CadiException e) { + } + + doThrow(new ConnectException()).when(retryableMock).code((Rcli) any()); + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + when(goodRetry.code((Rcli) any())).thenReturn(5); + assertThat(hman.oneOf(ssMock, goodRetry, false, uriString.substring(7)), is(5)); + } + + @Test + public void coverageTest() throws LocatorException { + HMangr hman = new HMangr(access, locMock); + hman.readTimeout(5); + assertThat(hman.readTimeout(), is(5)); + hman.connectionTimeout(5); + assertThat(hman.connectionTimeout(), is(5)); + hman.apiVersion("v1.0"); + assertThat(hman.apiVersion(), is("v1.0")); + hman.close(); + + } + + private class HManagerStub extends HMangr { + public HManagerStub(Access access, Locator loc) throws LocatorException { super(access, loc); } + @Override public RET same(SecuritySetter ss, Retryable retryable) { + return null; + } + @Override public RET oneOf(SecuritySetter ss, Retryable retryable, boolean notify, String host) { + return null; + } + } + } \ No newline at end of file diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java index 9179aa36..923dd1a0 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java @@ -33,28 +33,28 @@ import org.onap.aaf.cadi.config.SecurityInfoC; import org.onap.aaf.cadi.http.HNoAuthSS; public class JU_HNoAuthSS { - - @Mock - SecurityInfoC siMock; - - @Mock - HttpURLConnection httpMock; + + @Mock + SecurityInfoC siMock; + + @Mock + HttpURLConnection httpMock; - @Mock - HttpsURLConnection httpsMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test() throws IOException, CadiException { - HNoAuthSS noAuth = new HNoAuthSS(null); - noAuth.setSecurity(httpMock); - noAuth = new HNoAuthSS(siMock); - noAuth.setSecurity(httpMock); - noAuth.setSecurity(httpsMock); - } + @Mock + HttpsURLConnection httpsMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws IOException, CadiException { + HNoAuthSS noAuth = new HNoAuthSS(null); + noAuth.setSecurity(httpMock); + noAuth = new HNoAuthSS(siMock); + noAuth.setSecurity(httpMock); + noAuth.setSecurity(httpsMock); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java index 06055ad6..ab6a39c0 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java @@ -44,78 +44,78 @@ import org.onap.aaf.cadi.http.HMangr; import org.onap.aaf.cadi.http.HRcli; public class JU_HRcli { - - @Mock - SecuritySetter ssMock; - - @Mock - Locator locMock; - - @Mock - Locator.Item itemMock; - - private HMangr hman; - private PropAccess access; - private static URI uri; - - private static final String uriString = "example.com"; - - @Before - public void setup() throws LocatorException, URISyntaxException { - MockitoAnnotations.initMocks(this); + + @Mock + SecuritySetter ssMock; + + @Mock + Locator locMock; + + @Mock + Locator.Item itemMock; + + private HMangr hman; + private PropAccess access; + private static URI uri; + + private static final String uriString = "example.com"; + + @Before + public void setup() throws LocatorException, URISyntaxException { + MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - hman = new HMangr(access, locMock); - uri = new URI(uriString); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + hman = new HMangr(access, locMock); + uri = new URI(uriString); - when(locMock.get(itemMock)).thenReturn(uri); - } + when(locMock.get(itemMock)).thenReturn(uri); + } - @Test(expected = CadiException.class) - public void publicInterfaceTest() throws URISyntaxException, LocatorException, CadiException { - HRcli hrcli = new HRcli(hman, itemMock, ssMock); - assertThat(hrcli.setManager(hman), is(hrcli)); - assertThat(hrcli.toString(), is(uriString)); + @Test(expected = CadiException.class) + public void publicInterfaceTest() throws URISyntaxException, LocatorException, CadiException { + HRcli hrcli = new HRcli(hman, itemMock, ssMock); + assertThat(hrcli.setManager(hman), is(hrcli)); + assertThat(hrcli.toString(), is(uriString)); - hrcli.setSecuritySetter(ssMock); - assertThat(hrcli.getSecuritySetter(), is(ssMock)); - - // No throw - hrcli.invalidate(); - // Throw - doThrow(CadiException.class).when(locMock).invalidate(itemMock); - hrcli.invalidate(); - } - - @Test(expected = CadiException.class) - public void protectedInterfaceTest() throws CadiException, LocatorException { - HRcliStub hrcli = new HRcliStub(hman, uri, itemMock, ssMock); - HRcli clone = hrcli.clone(uri, ssMock); - assertThat(clone.toString(), is(hrcli.toString())); - - EClient eclient = hrcli.client(); - assertThat(eclient, is(not(nullValue()))); + hrcli.setSecuritySetter(ssMock); + assertThat(hrcli.getSecuritySetter(), is(ssMock)); + + // No throw + hrcli.invalidate(); + // Throw + doThrow(CadiException.class).when(locMock).invalidate(itemMock); + hrcli.invalidate(); + } + + @Test(expected = CadiException.class) + public void protectedInterfaceTest() throws CadiException, LocatorException { + HRcliStub hrcli = new HRcliStub(hman, uri, itemMock, ssMock); + HRcli clone = hrcli.clone(uri, ssMock); + assertThat(clone.toString(), is(hrcli.toString())); + + EClient eclient = hrcli.client(); + assertThat(eclient, is(not(nullValue()))); - hrcli = new HRcliStub(hman, null, itemMock, ssMock); - when(locMock.best()).thenReturn(itemMock); - eclient = hrcli.client(); - assertThat(eclient, is(not(nullValue()))); + hrcli = new HRcliStub(hman, null, itemMock, ssMock); + when(locMock.best()).thenReturn(itemMock); + eclient = hrcli.client(); + assertThat(eclient, is(not(nullValue()))); - hrcli = new HRcliStub(hman, null, itemMock, ssMock); - when(locMock.best()).thenReturn(null); - eclient = hrcli.client(); - } - - private class HRcliStub extends HRcli { - public HRcliStub(HMangr hman, URI uri, Item locItem, SecuritySetter secSet) { - super(hman, uri, locItem, secSet); - } - public HRcli clone(URI uri, SecuritySetter ss) { - return super.clone(uri, ss); - } - public EClient client() throws CadiException { - return super.client(); - } - } + hrcli = new HRcliStub(hman, null, itemMock, ssMock); + when(locMock.best()).thenReturn(null); + eclient = hrcli.client(); + } + + private class HRcliStub extends HRcli { + public HRcliStub(HMangr hman, URI uri, Item locItem, SecuritySetter secSet) { + super(hman, uri, locItem, secSet); + } + public HRcli clone(URI uri, SecuritySetter ss) { + return super.clone(uri, ss); + } + public EClient client() throws CadiException { + return super.client(); + } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java index 0fb695ec..9f2c9a71 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java @@ -34,18 +34,18 @@ import org.onap.aaf.cadi.http.HTokenSS; public class JU_HTokenSS { - @Mock - SecurityInfoC siMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test() throws IOException { - HTokenSS token = new HTokenSS(siMock, "string1", "string2"); - assertThat(token, is(not(nullValue()))); - } + @Mock + SecurityInfoC siMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws IOException { + HTokenSS token = new HTokenSS(siMock, "string1", "string2"); + assertThat(token, is(not(nullValue()))); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java index fcb25d4e..77fac567 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java @@ -41,52 +41,52 @@ import org.onap.aaf.cadi.http.HTransferSS; import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_HTransferSS { - - @Mock - TaggedPrincipal princMock; - - @Mock - HttpURLConnection hucMock; + + @Mock + TaggedPrincipal princMock; + + @Mock + HttpURLConnection hucMock; - @Mock - HttpsURLConnection hucsMock; + @Mock + HttpsURLConnection hucsMock; - @Mock - SecurityInfoC siMock; - - @Mock - SecurityInfoC siMockNoDefSS; + @Mock + SecurityInfoC siMock; + + @Mock + SecurityInfoC siMockNoDefSS; - @Mock - SecuritySetter ssMock; - - private static final String princName = "name"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(princMock.getName()).thenReturn(princName); - siMock.defSS = ssMock; - } + @Mock + SecuritySetter ssMock; + + private static final String princName = "name"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(princMock.getName()).thenReturn(princName); + siMock.defSS = ssMock; + } - @Test - public void test() throws IOException, CadiException { - HTransferSS transfer = new HTransferSS(princMock, "string1"); - assertThat(transfer.setLastResponse(0), is(0)); - - transfer = new HTransferSS(princMock, "string1", siMock); - transfer.setSecurity(hucsMock); - assertThat(transfer.getID(), is(princName)); + @Test + public void test() throws IOException, CadiException { + HTransferSS transfer = new HTransferSS(princMock, "string1"); + assertThat(transfer.setLastResponse(0), is(0)); + + transfer = new HTransferSS(princMock, "string1", siMock); + transfer.setSecurity(hucsMock); + assertThat(transfer.getID(), is(princName)); - transfer = new HTransferSS(null, "string1", siMock); - transfer.setSecurity(hucsMock); - assertThat(transfer.getID(), is("")); - } + transfer = new HTransferSS(null, "string1", siMock); + transfer.setSecurity(hucsMock); + assertThat(transfer.getID(), is("")); + } - @Test(expected = CadiException.class) - public void testThrows() throws CadiException { - HTransferSS transfer = new HTransferSS(princMock, "string1", siMockNoDefSS); - transfer.setSecurity(hucMock); - } + @Test(expected = CadiException.class) + public void testThrows() throws CadiException { + HTransferSS transfer = new HTransferSS(princMock, "string1", siMockNoDefSS); + transfer.setSecurity(hucMock); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java index b57f29e0..fd102a95 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java @@ -48,70 +48,70 @@ import org.onap.aaf.cadi.http.HX509SS; import org.onap.aaf.misc.env.APIException; public class JU_HX509SS { - - @Mock X509Certificate x509Mock; - @Mock X509KeyManager keyManagerMock; - @Mock PrivateKey privateKeyMock; - @Mock SecurityInfoC siMock; - @Mock HttpURLConnection hucMock; - @Mock HttpsURLConnection hucsMock; - - private final static String alias = "Some alias"; - private final static String algName = "Some algName"; - private final static byte[] publicKeyBytes = "a public key".getBytes(); - - private PropAccess access; - private SecurityInfoC si; - - @Before - public void setup() throws IOException, CadiException, CertificateEncodingException { - MockitoAnnotations.initMocks(this); - - when(x509Mock.getSigAlgName()).thenReturn(algName); - when(x509Mock.getEncoded()).thenReturn(publicKeyBytes); - - when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[] {x509Mock}); - when(keyManagerMock.getPrivateKey(alias)).thenReturn(privateKeyMock); + + @Mock X509Certificate x509Mock; + @Mock X509KeyManager keyManagerMock; + @Mock PrivateKey privateKeyMock; + @Mock SecurityInfoC siMock; + @Mock HttpURLConnection hucMock; + @Mock HttpsURLConnection hucsMock; + + private final static String alias = "Some alias"; + private final static String algName = "Some algName"; + private final static byte[] publicKeyBytes = "a public key".getBytes(); + + private PropAccess access; + private SecurityInfoC si; + + @Before + public void setup() throws IOException, CadiException, CertificateEncodingException { + MockitoAnnotations.initMocks(this); + + when(x509Mock.getSigAlgName()).thenReturn(algName); + when(x509Mock.getEncoded()).thenReturn(publicKeyBytes); + + when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[] {x509Mock}); + when(keyManagerMock.getPrivateKey(alias)).thenReturn(privateKeyMock); - when(siMock.getKeyManagers()).thenReturn(new X509KeyManager[] {keyManagerMock}); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.CADI_ALIAS, alias); - // si = SecurityInfoC.instance(access, HttpURLConnectionStub.class); - } + when(siMock.getKeyManagers()).thenReturn(new X509KeyManager[] {keyManagerMock}); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_ALIAS, alias); + // si = SecurityInfoC.instance(access, HttpURLConnectionStub.class); + } - @Test - public void test() throws APIException, CadiException { - HX509SS x509 = new HX509SS(alias, siMock); - assertThat(x509.getID(), is(alias)); - assertThat(x509.setLastResponse(0), is(0)); - assertThat(x509.setLastResponse(1), is(0)); - assertThat(x509.setLastResponse(2), is(0)); - - // coverage... - x509.setSecurity(hucMock); - x509.setSecurity(hucsMock); - } - - // TODO: Test the setSecurity method - Ian - // @Test - // public void test2() throws APIException, CadiException { - // HX509SS x509 = new HX509SS(si, false); - // x509.setSecurity(hucMock); - // x509.setSecurity(hucsMock); - // } - - @Test(expected = APIException.class) - public void throws1Test() throws APIException, CadiException { - @SuppressWarnings("unused") - HX509SS x509 = new HX509SS(siMock); - } + @Test + public void test() throws APIException, CadiException { + HX509SS x509 = new HX509SS(alias, siMock); + assertThat(x509.getID(), is(alias)); + assertThat(x509.setLastResponse(0), is(0)); + assertThat(x509.setLastResponse(1), is(0)); + assertThat(x509.setLastResponse(2), is(0)); + + // coverage... + x509.setSecurity(hucMock); + x509.setSecurity(hucsMock); + } + + // TODO: Test the setSecurity method - Ian + // @Test + // public void test2() throws APIException, CadiException { + // HX509SS x509 = new HX509SS(si, false); + // x509.setSecurity(hucMock); + // x509.setSecurity(hucsMock); + // } + + @Test(expected = APIException.class) + public void throws1Test() throws APIException, CadiException { + @SuppressWarnings("unused") + HX509SS x509 = new HX509SS(siMock); + } - @Test(expected = APIException.class) - public void throws3Test() throws APIException, CadiException { - when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[0]); - @SuppressWarnings("unused") - HX509SS x509 = new HX509SS(alias, siMock); - } - + @Test(expected = APIException.class) + public void throws3Test() throws APIException, CadiException { + when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[0]); + @SuppressWarnings("unused") + HX509SS x509 = new HX509SS(alias, siMock); + } + } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java index a80e52f7..9b5bbafe 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java @@ -35,91 +35,91 @@ import org.onap.aaf.cadi.Locator.Item; import org.onap.aaf.cadi.locator.DNSLocator; public class JU_DNSLocator { - - private PropAccess access; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws LocatorException { - DNSLocator dl; - Item item; - URI uri; - - dl = new DNSLocator(access, "https", "localhost", "8100-8101"); - - item = dl.best(); - uri = dl.get(item); - assertThat(uri.toString(), is("https://127.0.0.1:8100")); - item = dl.best(); - assertThat(uri.toString(), is("https://127.0.0.1:8100")); - - assertThat(dl.hasItems(), is(true)); - for (item = dl.first(); item != null; item = dl.next(item)) { - dl.invalidate(item); - } - assertThat(dl.hasItems(), is(false)); - - // This doesn't actually do anything besides increase coverage - dl.destroy(); - } - - @Test - public void constructorTest() throws LocatorException { - // For coverage - new DNSLocator(access, "https", "localhost", "8100"); - new DNSLocator(access, "https", "localhost", "8100-8101"); - - new DNSLocator(access, "http:localhost"); - new DNSLocator(access, "https:localhost"); - new DNSLocator(access, "https:localhost:8100"); - new DNSLocator(access, "https:localhost:[8100]"); - new DNSLocator(access, "https:localhost:[8100-8101]"); - new DNSLocator(access, "https:localhost:8000/"); - } - - @Test - public void refreshTest() throws LocatorException { - DNSLocator dl = new DNSLocator(access, "https", "bogushost", "8100-8101"); - assertThat(dl.refresh(), is(false)); - } - - @Test(expected = LocatorException.class) - public void throws1Test() throws LocatorException { - new DNSLocator(access, null); - } - - @Test(expected = LocatorException.class) - public void throws2Test() throws LocatorException { - new DNSLocator(access, "ftp:invalid"); - } - - @Test(expected = LocatorException.class) - public void throws3Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[8100"); - } - - @Test(expected = LocatorException.class) - public void throws4Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[]"); - } - - @Test(expected = LocatorException.class) - public void throws5Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[8100-]"); - } - - @Test(expected = LocatorException.class) - public void throws6Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[-8101]"); - } - - @Test(expected = LocatorException.class) - public void throws7Test() throws LocatorException { - new DNSLocator(access, "https:localhost:/"); - } + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws LocatorException { + DNSLocator dl; + Item item; + URI uri; + + dl = new DNSLocator(access, "https", "localhost", "8100-8101"); + + item = dl.best(); + uri = dl.get(item); + assertThat(uri.toString(), is("https://127.0.0.1:8100")); + item = dl.best(); + assertThat(uri.toString(), is("https://127.0.0.1:8100")); + + assertThat(dl.hasItems(), is(true)); + for (item = dl.first(); item != null; item = dl.next(item)) { + dl.invalidate(item); + } + assertThat(dl.hasItems(), is(false)); + + // This doesn't actually do anything besides increase coverage + dl.destroy(); + } + + @Test + public void constructorTest() throws LocatorException { + // For coverage + new DNSLocator(access, "https", "localhost", "8100"); + new DNSLocator(access, "https", "localhost", "8100-8101"); + + new DNSLocator(access, "http:localhost"); + new DNSLocator(access, "https:localhost"); + new DNSLocator(access, "https:localhost:8100"); + new DNSLocator(access, "https:localhost:[8100]"); + new DNSLocator(access, "https:localhost:[8100-8101]"); + new DNSLocator(access, "https:localhost:8000/"); + } + + @Test + public void refreshTest() throws LocatorException { + DNSLocator dl = new DNSLocator(access, "https", "bogushost", "8100-8101"); + assertThat(dl.refresh(), is(false)); + } + + @Test(expected = LocatorException.class) + public void throws1Test() throws LocatorException { + new DNSLocator(access, null); + } + + @Test(expected = LocatorException.class) + public void throws2Test() throws LocatorException { + new DNSLocator(access, "ftp:invalid"); + } + + @Test(expected = LocatorException.class) + public void throws3Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[8100"); + } + + @Test(expected = LocatorException.class) + public void throws4Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[]"); + } + + @Test(expected = LocatorException.class) + public void throws5Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[8100-]"); + } + + @Test(expected = LocatorException.class) + public void throws6Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[-8101]"); + } + + @Test(expected = LocatorException.class) + public void throws7Test() throws LocatorException { + new DNSLocator(access, "https:localhost:/"); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java index 81140d23..e40ecb6e 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java @@ -39,112 +39,112 @@ import org.onap.aaf.cadi.locator.HClientHotPeerLocator; public class JU_HClientHotPeerLocator { - @Mock private HX509SS ssMock; - - private PropAccess access; - private ByteArrayOutputStream outStream; - - // Note: - The IP and port are irrelevant for these tests - private static final String goodURL1 = "fakeIP1:fakePort1/38/-90"; // Approx St Louis - private static final String goodURL2 = "fakeIP2:fakePort2/33/-96"; // Approx Dallas - private static final String badURL = "~%$!@#$//"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - outStream = new ByteArrayOutputStream(); - access = new PropAccess(new PrintStream(outStream), new String[0]); - } - - @Test - public void test() throws LocatorException { - HClientHotPeerLocator loc; - String urlStr = goodURL1 + ',' + goodURL2; - loc = new HClientHotPeerLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); - assertThat(loc.hasItems(), is(true)); - - String[] messages = outStream.toString().split(System.lineSeparator()); - String preffered = messages[0].split(" ", 4)[3]; - String alternate = messages[1].split(" ", 4)[3]; - assertThat(preffered, is("Preferred Client is " + goodURL1)); - assertThat(alternate, is("Alternate Client is " + goodURL2)); - - HClient firstClient = loc.get(loc.first()); - HClient bestClient = loc.bestClient(); - assertThat(bestClient, is(firstClient)); - - Locator.Item item = loc.first(); - assertThat(loc.info(item), is(goodURL1)); - - item = loc.next(item); - assertThat(loc.info(item), is(goodURL2)); - - item = loc.next(item); - assertThat(item, is(nullValue())); - assertThat(loc.info(item), is("Invalid Item")); - - item = loc.first(); - loc.invalidate(item); - - loc.invalidate(loc.bestClient()); - loc.invalidate(loc.get(loc.next(item))); - loc.destroy(); - } - - @Test(expected = LocatorException.class) - public void failuresTest() throws LocatorException { - HClientHotPeerLocator loc; - String urlStr = goodURL1 + ',' + goodURL2 + ',' + badURL; - loc = new HClientHotPeerLocator(access, urlStr, 1000000, "38.627", "-90.199", ssMock); - String[] messages = outStream.toString().split(System.lineSeparator()); - String preffered = messages[0].split(" ", 4)[3]; - String alternate1 = messages[1].split(" ", 4)[3]; - String alternate2 = messages[2].split(" ", 4)[3]; - assertThat(preffered, is("Preferred Client is " + badURL)); - assertThat(alternate1, is("Alternate Client is " + goodURL1)); - assertThat(alternate2, is("Alternate Client is " + goodURL2)); - - outStream.reset(); - - loc.invalidate(loc.first()); - - loc.destroy(); - loc.best(); - } - - @Test - public void hasNoItemTest() throws LocatorException { - HClientHotPeerLocator loc; - loc = new HClientHotPeerLocator(access, badURL, 0, "38.627", "-90.199", ssMock); - assertThat(loc.hasItems(), is(false)); - loc.invalidate(loc.first()); - } - - @Test(expected = LocatorException.class) - public void invalidClientTest() throws LocatorException { - @SuppressWarnings("unused") - HClientHotPeerLocator loc = new HClientHotPeerLocator(access, "InvalidClient", 0, "38.627", "-90.199", ssMock); - } - - @Test(expected = LocatorException.class) - public void coverageTest() throws LocatorException { - CoverageLocator loc; - String urlStr = goodURL1 + ',' + goodURL2; - loc = new CoverageLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); - assertThat(loc._invalidate(null), is(nullValue())); - loc._destroy(null); - - loc._newClient("bad string"); - } - - private class CoverageLocator extends HClientHotPeerLocator { - public CoverageLocator(Access access, String urlstr, long invalidateTime, String localLatitude, - String localLongitude, HX509SS ss) throws LocatorException { - super(access, urlstr, invalidateTime, localLatitude, localLongitude, ss); - } - public HClient _newClient(String clientInfo) throws LocatorException { return super._newClient(clientInfo); } - public HClient _invalidate(HClient client) { return super._invalidate(client); } - public void _destroy(HClient client) { super._destroy(client); } - } + @Mock private HX509SS ssMock; + + private PropAccess access; + private ByteArrayOutputStream outStream; + + // Note: - The IP and port are irrelevant for these tests + private static final String goodURL1 = "fakeIP1:fakePort1/38/-90"; // Approx St Louis + private static final String goodURL2 = "fakeIP2:fakePort2/33/-96"; // Approx Dallas + private static final String badURL = "~%$!@#$//"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]); + } + + @Test + public void test() throws LocatorException { + HClientHotPeerLocator loc; + String urlStr = goodURL1 + ',' + goodURL2; + loc = new HClientHotPeerLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); + assertThat(loc.hasItems(), is(true)); + + String[] messages = outStream.toString().split(System.lineSeparator()); + String preffered = messages[0].split(" ", 4)[3]; + String alternate = messages[1].split(" ", 4)[3]; + assertThat(preffered, is("Preferred Client is " + goodURL1)); + assertThat(alternate, is("Alternate Client is " + goodURL2)); + + HClient firstClient = loc.get(loc.first()); + HClient bestClient = loc.bestClient(); + assertThat(bestClient, is(firstClient)); + + Locator.Item item = loc.first(); + assertThat(loc.info(item), is(goodURL1)); + + item = loc.next(item); + assertThat(loc.info(item), is(goodURL2)); + + item = loc.next(item); + assertThat(item, is(nullValue())); + assertThat(loc.info(item), is("Invalid Item")); + + item = loc.first(); + loc.invalidate(item); + + loc.invalidate(loc.bestClient()); + loc.invalidate(loc.get(loc.next(item))); + loc.destroy(); + } + + @Test(expected = LocatorException.class) + public void failuresTest() throws LocatorException { + HClientHotPeerLocator loc; + String urlStr = goodURL1 + ',' + goodURL2 + ',' + badURL; + loc = new HClientHotPeerLocator(access, urlStr, 1000000, "38.627", "-90.199", ssMock); + String[] messages = outStream.toString().split(System.lineSeparator()); + String preffered = messages[0].split(" ", 4)[3]; + String alternate1 = messages[1].split(" ", 4)[3]; + String alternate2 = messages[2].split(" ", 4)[3]; + assertThat(preffered, is("Preferred Client is " + badURL)); + assertThat(alternate1, is("Alternate Client is " + goodURL1)); + assertThat(alternate2, is("Alternate Client is " + goodURL2)); + + outStream.reset(); + + loc.invalidate(loc.first()); + + loc.destroy(); + loc.best(); + } + + @Test + public void hasNoItemTest() throws LocatorException { + HClientHotPeerLocator loc; + loc = new HClientHotPeerLocator(access, badURL, 0, "38.627", "-90.199", ssMock); + assertThat(loc.hasItems(), is(false)); + loc.invalidate(loc.first()); + } + + @Test(expected = LocatorException.class) + public void invalidClientTest() throws LocatorException { + @SuppressWarnings("unused") + HClientHotPeerLocator loc = new HClientHotPeerLocator(access, "InvalidClient", 0, "38.627", "-90.199", ssMock); + } + + @Test(expected = LocatorException.class) + public void coverageTest() throws LocatorException { + CoverageLocator loc; + String urlStr = goodURL1 + ',' + goodURL2; + loc = new CoverageLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); + assertThat(loc._invalidate(null), is(nullValue())); + loc._destroy(null); + + loc._newClient("bad string"); + } + + private class CoverageLocator extends HClientHotPeerLocator { + public CoverageLocator(Access access, String urlstr, long invalidateTime, String localLatitude, + String localLongitude, HX509SS ss) throws LocatorException { + super(access, urlstr, invalidateTime, localLatitude, localLongitude, ss); + } + public HClient _newClient(String clientInfo) throws LocatorException { return super._newClient(clientInfo); } + public HClient _invalidate(HClient client) { return super._invalidate(client); } + public void _destroy(HClient client) { super._destroy(client); } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java index 024deff7..7b61e398 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java @@ -36,81 +36,81 @@ import org.onap.aaf.cadi.locator.PropertyLocator; public class JU_PropertyLocator { - @Mock - Socket socketMock; + @Mock + Socket socketMock; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); - when(socketMock.isConnected()).thenReturn(true); - when(socketMock.isClosed()).thenReturn(true).thenReturn(false); - } + when(socketMock.isConnected()).thenReturn(true); + when(socketMock.isClosed()).thenReturn(true).thenReturn(false); + } - @Test - public void test() throws Exception { - String uris = "https://fred.wilma.com:26444,https://tom.jerry.com:[534-535]"; - PropertyLocator pl = new PropertyLocator(uris, 0L, 1000*60*20L) { - @Override protected Socket createSocket() { return socketMock; } - }; - String str = pl.toString(); - assertThat(str.contains("https://fred.wilma.com:26444"), is(true)); - assertThat(str.contains("https://tom.jerry.com:534"), is(true)); - assertThat(str.contains("https://tom.jerry.com:535"), is(true)); + @Test + public void test() throws Exception { + String uris = "https://fred.wilma.com:26444,https://tom.jerry.com:[534-535]"; + PropertyLocator pl = new PropertyLocator(uris, 0L, 1000*60*20L) { + @Override protected Socket createSocket() { return socketMock; } + }; + String str = pl.toString(); + assertThat(str.contains("https://fred.wilma.com:26444"), is(true)); + assertThat(str.contains("https://tom.jerry.com:534"), is(true)); + assertThat(str.contains("https://tom.jerry.com:535"), is(true)); - Item item = pl.first(); - assertThat(item.toString(), is("Item: 0 order: 0")); + Item item = pl.first(); + assertThat(item.toString(), is("Item: 0 order: 0")); - URI uri = pl.get(item); - assertThat(uri.toString(), is("https://fred.wilma.com:26444")); + URI uri = pl.get(item); + assertThat(uri.toString(), is("https://fred.wilma.com:26444")); - assertThat(pl.get(null), is(nullValue())); + assertThat(pl.get(null), is(nullValue())); - assertThat(pl.hasItems(), is(true)); + assertThat(pl.hasItems(), is(true)); - assertThat(countItems(pl), is(3)); - pl.invalidate(pl.best()); + assertThat(countItems(pl), is(3)); + pl.invalidate(pl.best()); - assertThat(countItems(pl), is(2)); - pl.invalidate(pl.best()); + assertThat(countItems(pl), is(2)); + pl.invalidate(pl.best()); - assertThat(countItems(pl), is(1)); + assertThat(countItems(pl), is(1)); - pl.invalidate(pl.best()); + pl.invalidate(pl.best()); - assertThat(pl.hasItems(), is(false)); - assertThat(countItems(pl), is(0)); + assertThat(pl.hasItems(), is(false)); + assertThat(countItems(pl), is(0)); - Thread.sleep(20L); // PL checks same milli... - pl.refresh(); + Thread.sleep(20L); // PL checks same milli... + pl.refresh(); - assertThat(pl.hasItems(), is(true)); - - assertThat(pl.next(null), is(nullValue())); + assertThat(pl.hasItems(), is(true)); + + assertThat(pl.next(null), is(nullValue())); - // coverage... - pl.invalidate(null); - pl.invalidate(null); - pl.invalidate(null); - pl.invalidate(null); + // coverage... + pl.invalidate(null); + pl.invalidate(null); + pl.invalidate(null); + pl.invalidate(null); - pl.destroy(); + pl.destroy(); - pl = new PropertyLocator(uris); - - } + pl = new PropertyLocator(uris); + + } - @Test(expected=LocatorException.class) - public void exceptionTest() throws LocatorException { - new PropertyLocator(null); - } + @Test(expected=LocatorException.class) + public void exceptionTest() throws LocatorException { + new PropertyLocator(null); + } - private int countItems(PropertyLocator pl) throws LocatorException { - int count = 0; - for(Item i = pl.first(); i != null; i = pl.next(i)) { - ++count; - } - return count; - } + private int countItems(PropertyLocator pl) throws LocatorException { + int count = 0; + for(Item i = pl.first(); i != null; i = pl.next(i)) { + ++count; + } + return count; + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java b/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java index f492d4a2..31fda501 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java @@ -28,52 +28,52 @@ import org.onap.aaf.cadi.routing.GreatCircle; public class JU_GreatCircle { - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void calc1Test() { - assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); - assertEquals(0.0, GreatCircle.calc(38.627345, -90.193774, 38.627345, -90.193774), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(35.252234, -81.384929, 38.627345, -90.193774), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(-38.627345, 90.193774, -35.252234, 81.384929), 0.000000001); - assertEquals(105.71060033936052, GreatCircle.calc(-38.627345, 90.193774, -35.252234, -81.384929), 0.000000001); - assertEquals(105.71060033936052, GreatCircle.calc(38.627345, -90.193774, 35.252234, 81.384929), 0.000000001); - assertEquals(74.32786874922931, GreatCircle.calc(-38.627345, 90.193774, 35.252234, 81.384929), 0.000000001); - } + @Test + public void calc1Test() { + assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); + assertEquals(0.0, GreatCircle.calc(38.627345, -90.193774, 38.627345, -90.193774), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(35.252234, -81.384929, 38.627345, -90.193774), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(-38.627345, 90.193774, -35.252234, 81.384929), 0.000000001); + assertEquals(105.71060033936052, GreatCircle.calc(-38.627345, 90.193774, -35.252234, -81.384929), 0.000000001); + assertEquals(105.71060033936052, GreatCircle.calc(38.627345, -90.193774, 35.252234, 81.384929), 0.000000001); + assertEquals(74.32786874922931, GreatCircle.calc(-38.627345, 90.193774, 35.252234, 81.384929), 0.000000001); + } - @Test - public void calc2Test() { - assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345", "-90.193774", "35.252234", "-81.384929"}), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234,-81.384929"}), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774,35.252234,-81.384929"}), 0.000000001); + @Test + public void calc2Test() { + assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345", "-90.193774", "35.252234", "-81.384929"}), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234,-81.384929"}), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774,35.252234,-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[0]), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"38.627345;-90.193774", "35.252234,-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234;-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774;35.252234,-81.384929"}), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[0]), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[] {"38.627345;-90.193774", "35.252234,-81.384929"}), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234;-81.384929"}), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774;35.252234,-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"Invalid input", "Invalid input", "Invalid input", "Invalid input"}), 0.000000001); - } + assertEquals(-1, GreatCircle.calc(new String[] {"Invalid input", "Invalid input", "Invalid input", "Invalid input"}), 0.000000001); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - GreatCircle gc = new GreatCircle(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + GreatCircle gc = new GreatCircle(); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java b/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java index b0ac5a0c..5b47faab 100644 --- a/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java +++ b/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java @@ -30,79 +30,79 @@ import org.onap.aaf.cadi.client.Result; public class JU_ResultTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testOk() { - Result t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testOk() { + Result t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr() { - Result t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } - - @Test - public void testOk1() { - Result t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testErr() { + Result t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } + + @Test + public void testOk1() { + Result t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr1() { - Result t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } - - @Test - public void testOk2() { - Result t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testErr1() { + Result t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } + + @Test + public void testOk2() { + Result t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr2() { - Result t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } - - @Test - public void testOk3() { - Result t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testErr2() { + Result t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } + + @Test + public void testOk3() { + Result t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr3() { - Result t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } + @Test + public void testErr3() { + Result t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java b/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java index 3ef3355a..142dde26 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java @@ -52,80 +52,80 @@ import org.onap.aaf.cadi.util.Chmod; * */ public class AES implements Encryption { - public static final String AES = AES.class.getSimpleName(); - public static final int AES_KEY_SIZE = 128; // 256 isn't supported on all JDKs. - - private SecretKeySpec aeskeySpec; + public static final String AES = AES.class.getSimpleName(); + public static final int AES_KEY_SIZE = 128; // 256 isn't supported on all JDKs. + + private SecretKeySpec aeskeySpec; - public static SecretKey newKey() throws NoSuchAlgorithmException { - KeyGenerator kgen = KeyGenerator.getInstance(AES); - kgen.init(AES_KEY_SIZE); - return kgen.generateKey(); - } + public static SecretKey newKey() throws NoSuchAlgorithmException { + KeyGenerator kgen = KeyGenerator.getInstance(AES); + kgen.init(AES_KEY_SIZE); + return kgen.generateKey(); + } - public AES(byte[] aeskey, int offset, int len) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException { - aeskeySpec = new SecretKeySpec(aeskey,offset,len,AES); - } - - public byte[] encrypt(byte[] in) throws CadiException { - try { - Cipher c = Cipher.getInstance(AES); - c.init(Cipher.ENCRYPT_MODE,aeskeySpec); - return c.doFinal(in); - } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new CadiException(e); - } - } - - public byte[] decrypt(byte[] in) throws CadiException { - try { - Cipher c = Cipher.getInstance(AES); - c.init(Cipher.DECRYPT_MODE,aeskeySpec); - return c.doFinal(in); - } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new CadiException(e); - } - } - - public void save(File keyfile) throws IOException { - FileOutputStream fis = new FileOutputStream(keyfile); - try { - fis.write(aeskeySpec.getEncoded()); - } finally { - fis.close(); - } - Chmod.to400.chmod(keyfile); - } + public AES(byte[] aeskey, int offset, int len) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException { + aeskeySpec = new SecretKeySpec(aeskey,offset,len,AES); + } + + public byte[] encrypt(byte[] in) throws CadiException { + try { + Cipher c = Cipher.getInstance(AES); + c.init(Cipher.ENCRYPT_MODE,aeskeySpec); + return c.doFinal(in); + } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException e) { + throw new CadiException(e); + } + } + + public byte[] decrypt(byte[] in) throws CadiException { + try { + Cipher c = Cipher.getInstance(AES); + c.init(Cipher.DECRYPT_MODE,aeskeySpec); + return c.doFinal(in); + } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException e) { + throw new CadiException(e); + } + } + + public void save(File keyfile) throws IOException { + FileOutputStream fis = new FileOutputStream(keyfile); + try { + fis.write(aeskeySpec.getEncoded()); + } finally { + fis.close(); + } + Chmod.to400.chmod(keyfile); + } - public CipherOutputStream outputStream(OutputStream os, boolean encrypt) { - try { - Cipher c = Cipher.getInstance(AES); - if(encrypt) { - c.init(Cipher.ENCRYPT_MODE,aeskeySpec); - } else { - c.init(Cipher.DECRYPT_MODE,aeskeySpec); - } - return new CipherOutputStream(os,c); - } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { - // Cannot add Exception to this API. throw Runtime - System.err.println("Error creating Aes CipherOutputStream"); - return null; // should never get here. - } - } - - public CipherInputStream inputStream(InputStream is, boolean encrypt) { - try { - Cipher c = Cipher.getInstance(AES); - if(encrypt) { - c.init(Cipher.ENCRYPT_MODE,aeskeySpec); - } else { - c.init(Cipher.DECRYPT_MODE,aeskeySpec); - } - return new CipherInputStream(is,c); - } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { - // Cannot add Exception to this API. throw Runtime - System.err.println("Error creating Aes CipherInputStream"); - return null; // should never get here. - } - } + public CipherOutputStream outputStream(OutputStream os, boolean encrypt) { + try { + Cipher c = Cipher.getInstance(AES); + if(encrypt) { + c.init(Cipher.ENCRYPT_MODE,aeskeySpec); + } else { + c.init(Cipher.DECRYPT_MODE,aeskeySpec); + } + return new CipherOutputStream(os,c); + } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { + // Cannot add Exception to this API. throw Runtime + System.err.println("Error creating Aes CipherOutputStream"); + return null; // should never get here. + } + } + + public CipherInputStream inputStream(InputStream is, boolean encrypt) { + try { + Cipher c = Cipher.getInstance(AES); + if(encrypt) { + c.init(Cipher.ENCRYPT_MODE,aeskeySpec); + } else { + c.init(Cipher.DECRYPT_MODE,aeskeySpec); + } + return new CipherInputStream(is,c); + } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { + // Cannot add Exception to this API. throw Runtime + System.err.println("Error creating Aes CipherInputStream"); + return null; // should never get here. + } + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java b/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java index 39631894..d9d4474d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java @@ -48,420 +48,420 @@ import org.onap.aaf.cadi.principal.CachedBasicPrincipal; * */ public abstract class AbsUserCache { - // Need an obvious key for when there is no Authentication Cred - private static final String NO_CRED = "NoCred"; - static final int MIN_INTERVAL = 1000*60; // Min 1 min - static final int MAX_INTERVAL = 1000*60*60*4; // 4 hour max - private static Timer timer; - // Map of userName to User - private final Map> userMap; - private static final Map missMap = new TreeMap<>(); - private final Symm missEncrypt; - - private Clean clean; - protected Access access; - - protected AbsUserCache(Access access, long cleanInterval, int highCount, int usageCount) { - this.access = access; - Symm s; - try { - byte[] gennedKey = Symm.keygen(); - s = Symm.obtain(new ByteArrayInputStream(gennedKey)); - } catch (IOException e) { - access.log(e); - s = Symm.base64noSplit; - } - missEncrypt = s; - - userMap = new ConcurrentHashMap<>(); + // Need an obvious key for when there is no Authentication Cred + private static final String NO_CRED = "NoCred"; + static final int MIN_INTERVAL = 1000*60; // Min 1 min + static final int MAX_INTERVAL = 1000*60*60*4; // 4 hour max + private static Timer timer; + // Map of userName to User + private final Map> userMap; + private static final Map missMap = new TreeMap<>(); + private final Symm missEncrypt; + + private Clean clean; + protected Access access; + + protected AbsUserCache(Access access, long cleanInterval, int highCount, int usageCount) { + this.access = access; + Symm s; + try { + byte[] gennedKey = Symm.keygen(); + s = Symm.obtain(new ByteArrayInputStream(gennedKey)); + } catch (IOException e) { + access.log(e); + s = Symm.base64noSplit; + } + missEncrypt = s; + + userMap = new ConcurrentHashMap<>(); - - if(cleanInterval>0) { - cleanInterval = Math.max(MIN_INTERVAL, cleanInterval); - synchronized(AbsUserCache.class) { // Lazy instantiate.. in case there is no cleanup needed - if(timer==null) { - timer = new Timer("CADI Cleanup Timer",true); - } - - timer.schedule(clean = new Clean(access, cleanInterval, highCount, usageCount), cleanInterval, cleanInterval); - access.log(Access.Level.INIT, "Cleaning Thread initialized with interval of",cleanInterval, "ms and max objects of", highCount); - } - } - } - - @SuppressWarnings("unchecked") - public AbsUserCache(AbsUserCache cache) { - this.access = cache.access; - userMap = cache.userMap; - missEncrypt = cache.missEncrypt; - - synchronized(AbsUserCache.class) { - if(cache.clean!=null && cache.clean.lur==null && this instanceof CachingLur) { - cache.clean.lur=(CachingLur)this; - } - } - } + + if(cleanInterval>0) { + cleanInterval = Math.max(MIN_INTERVAL, cleanInterval); + synchronized(AbsUserCache.class) { // Lazy instantiate.. in case there is no cleanup needed + if(timer==null) { + timer = new Timer("CADI Cleanup Timer",true); + } + + timer.schedule(clean = new Clean(access, cleanInterval, highCount, usageCount), cleanInterval, cleanInterval); + access.log(Access.Level.INIT, "Cleaning Thread initialized with interval of",cleanInterval, "ms and max objects of", highCount); + } + } + } + + @SuppressWarnings("unchecked") + public AbsUserCache(AbsUserCache cache) { + this.access = cache.access; + userMap = cache.userMap; + missEncrypt = cache.missEncrypt; + + synchronized(AbsUserCache.class) { + if(cache.clean!=null && cache.clean.lur==null && this instanceof CachingLur) { + cache.clean.lur=(CachingLur)this; + } + } + } - protected void setLur(CachingLur lur) { - if(clean!=null)clean.lur = lur; - - } - - protected void addUser(User user) { - Principal p = user.principal; - String key; - try { - if(p instanceof GetCred) { - key = missKey(p.getName(), ((GetCred)p).getCred()); - } else { - byte[] cred; - if((cred=user.getCred())==null) { - key = user.name + NO_CRED; - } else { - key = missKey(user.name,cred); - } - } - } catch (IOException e) { - access.log(e); - return; - } - userMap.put(key, user); - } + protected void setLur(CachingLur lur) { + if(clean!=null)clean.lur = lur; + + } + + protected void addUser(User user) { + Principal p = user.principal; + String key; + try { + if(p instanceof GetCred) { + key = missKey(p.getName(), ((GetCred)p).getCred()); + } else { + byte[] cred; + if((cred=user.getCred())==null) { + key = user.name + NO_CRED; + } else { + key = missKey(user.name,cred); + } + } + } catch (IOException e) { + access.log(e); + return; + } + userMap.put(key, user); + } - // Useful for looking up by WebToken, etc. - protected void addUser(String key, User user) { - userMap.put(key, user); - } - - /** - * Add miss to missMap. If Miss exists, or too many tries, returns false. - * - * otherwise, returns true to allow another attempt. - * - * @param key - * @param bs - * @return - * @throws IOException - */ - protected synchronized boolean addMiss(String key, byte[] bs) { - String mkey; - try { - mkey = missKey(key,bs); - } catch (IOException e) { - access.log(e); - return false; - } - Miss miss = missMap.get(mkey); - if(miss==null) { - missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval,key)); - return true; - } - return miss.mayContinue(); - } + // Useful for looking up by WebToken, etc. + protected void addUser(String key, User user) { + userMap.put(key, user); + } + + /** + * Add miss to missMap. If Miss exists, or too many tries, returns false. + * + * otherwise, returns true to allow another attempt. + * + * @param key + * @param bs + * @return + * @throws IOException + */ + protected synchronized boolean addMiss(String key, byte[] bs) { + String mkey; + try { + mkey = missKey(key,bs); + } catch (IOException e) { + access.log(e); + return false; + } + Miss miss = missMap.get(mkey); + if(miss==null) { + missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval,key)); + return true; + } + return miss.mayContinue(); + } - protected Miss missed(String key, byte[] bs) throws IOException { - return missMap.get(missKey(key,bs)); - } + protected Miss missed(String key, byte[] bs) throws IOException { + return missMap.get(missKey(key,bs)); + } - protected User getUser(Principal principal) { - String key; - if(principal instanceof GetCred) { - GetCred gc = (GetCred)principal; - try { - key = missKey(principal.getName(), gc.getCred()); - } catch (IOException e) { - access.log(e, "Error getting key from Principal"); - key = principal.getName(); - } - } else { - key = principal.getName()+NO_CRED; - } - User u = userMap.get(key); - if(u!=null) { - u.incCount(); - } - return u; - } - - protected User getUser(CachedBasicPrincipal cbp) { - return getUser(cbp.getName(), cbp.getCred()); - } - - protected User getUser(String user, byte[] cred) { - User u; - String key=null; - try { - key =missKey(user,cred); - } catch (IOException e) { - access.log(e); - return null; - } - u = userMap.get(key); - if(u!=null) { - if(u.permExpired()) { - userMap.remove(key); - u=null; - } else { - u.incCount(); - } - } - return u; - } - - /** - * Removes User from the Cache - * @param user - */ - protected void remove(User user) { - userMap.remove(user.principal.getName()); - } - - /** - * Removes user from the Cache - * - * @param user - */ - public void remove(String user) { - Object o = userMap.remove(user); - if(o!=null) { - access.log(Level.INFO, user,"removed from Client Cache by Request"); - } - } - - /** - * Clear all Users from the Client Cache - */ - public void clearAll() { - userMap.clear(); - } - - public final List dumpInfo() { - List rv = new ArrayList<>(); - for(User user : userMap.values()) { - rv.add(new DumpInfo(user)); - } - return rv; - } + protected User getUser(Principal principal) { + String key; + if(principal instanceof GetCred) { + GetCred gc = (GetCred)principal; + try { + key = missKey(principal.getName(), gc.getCred()); + } catch (IOException e) { + access.log(e, "Error getting key from Principal"); + key = principal.getName(); + } + } else { + key = principal.getName()+NO_CRED; + } + User u = userMap.get(key); + if(u!=null) { + u.incCount(); + } + return u; + } + + protected User getUser(CachedBasicPrincipal cbp) { + return getUser(cbp.getName(), cbp.getCred()); + } + + protected User getUser(String user, byte[] cred) { + User u; + String key=null; + try { + key =missKey(user,cred); + } catch (IOException e) { + access.log(e); + return null; + } + u = userMap.get(key); + if(u!=null) { + if(u.permExpired()) { + userMap.remove(key); + u=null; + } else { + u.incCount(); + } + } + return u; + } + + /** + * Removes User from the Cache + * @param user + */ + protected void remove(User user) { + userMap.remove(user.principal.getName()); + } + + /** + * Removes user from the Cache + * + * @param user + */ + public void remove(String user) { + Object o = userMap.remove(user); + if(o!=null) { + access.log(Level.INFO, user,"removed from Client Cache by Request"); + } + } + + /** + * Clear all Users from the Client Cache + */ + public void clearAll() { + userMap.clear(); + } + + public final List dumpInfo() { + List rv = new ArrayList<>(); + for(User user : userMap.values()) { + rv.add(new DumpInfo(user)); + } + return rv; + } - /** - * The default behavior of a LUR is to not handle something exclusively. - */ - public boolean handlesExclusively(Permission ... pond) { - return false; - } - - /** - * Container calls when cleaning up... - * - * If overloading in Derived class, be sure to call "super.destroy()" - */ - public void destroy() { - if(timer!=null) { - timer.purge(); - timer.cancel(); - } - } - - + /** + * The default behavior of a LUR is to not handle something exclusively. + */ + public boolean handlesExclusively(Permission ... pond) { + return false; + } + + /** + * Container calls when cleaning up... + * + * If overloading in Derived class, be sure to call "super.destroy()" + */ + public void destroy() { + if(timer!=null) { + timer.purge(); + timer.cancel(); + } + } + + - // Simple map of Group name to a set of User Names - // private Map> groupMap = new HashMap<>(); + // Simple map of Group name to a set of User Names + // private Map> groupMap = new HashMap<>(); - /** - * Class to hold a small subset of the data, because we don't want to expose actual Permission or User Objects - */ - public final class DumpInfo { - public String user; - public List perms; - - public DumpInfo(User user) { - this.user = user.principal.getName(); - perms = new ArrayList<>(user.perms.keySet()); - } - } - - /** - * Clean will examine resources, and remove those that have expired. - * - * If "highs" have been exceeded, then we'll expire 10% more the next time. This will adjust after each run - * without checking contents more than once, making a good average "high" in the minimum speed. - * - * @author Jonathan - * - */ - private final class Clean extends TimerTask { - private final Access access; - private CachingLur lur; - - // The idea here is to not be too restrictive on a high, but to Expire more items by - // shortening the time to expire. This is done by judiciously incrementing "advance" - // when the "highs" are exceeded. This effectively reduces numbers of cached items quickly. - private final int high; - private long advance; - private final long timeInterval; - private final int usageTriggerCount; - - public Clean(Access access, long cleanInterval, int highCount, int usageTriggerCount) { - this.access = access; - lur = null; - high = highCount; - timeInterval = cleanInterval; - advance = 0; - this.usageTriggerCount=usageTriggerCount; - } - public void run() { - int renewed = 0; - int count = 0; - int total = 0; - try { - // look at now. If we need to expire more by increasing "now" by "advance" - ArrayList> al = new ArrayList<>(userMap.values().size()); - al.addAll(0, userMap.values()); - long now = System.currentTimeMillis() + advance; - for(User user : al) { - ++total; - if(user.count>usageTriggerCount) { - boolean touched = false, removed=false; - if(user.principal instanceof CachedPrincipal) { - CachedPrincipal cp = (CachedPrincipal)user.principal; - if(cp.expires() < now) { - switch(cp.revalidate(null)) { - case INACCESSIBLE: - access.log(Level.AUDIT, "AAF Inaccessible. Keeping credentials"); - break; - case REVALIDATED: - user.resetCount(); - touched = true; - break; - default: - user.resetCount(); - remove(user); - ++count; - removed = true; - break; - } - } - } - - if(!removed && lur!=null && user.permExpires<= now ) { - if(lur.reload(user).equals(Resp.REVALIDATED)) { - user.renewPerm(); - access.log(Level.DEBUG, "Reloaded Perms for",user); - touched = true; - } - } - user.resetCount(); - if(touched) { - ++renewed; - } - - } else { - if(user.permExpired()) { - remove(user); - ++count; - } - } - } - - // Clean out Misses - int missTotal = missMap.keySet().size(); - int miss = 0; - if(missTotal>0) { - ArrayList keys = new ArrayList<>(missTotal); - keys.addAll(missMap.keySet()); - for(String key : keys) { - Miss m = missMap.get(key); - if(m!=null) { - long timeLeft = m.timestamp - System.currentTimeMillis(); - if(timeLeft<0) { - synchronized(missMap) { - missMap.remove(key); - } - access.log(Level.INFO, m.name, " has been removed from Missed Credential Map (" + m.tries + " invalid tries)"); - ++miss; - } else { - access.log(Level.INFO, m.name, " remains in Missed Credential Map (" + m.tries + " invalid tries) for " + (timeLeft/1000) + " more seconds"); - } - } - } - } - - if(count+renewed+miss>0) { - access.log(Level.INFO, (lur==null?"Cache":lur.getClass().getSimpleName()), "removed",count, - "and renewed",renewed,"expired Permissions out of", total,"and removed", miss, "password misses out of",missTotal); - } - - // If High (total) is reached during this period, increase the number of expired services removed for next time. - // There's no point doing it again here, as there should have been cleaned items. - if(total>high) { - // advance cleanup by 10%, without getting greater than timeInterval. - advance = Math.min(timeInterval, advance+(timeInterval/10)); - } else { - // reduce advance by 10%, without getting lower than 0. - advance = Math.max(0, advance-(timeInterval/10)); - } - } catch (Exception e) { - access.log(Level.ERROR,e.getMessage()); - } - } - } + /** + * Class to hold a small subset of the data, because we don't want to expose actual Permission or User Objects + */ + public final class DumpInfo { + public String user; + public List perms; + + public DumpInfo(User user) { + this.user = user.principal.getName(); + perms = new ArrayList<>(user.perms.keySet()); + } + } + + /** + * Clean will examine resources, and remove those that have expired. + * + * If "highs" have been exceeded, then we'll expire 10% more the next time. This will adjust after each run + * without checking contents more than once, making a good average "high" in the minimum speed. + * + * @author Jonathan + * + */ + private final class Clean extends TimerTask { + private final Access access; + private CachingLur lur; + + // The idea here is to not be too restrictive on a high, but to Expire more items by + // shortening the time to expire. This is done by judiciously incrementing "advance" + // when the "highs" are exceeded. This effectively reduces numbers of cached items quickly. + private final int high; + private long advance; + private final long timeInterval; + private final int usageTriggerCount; + + public Clean(Access access, long cleanInterval, int highCount, int usageTriggerCount) { + this.access = access; + lur = null; + high = highCount; + timeInterval = cleanInterval; + advance = 0; + this.usageTriggerCount=usageTriggerCount; + } + public void run() { + int renewed = 0; + int count = 0; + int total = 0; + try { + // look at now. If we need to expire more by increasing "now" by "advance" + ArrayList> al = new ArrayList<>(userMap.values().size()); + al.addAll(0, userMap.values()); + long now = System.currentTimeMillis() + advance; + for(User user : al) { + ++total; + if(user.count>usageTriggerCount) { + boolean touched = false, removed=false; + if(user.principal instanceof CachedPrincipal) { + CachedPrincipal cp = (CachedPrincipal)user.principal; + if(cp.expires() < now) { + switch(cp.revalidate(null)) { + case INACCESSIBLE: + access.log(Level.AUDIT, "AAF Inaccessible. Keeping credentials"); + break; + case REVALIDATED: + user.resetCount(); + touched = true; + break; + default: + user.resetCount(); + remove(user); + ++count; + removed = true; + break; + } + } + } + + if(!removed && lur!=null && user.permExpires<= now ) { + if(lur.reload(user).equals(Resp.REVALIDATED)) { + user.renewPerm(); + access.log(Level.DEBUG, "Reloaded Perms for",user); + touched = true; + } + } + user.resetCount(); + if(touched) { + ++renewed; + } + + } else { + if(user.permExpired()) { + remove(user); + ++count; + } + } + } + + // Clean out Misses + int missTotal = missMap.keySet().size(); + int miss = 0; + if(missTotal>0) { + ArrayList keys = new ArrayList<>(missTotal); + keys.addAll(missMap.keySet()); + for(String key : keys) { + Miss m = missMap.get(key); + if(m!=null) { + long timeLeft = m.timestamp - System.currentTimeMillis(); + if(timeLeft<0) { + synchronized(missMap) { + missMap.remove(key); + } + access.log(Level.INFO, m.name, " has been removed from Missed Credential Map (" + m.tries + " invalid tries)"); + ++miss; + } else { + access.log(Level.INFO, m.name, " remains in Missed Credential Map (" + m.tries + " invalid tries) for " + (timeLeft/1000) + " more seconds"); + } + } + } + } + + if(count+renewed+miss>0) { + access.log(Level.INFO, (lur==null?"Cache":lur.getClass().getSimpleName()), "removed",count, + "and renewed",renewed,"expired Permissions out of", total,"and removed", miss, "password misses out of",missTotal); + } + + // If High (total) is reached during this period, increase the number of expired services removed for next time. + // There's no point doing it again here, as there should have been cleaned items. + if(total>high) { + // advance cleanup by 10%, without getting greater than timeInterval. + advance = Math.min(timeInterval, advance+(timeInterval/10)); + } else { + // reduce advance by 10%, without getting lower than 0. + advance = Math.max(0, advance-(timeInterval/10)); + } + } catch (Exception e) { + access.log(Level.ERROR,e.getMessage()); + } + } + } - private String missKey(String name, byte[] bs) throws IOException { - return name + Hash.toHex(missEncrypt.encode(bs)); - } + private String missKey(String name, byte[] bs) throws IOException { + return name + Hash.toHex(missEncrypt.encode(bs)); + } - protected static class Miss { - private static final int MAX_TRIES = 3; + protected static class Miss { + private static final int MAX_TRIES = 3; - long timestamp; + long timestamp; - private long timetolive; + private long timetolive; - private long tries; + private long tries; - private final String name; - - public Miss(final byte[] first, final long timeInterval, final String name) { - timestamp = System.currentTimeMillis() + timeInterval; - this.timetolive = timeInterval; - tries = 0L; - this.name = name; - } - - - public synchronized boolean mayContinue() { - long ts = System.currentTimeMillis(); - if(ts>timestamp) { - tries = 0; - timestamp = ts + timetolive; - } else if(MAX_TRIES <= ++tries) { - return false; - } - return true; - } - - } - - /** - * Report on state - */ - public String toString() { - return getClass().getSimpleName() + - " Cache:\n Users Cached: " + - userMap.size() + - "\n Misses Saved: " + - missMap.size() + - '\n'; - - } + private final String name; + + public Miss(final byte[] first, final long timeInterval, final String name) { + timestamp = System.currentTimeMillis() + timeInterval; + this.timetolive = timeInterval; + tries = 0L; + this.name = name; + } + + + public synchronized boolean mayContinue() { + long ts = System.currentTimeMillis(); + if(ts>timestamp) { + tries = 0; + timestamp = ts + timetolive; + } else if(MAX_TRIES <= ++tries) { + return false; + } + return true; + } + + } + + /** + * Report on state + */ + public String toString() { + return getClass().getSimpleName() + + " Cache:\n Users Cached: " + + userMap.size() + + "\n Misses Saved: " + + missMap.size() + + '\n'; + + } - public void clear(Principal p, StringBuilder sb) { - sb.append(toString()); - userMap.clear(); - missMap.clear(); - access.log(Level.AUDIT, p.getName(),"has cleared User Cache in",getClass().getSimpleName()); - sb.append("Now cleared\n"); - } + public void clear(Principal p, StringBuilder sb) { + sb.append(toString()); + userMap.clear(); + missMap.clear(); + access.log(Level.AUDIT, p.getName(),"has cleared User Cache in",getClass().getSimpleName()); + sb.append("Now cleared\n"); + } } \ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java index 83127238..76d9bb2a 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java @@ -35,146 +35,146 @@ import java.util.Properties; * */ public interface Access { - // levels to use - public enum Level { - DEBUG(0x1), INFO(0x10), AUDIT(0x100), WARN(0x2000), ERROR(0x4000), INIT(0x8000),TRACE(0x10000),NONE(0XFFFF); - private final int bit; - - Level(int ord) { - bit = ord; - } - - public boolean inMask(int mask) { - return (mask & bit) == bit; - } - - public int addToMask(int mask) { - return mask | bit; - } - - public int delFromMask(int mask) { - return mask & ~bit; - } - - public int toggle(int mask) { - if(inMask(mask)) { - return delFromMask(mask); - } else { - return addToMask(mask); - } - } - - - public int maskOf() { - int mask=0; - for(Level l : values()) { - if(ordinal()<=l.ordinal() && l!=NONE) { - mask|=l.bit; - } - } - return mask; - } - } - - /** - * Write a variable list of Object's text via the toString() method with appropriate space, etc. - * @param elements - */ - public void log(Level level, Object ... elements); - - /** - * Printf mechanism for Access - * @param level - * @param fmt - * @param elements - */ - public void printf(Level level, String fmt, Object ... elements); - - /** - * Check if message will log before constructing - * @param level - * @return - */ - public boolean willLog(Level level); - - /** - * Write the contents of an exception, followed by a variable list of Object's text via the - * toString() method with appropriate space, etc. - * - * The Loglevel is always "ERROR" - * - * @param elements - */ - public void log(Exception e, Object ... elements); - - /** - * Set the Level to compare logging too - */ - public void setLogLevel(Level level); - - /** - * It is important in some cases to create a class from within the same Classloader that created - * Security Objects. Specifically, it's pretty typical for Web Containers to separate classloaders - * so as to allow Apps with different dependencies. - * @return - */ - public ClassLoader classLoader(); - - public String getProperty(String string, String def); - - public Properties getProperties(); - - public void load(InputStream is) throws IOException; - - /** - * if "anytext" is true, then decryption will always be attempted. Otherwise, only if starts with - * Symm.ENC - * @param encrypted - * @param anytext - * @return - * @throws IOException - */ - public String decrypt(String encrypted, boolean anytext) throws IOException; - - public static final Access NULL = new Access() { - public void log(Level level, Object... elements) { - } - - @Override - public void printf(Level level, String fmt, Object... elements) { - } - - public void log(Exception e, Object... elements) { - } - - public ClassLoader classLoader() { - return ClassLoader.getSystemClassLoader(); - } - - public String getProperty(String string, String def) { - return null; - } - - public void load(InputStream is) throws IOException { - } - - public void setLogLevel(Level level) { - } - - public String decrypt(String encrypted, boolean anytext) throws IOException { - return encrypted; - } - - @Override - public boolean willLog(Level level) { - return false; - } - - @Override - public Properties getProperties() { - return new Properties(); - } - }; + // levels to use + public enum Level { + DEBUG(0x1), INFO(0x10), AUDIT(0x100), WARN(0x2000), ERROR(0x4000), INIT(0x8000),TRACE(0x10000),NONE(0XFFFF); + private final int bit; + + Level(int ord) { + bit = ord; + } + + public boolean inMask(int mask) { + return (mask & bit) == bit; + } + + public int addToMask(int mask) { + return mask | bit; + } + + public int delFromMask(int mask) { + return mask & ~bit; + } + + public int toggle(int mask) { + if(inMask(mask)) { + return delFromMask(mask); + } else { + return addToMask(mask); + } + } + + + public int maskOf() { + int mask=0; + for(Level l : values()) { + if(ordinal()<=l.ordinal() && l!=NONE) { + mask|=l.bit; + } + } + return mask; + } + } + + /** + * Write a variable list of Object's text via the toString() method with appropriate space, etc. + * @param elements + */ + public void log(Level level, Object ... elements); + + /** + * Printf mechanism for Access + * @param level + * @param fmt + * @param elements + */ + public void printf(Level level, String fmt, Object ... elements); + + /** + * Check if message will log before constructing + * @param level + * @return + */ + public boolean willLog(Level level); + + /** + * Write the contents of an exception, followed by a variable list of Object's text via the + * toString() method with appropriate space, etc. + * + * The Loglevel is always "ERROR" + * + * @param elements + */ + public void log(Exception e, Object ... elements); + + /** + * Set the Level to compare logging too + */ + public void setLogLevel(Level level); + + /** + * It is important in some cases to create a class from within the same Classloader that created + * Security Objects. Specifically, it's pretty typical for Web Containers to separate classloaders + * so as to allow Apps with different dependencies. + * @return + */ + public ClassLoader classLoader(); + + public String getProperty(String string, String def); + + public Properties getProperties(); + + public void load(InputStream is) throws IOException; + + /** + * if "anytext" is true, then decryption will always be attempted. Otherwise, only if starts with + * Symm.ENC + * @param encrypted + * @param anytext + * @return + * @throws IOException + */ + public String decrypt(String encrypted, boolean anytext) throws IOException; + + public static final Access NULL = new Access() { + public void log(Level level, Object... elements) { + } + + @Override + public void printf(Level level, String fmt, Object... elements) { + } + + public void log(Exception e, Object... elements) { + } + + public ClassLoader classLoader() { + return ClassLoader.getSystemClassLoader(); + } + + public String getProperty(String string, String def) { + return null; + } + + public void load(InputStream is) throws IOException { + } + + public void setLogLevel(Level level) { + } + + public String decrypt(String encrypted, boolean anytext) throws IOException { + return encrypted; + } + + @Override + public boolean willLog(Level level) { + return false; + } + + @Override + public Properties getProperties() { + return new Properties(); + } + }; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/BasicCred.java b/cadi/core/src/main/java/org/onap/aaf/cadi/BasicCred.java index b80cda89..ebb41aba 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/BasicCred.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/BasicCred.java @@ -30,7 +30,7 @@ package org.onap.aaf.cadi; * */ public interface BasicCred extends GetCred { - public void setUser(String user); - public void setCred(byte[] passwd); - public String getUser(); + public void setUser(String user); + public void setCred(byte[] passwd); + public String getUser(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java b/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java index 2df01cda..3f47351b 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java @@ -47,154 +47,154 @@ import javax.servlet.ServletInputStream; * */ public class BufferedServletInputStream extends ServletInputStream { - private static final int NONE = 0; - private static final int STORE = 1; - private static final int READ = 2; - - private InputStream is; - private int state = NONE; - private Capacitor capacitor; - - public BufferedServletInputStream(InputStream is) { - this.is = is; - capacitor = null; - } - - - public int read() throws IOException { - int value=-1; - if(capacitor==null) { - value=is.read(); - } else { - switch(state) { - case STORE: - value = is.read(); - if(value>=0) { - capacitor.put((byte)value); - } - break; - case READ: - value = capacitor.read(); - if(value<0) { - capacitor.done(); - capacitor=null; // all done with buffer - value = is.read(); - } - } - } - return value; - } - - public int read(byte[] b) throws IOException { - return read(b,0,b.length); - } - - - public int read(byte[] b, int off, int len) throws IOException { - int count = -1; - if(capacitor==null) { - count = is.read(b,off,len); - } else { - switch(state) { - case STORE: - count = is.read(b, off, len); - if(count>0) { - capacitor.put(b, off, count); - } - break; - case READ: - count = capacitor.read(b, off, len); - if(count<=0) { - capacitor.done(); - capacitor=null; // all done with buffer - } - if(count0) { // watch for -1 - count+=temp; - } else if(count<=0) { + private static final int NONE = 0; + private static final int STORE = 1; + private static final int READ = 2; + + private InputStream is; + private int state = NONE; + private Capacitor capacitor; + + public BufferedServletInputStream(InputStream is) { + this.is = is; + capacitor = null; + } + + + public int read() throws IOException { + int value=-1; + if(capacitor==null) { + value=is.read(); + } else { + switch(state) { + case STORE: + value = is.read(); + if(value>=0) { + capacitor.put((byte)value); + } + break; + case READ: + value = capacitor.read(); + if(value<0) { + capacitor.done(); + capacitor=null; // all done with buffer + value = is.read(); + } + } + } + return value; + } + + public int read(byte[] b) throws IOException { + return read(b,0,b.length); + } + + + public int read(byte[] b, int off, int len) throws IOException { + int count = -1; + if(capacitor==null) { + count = is.read(b,off,len); + } else { + switch(state) { + case STORE: + count = is.read(b, off, len); + if(count>0) { + capacitor.put(b, off, count); + } + break; + case READ: + count = capacitor.read(b, off, len); + if(count<=0) { + capacitor.done(); + capacitor=null; // all done with buffer + } + if(count0) { // watch for -1 + count+=temp; + } else if(count<=0) { count = temp; // must account for Stream coming back -1 - } - } - break; - } - } - return count; - } - - public long skip(long n) throws IOException { - long skipped = capacitor.skip(n); - if(skipped extends Lur { - public abstract void remove(String user); - public abstract Resp reload(User user); - public abstract void setDebug(String commaDelimIDsOrNull); - public abstract void clear(Principal p, StringBuilder sb); + public abstract void remove(String user); + public abstract Resp reload(User user); + public abstract void setDebug(String commaDelimIDsOrNull); + public abstract void clear(Principal p, StringBuilder sb); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CadiException.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CadiException.java index 0f250b36..96a55f93 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CadiException.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CadiException.java @@ -26,25 +26,25 @@ package org.onap.aaf.cadi; * @author Jonathan */ public class CadiException extends Exception { - /** - * Generated ID - */ - private static final long serialVersionUID = -4180145363107742619L; + /** + * Generated ID + */ + private static final long serialVersionUID = -4180145363107742619L; - public CadiException() { - super(); - } + public CadiException() { + super(); + } - public CadiException(String message) { - super(message); - } + public CadiException(String message) { + super(message); + } - public CadiException(Throwable cause) { - super(cause); - } + public CadiException(Throwable cause) { + super(cause); + } - public CadiException(String message, Throwable cause) { - super(message, cause); - } + public CadiException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java index 6f4d5cc7..647cd8a6 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java @@ -51,150 +51,150 @@ import org.onap.aaf.cadi.util.Timing; * */ public class CadiWrap extends HttpServletRequestWrapper implements HttpServletRequest, BasicCred { - private TaggedPrincipal principal; - private Lur lur; - private String user; // used to set user/pass from brain-dead protocols like WSSE - private byte[] password; - private PermConverter pconv; - private Access access; - - /** - * Standard Wrapper constructor for Delegate pattern - * @param request - */ - public CadiWrap(HttpServletRequest request, TafResp tafResp, Lur lur) { - super(request); - principal = tafResp.getPrincipal(); - access = tafResp.getAccess(); - this.lur = lur; - pconv = NullPermConverter.singleton(); - } - - /** - * Standard Wrapper constructor for Delegate pattern, with PermConverter - * @param request - */ - public CadiWrap(HttpServletRequest request, TafResp tafResp, Lur lur, PermConverter pc) { - super(request); - principal = tafResp.getPrincipal(); - access = tafResp.getAccess(); - this.lur = lur; - pconv = pc; - } - - - /** - * Part of the HTTP Security API. Declare the User associated with this HTTP Transaction. - * CADI does this by reporting the name associated with the Principal obtained, if any. - */ - @Override - public String getRemoteUser() { - return principal==null?null:principal.getName(); - } - - /** - * Part of the HTTP Security API. Return the User Principal associated with this HTTP - * Transaction. - */ - @Override - public Principal getUserPrincipal() { - return principal; - } - - /** - * This is the key API call for AUTHZ in J2EE. Given a Role (String passed in), is the user - * associated with this HTTP Transaction allowed to function in this Role? - * - * For CADI, we pass the responsibility for determining this to the "LUR", which may be - * determined by the Enterprise. - * - * Note: Role check is also done in "CadiRealm" in certain cases... - * - * - */ - @Override - public boolean isUserInRole(String perm) { - return perm==null?false:checkPerm(access,"isUserInRole",principal,pconv,lur,perm); - } - - public static boolean checkPerm(Access access, String caller, Principal principal, PermConverter pconv, Lur lur, String perm) { - if(principal== null) { - access.log(Level.AUDIT,caller, "No Principal in Transaction"); - return false; - } else { - final long start = System.nanoTime(); - perm = pconv.convert(perm); - if(lur.fish(principal,lur.createPerm(perm))) { - access.printf(Level.DEBUG,"%s: %s has %s, %f ms", caller, principal.getName(), perm, Timing.millis(start)); - return true; - } else { - access.printf(Level.DEBUG,"%s: %s does not have %s, %f ms", caller, principal.getName(), perm, Timing.millis(start)); - return false; - } - } - - } - - /** - * CADI Function (Non J2EE standard). GetPermissions will read the Permissions from AAF (if configured) and Roles from Local Lur, etc - * as implemented with lur.fishAll - * - * To utilize, the Request must be a "CadiWrap" object, then call. - */ - public List getPermissions(Principal p) { - List perms = new ArrayList<>(); - lur.fishAll(p, perms); - return perms; - } - /** - * Allow setting of tafResp and lur after construction - * - * This can happen if the CadiWrap is constructed in a Valve other than CadiValve - */ - public void set(TafResp tafResp, Lur lur) { - principal = tafResp.getPrincipal(); - access = tafResp.getAccess(); - this.lur = lur; - } - - public String getUser() { - if(user==null && principal!=null) { - user = principal.getName(); - } - return user; - } - - public byte[] getCred() { - return password; - } - - public void setUser(String user) { - this.user = user; - } - - public void setCred(byte[] passwd) { - password = passwd; - } - - public CadiWrap setPermConverter(PermConverter pc) { - pconv = pc; - return this; - } - - // Add a feature - public void invalidate(String id) { - if(lur instanceof EpiLur) { - ((EpiLur)lur).remove(id); - } else if(lur instanceof CachingLur) { - ((CachingLur)lur).remove(id); - } - } - - public Lur getLur() { - return lur; - } - - public Access access() { - return access; - } + private TaggedPrincipal principal; + private Lur lur; + private String user; // used to set user/pass from brain-dead protocols like WSSE + private byte[] password; + private PermConverter pconv; + private Access access; + + /** + * Standard Wrapper constructor for Delegate pattern + * @param request + */ + public CadiWrap(HttpServletRequest request, TafResp tafResp, Lur lur) { + super(request); + principal = tafResp.getPrincipal(); + access = tafResp.getAccess(); + this.lur = lur; + pconv = NullPermConverter.singleton(); + } + + /** + * Standard Wrapper constructor for Delegate pattern, with PermConverter + * @param request + */ + public CadiWrap(HttpServletRequest request, TafResp tafResp, Lur lur, PermConverter pc) { + super(request); + principal = tafResp.getPrincipal(); + access = tafResp.getAccess(); + this.lur = lur; + pconv = pc; + } + + + /** + * Part of the HTTP Security API. Declare the User associated with this HTTP Transaction. + * CADI does this by reporting the name associated with the Principal obtained, if any. + */ + @Override + public String getRemoteUser() { + return principal==null?null:principal.getName(); + } + + /** + * Part of the HTTP Security API. Return the User Principal associated with this HTTP + * Transaction. + */ + @Override + public Principal getUserPrincipal() { + return principal; + } + + /** + * This is the key API call for AUTHZ in J2EE. Given a Role (String passed in), is the user + * associated with this HTTP Transaction allowed to function in this Role? + * + * For CADI, we pass the responsibility for determining this to the "LUR", which may be + * determined by the Enterprise. + * + * Note: Role check is also done in "CadiRealm" in certain cases... + * + * + */ + @Override + public boolean isUserInRole(String perm) { + return perm==null?false:checkPerm(access,"isUserInRole",principal,pconv,lur,perm); + } + + public static boolean checkPerm(Access access, String caller, Principal principal, PermConverter pconv, Lur lur, String perm) { + if(principal== null) { + access.log(Level.AUDIT,caller, "No Principal in Transaction"); + return false; + } else { + final long start = System.nanoTime(); + perm = pconv.convert(perm); + if(lur.fish(principal,lur.createPerm(perm))) { + access.printf(Level.DEBUG,"%s: %s has %s, %f ms", caller, principal.getName(), perm, Timing.millis(start)); + return true; + } else { + access.printf(Level.DEBUG,"%s: %s does not have %s, %f ms", caller, principal.getName(), perm, Timing.millis(start)); + return false; + } + } + + } + + /** + * CADI Function (Non J2EE standard). GetPermissions will read the Permissions from AAF (if configured) and Roles from Local Lur, etc + * as implemented with lur.fishAll + * + * To utilize, the Request must be a "CadiWrap" object, then call. + */ + public List getPermissions(Principal p) { + List perms = new ArrayList<>(); + lur.fishAll(p, perms); + return perms; + } + /** + * Allow setting of tafResp and lur after construction + * + * This can happen if the CadiWrap is constructed in a Valve other than CadiValve + */ + public void set(TafResp tafResp, Lur lur) { + principal = tafResp.getPrincipal(); + access = tafResp.getAccess(); + this.lur = lur; + } + + public String getUser() { + if(user==null && principal!=null) { + user = principal.getName(); + } + return user; + } + + public byte[] getCred() { + return password; + } + + public void setUser(String user) { + this.user = user; + } + + public void setCred(byte[] passwd) { + password = passwd; + } + + public CadiWrap setPermConverter(PermConverter pc) { + pconv = pc; + return this; + } + + // Add a feature + public void invalidate(String id) { + if(lur instanceof EpiLur) { + ((EpiLur)lur).remove(id); + } else if(lur instanceof CachingLur) { + ((CachingLur)lur).remove(id); + } + } + + public Lur getLur() { + return lur; + } + + public Access access() { + return access; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java index 935e4f14..5ca1ce30 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java @@ -35,207 +35,207 @@ import java.util.ArrayList; * */ public class Capacitor { - private static final int DEFAULT_CHUNK = 256; - private ArrayList bbs = new ArrayList<>(); - private ByteBuffer curr = null; - private int idx; - - // Maintain a private RingBuffer for Memory, for efficiency - private static ByteBuffer[] ring = new ByteBuffer[16]; - private static int start, end; - - - public void put(byte b) { - if(curr == null || curr.remaining()==0) { // ensure we have a "curr" buffer ready for data - curr = ringGet(); - bbs.add(curr); - } - curr.put(b); - } + private static final int DEFAULT_CHUNK = 256; + private ArrayList bbs = new ArrayList<>(); + private ByteBuffer curr = null; + private int idx; + + // Maintain a private RingBuffer for Memory, for efficiency + private static ByteBuffer[] ring = new ByteBuffer[16]; + private static int start, end; + + + public void put(byte b) { + if(curr == null || curr.remaining()==0) { // ensure we have a "curr" buffer ready for data + curr = ringGet(); + bbs.add(curr); + } + curr.put(b); + } - public int read() { - if(curr!=null) { - if(curr.remaining()>0) { // have a buffer, use it! - return curr.get(); - } else if(idx0) { // loop through while there's data needed - if((len=curr.remaining())>length) { // if enough data in curr buffer, use this code - curr.get(array,offset,length); - count+=length; - length=0; - } else { // get data from curr, mark how much is needed to fulfil, and loop for next curr. - curr.get(array,offset,len); - count+=len; - offset+=len; - length-=len; - if(idx0) { // have a buffer, use it! + return curr.get(); + } else if(idx0) { // loop through while there's data needed + if((len=curr.remaining())>length) { // if enough data in curr buffer, use this code + curr.get(array,offset,length); + count+=length; + length=0; + } else { // get data from curr, mark how much is needed to fulfil, and loop for next curr. + curr.get(array,offset,len); + count+=len; + offset+=len; + length-=len; + if(idx0) { - if((len=curr.remaining())>length) { - curr.put(array,offset,length); - length=0; - } else { -// System.out.println(new String(array)); - curr.put(array,offset,len); - length-=len; - offset+=len; - curr = ringGet(); - bbs.add(curr); - } - } - } - - /** - * Move state from Storage mode into Read mode, changing all internal buffers to read mode, etc - */ - public void setForRead() { - for(ByteBuffer bb : bbs) { - bb.flip(); - } - if(bbs.isEmpty()) { - curr = null; - idx = 0; - } else { - curr=bbs.get(0); - idx=1; - } - } - - /** - * reuse all the buffers - */ - public void done() { - for(ByteBuffer bb : bbs) { - ringPut(bb); - } - bbs.clear(); - curr = null; - } - - /** - * Declare amount of data available to be read at once. - * - * @return - */ - public int available() { - int count = 0; - for(ByteBuffer bb : bbs) { - count+=bb.remaining(); - } - return count; - } - - /** - * Returns how many are left that were not skipped - * @param n - * @return - */ - public long skip(long n) { - long skipped=0L; - int skip; - if(curr==null) { - return 0; - } - while(n>0) { - if(n<(skip=curr.remaining())) { - curr.position(curr.position()+(int)n); - skipped+=skip; - n=0; - } else { - curr.position(curr.limit()); - - skipped-=skip; - if(idx 0 ? skipped : 0; - } - /** - * Be able to re-read data that is stored that has already been re-read. This is not a standard Stream behavior, but can be useful - * in a standalone mode. - */ - public void reset() { - for(ByteBuffer bb : bbs) { - bb.position(0); - } - if(bbs.isEmpty()) { - curr = null; - idx = 0; - } else { - curr=bbs.get(0); - idx=1; - } - } + /** + * Put an array of data into Capacitor + * + * @param array + * @param offset + * @param length + */ + public void put(byte[] array, int offset, int length) { + if(curr == null || curr.remaining()==0) { + curr = ringGet(); + bbs.add(curr); + } + + int len; + while(length>0) { + if((len=curr.remaining())>length) { + curr.put(array,offset,length); + length=0; + } else { +// System.out.println(new String(array)); + curr.put(array,offset,len); + length-=len; + offset+=len; + curr = ringGet(); + bbs.add(curr); + } + } + } + + /** + * Move state from Storage mode into Read mode, changing all internal buffers to read mode, etc + */ + public void setForRead() { + for(ByteBuffer bb : bbs) { + bb.flip(); + } + if(bbs.isEmpty()) { + curr = null; + idx = 0; + } else { + curr=bbs.get(0); + idx=1; + } + } + + /** + * reuse all the buffers + */ + public void done() { + for(ByteBuffer bb : bbs) { + ringPut(bb); + } + bbs.clear(); + curr = null; + } + + /** + * Declare amount of data available to be read at once. + * + * @return + */ + public int available() { + int count = 0; + for(ByteBuffer bb : bbs) { + count+=bb.remaining(); + } + return count; + } + + /** + * Returns how many are left that were not skipped + * @param n + * @return + */ + public long skip(long n) { + long skipped=0L; + int skip; + if(curr==null) { + return 0; + } + while(n>0) { + if(n<(skip=curr.remaining())) { + curr.position(curr.position()+(int)n); + skipped+=skip; + n=0; + } else { + curr.position(curr.limit()); + + skipped-=skip; + if(idx 0 ? skipped : 0; + } + /** + * Be able to re-read data that is stored that has already been re-read. This is not a standard Stream behavior, but can be useful + * in a standalone mode. + */ + public void reset() { + for(ByteBuffer bb : bbs) { + bb.position(0); + } + if(bbs.isEmpty()) { + curr = null; + idx = 0; + } else { + curr=bbs.get(0); + idx=1; + } + } - /* - * Ring Functions. Reuse allocated memory - */ - private ByteBuffer ringGet() { - ByteBuffer bb = null; - synchronized(ring) { - bb=ring[start]; - ring[start]=null; - if(bb!=null && ++start>15)start=0; - } - if(bb==null) { - bb=ByteBuffer.allocate(DEFAULT_CHUNK); - } else { - bb.clear();// refresh reused buffer - } - return bb; - } - - private void ringPut(ByteBuffer bb) { - synchronized(ring) { - ring[end]=bb; // if null or not, BB will just be Garbage collected - if(++end>15)end=0; - } - } + /* + * Ring Functions. Reuse allocated memory + */ + private ByteBuffer ringGet() { + ByteBuffer bb = null; + synchronized(ring) { + bb=ring[start]; + ring[start]=null; + if(bb!=null && ++start>15)start=0; + } + if(bb==null) { + bb=ByteBuffer.allocate(DEFAULT_CHUNK); + } else { + bb.clear();// refresh reused buffer + } + return bb; + } + + private void ringPut(ByteBuffer bb) { + synchronized(ring) { + ring[end]=bb; // if null or not, BB will just be Garbage collected + if(++end>15)end=0; + } + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java index 9444cfac..7ca9fac2 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java @@ -43,313 +43,313 @@ import org.onap.aaf.cadi.util.JsonOutputStream; */ public class CmdLine { - private static boolean systemExit = true; - /** - * @param args - */ - public static void main(String[] args) { - if(args.length>0) { - if("digest".equalsIgnoreCase(args[0]) && (args.length>2 || (args.length>1 && System.console()!=null))) { - String keyfile; - String password; - if(args.length>2) { - password = args[1]; - keyfile = args[2]; - if("-i".equals(password)) { - int c; - StringBuilder sb = new StringBuilder(); - try { - while((c=System.in.read())>=0) { - sb.append((char)c); - } - } catch (IOException e) { - e.printStackTrace(); - } - password = sb.toString(); - } - } else { - keyfile = args[1]; - password = new String(System.console().readPassword("Type here (keystrokes hidden): ")); - } + private static boolean systemExit = true; + /** + * @param args + */ + public static void main(String[] args) { + if(args.length>0) { + if("digest".equalsIgnoreCase(args[0]) && (args.length>2 || (args.length>1 && System.console()!=null))) { + String keyfile; + String password; + if(args.length>2) { + password = args[1]; + keyfile = args[2]; + if("-i".equals(password)) { + int c; + StringBuilder sb = new StringBuilder(); + try { + while((c=System.in.read())>=0) { + sb.append((char)c); + } + } catch (IOException e) { + e.printStackTrace(); + } + password = sb.toString(); + } + } else { + keyfile = args[1]; + password = new String(System.console().readPassword("Type here (keystrokes hidden): ")); + } - try { - Symm symm; - FileInputStream fis = new FileInputStream(keyfile); - try { - symm = Symm.obtain(fis); - } finally { - fis.close(); - } - symm.enpass(password, System.out); - System.out.println(); - System.out.flush(); - return; - /* testing code... don't want it exposed - System.out.println(" ******** Testing *********"); - for(int i=0;i<100000;++i) { - System.out.println(args[1]); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - b64.enpass(args[1], baos); - String pass; - System.out.println(pass=new String(baos.toByteArray())); - ByteArrayOutputStream reconstituted = new ByteArrayOutputStream(); - b64.depass(pass, reconstituted); - String r = reconstituted.toString(); - System.out.println(r); - if(!r.equals(args[1])) { - System.err.println("!!!!! STOP - ERROR !!!!!"); - return; - } - System.out.println(); - } - System.out.flush(); - */ - - } catch (IOException e) { - System.err.println("Cannot digest password"); - System.err.println(" \""+ e.getMessage() + '"'); - } + try { + Symm symm; + FileInputStream fis = new FileInputStream(keyfile); + try { + symm = Symm.obtain(fis); + } finally { + fis.close(); + } + symm.enpass(password, System.out); + System.out.println(); + System.out.flush(); + return; + /* testing code... don't want it exposed + System.out.println(" ******** Testing *********"); + for(int i=0;i<100000;++i) { + System.out.println(args[1]); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + b64.enpass(args[1], baos); + String pass; + System.out.println(pass=new String(baos.toByteArray())); + ByteArrayOutputStream reconstituted = new ByteArrayOutputStream(); + b64.depass(pass, reconstituted); + String r = reconstituted.toString(); + System.out.println(r); + if(!r.equals(args[1])) { + System.err.println("!!!!! STOP - ERROR !!!!!"); + return; + } + System.out.println(); + } + System.out.flush(); + */ + + } catch (IOException e) { + System.err.println("Cannot digest password"); + System.err.println(" \""+ e.getMessage() + '"'); + } // DO NOT LEAVE THIS METHOD Compiled IN CODE... Do not want looking at passwords on disk too easy // Jonathan. Oh, well, Deployment services need this behavior. I will put this code in, but leave it undocumented. // One still needs access to the keyfile to read. // July 2016 - thought of a tool "CMPass" to regurgitate from properties, but only if allowed. - } else if("regurgitate".equalsIgnoreCase(args[0]) && args.length>2) { - try { - Symm symm; - FileInputStream fis = new FileInputStream(args[2]); - try { - symm = Symm.obtain(fis); - } finally { - fis.close(); - } - boolean isFile = false; - if("-i".equals(args[1]) || (isFile="-f".equals(args[1]))) { - BufferedReader br; - if(isFile) { - if(args.length<4) { - System.err.println("Filename in 4th position"); - return; - } - br = new BufferedReader(new FileReader(args[3])); - } else { - br = new BufferedReader(new InputStreamReader(System.in)); - } - try { - String line; - boolean cont = false; - StringBuffer sb = new StringBuffer(); - JsonOutputStream jw = new JsonOutputStream(System.out); - while((line=br.readLine())!=null) { - if(cont) { - int end; - if((end=line.indexOf('"'))>=0) { - sb.append(line,0,end); - cont=false; - } else { - sb.append(line); - } - } else { - int idx; - if((idx = line.indexOf(' '))>=0 - && (idx = line.indexOf(' ',++idx))>0 - && (idx = line.indexOf('=',++idx))>0 - ) { - System.out.println(line.substring(0, idx-5)); - int start = idx+2; - int end; - if((end=line.indexOf('"',start))<0) { - end = line.length(); - cont = true; - } - sb.append(line,start,end); - } - } - if(sb.length()>0) { - symm.depass(sb.toString(),jw); - if(!cont) { - System.out.println(); - } - } - System.out.flush(); - sb.setLength(0); - if(!cont) { - jw.resetIndent(); - } - } - } finally { - if(isFile) { - br.close(); - } - } - } else { - symm.depass(args[1], System.out); - } - System.out.println(); - System.out.flush(); - return; - } catch (IOException e) { - System.err.println("Cannot regurgitate password"); - System.err.println(" \""+ e.getMessage() + '"'); - } - } else if("encode64".equalsIgnoreCase(args[0]) && args.length>1) { - try { - Symm.base64.encode(args[1], System.out); - System.out.println(); - System.out.flush(); - return; - } catch (IOException e) { - System.err.println("Cannot encode Base64 with " + args[1]); - System.err.println(" \""+ e.getMessage() + '"'); - } - } else if("decode64".equalsIgnoreCase(args[0]) && args.length>1) { - try { - Symm.base64.decode(args[1], System.out); - System.out.println(); - System.out.flush(); - return; - } catch (IOException e) { - System.err.println("Cannot decode Base64 text from " + args[1]); - System.err.println(" \""+ e.getMessage() + '"'); - } - } else if("encode64url".equalsIgnoreCase(args[0]) && args.length>1) { - try { - Symm.base64url.encode(args[1], System.out); - System.out.println(); - System.out.flush(); - return; - } catch (IOException e) { - System.err.println("Cannot encode Base64url with " + args[1]); - System.err.println(" \""+ e.getMessage() + '"'); - } - } else if("decode64url".equalsIgnoreCase(args[0]) && args.length>1) { - try { - Symm.base64url.decode(args[1], System.out); - System.out.println(); - System.out.flush(); - return; - } catch (IOException e) { - System.err.println("Cannot decode Base64url text from " + args[1]); - System.err.println(" \""+ e.getMessage() + '"'); - } - } else if("md5".equalsIgnoreCase(args[0]) && args.length>1) { - try { - System.out.println(Hash.hashMD5asStringHex(args[1])); - System.out.flush(); - } catch (NoSuchAlgorithmException e) { - System.err.println("Cannot hash MD5 from " + args[1]); - System.err.println(" \""+ e.getMessage() + '"'); - } - return; - } else if("sha256".equalsIgnoreCase(args[0]) && args.length>1) { - try { - if(args.length>2) { - int max = args.length>7?7:args.length; - for(int i=2;i1) { - File f = new File(args[1]); - FileOutputStream fos = new FileOutputStream(f); - try { - fos.write(Symm.keygen()); - fos.flush(); - } finally { - fos.close(); - Chmod.to400.chmod(f); - } - } else { - // create a Symmetric Key out of same characters found in base64 - System.out.write(Symm.keygen()); - System.out.flush(); - } - return; - } catch (IOException e) { - System.err.println("Cannot create a key " + args[0]); - System.err.println(" \""+ e.getMessage() + '"'); - } - - } else if("passgen".equalsIgnoreCase(args[0])) { - int numDigits; - if(args.length <= 1) { - numDigits = 24; - } else { - numDigits = Integer.parseInt(args[1]); - if(numDigits<8)numDigits = 8; - } - String pass; - boolean noLower,noUpper,noDigits,noSpecial,repeatingChars,missingChars; - do { - pass = Symm.randomGen(numDigits); - missingChars=noLower=noUpper=noDigits=noSpecial=true; - repeatingChars=false; - int c=-1,last; - for(int i=0;i=0x61 && c<=0x7A); - } - if(noUpper) { - noUpper=!(c>=0x41 && c<=0x5A); - } - if(noDigits) { - noDigits=!(c>=0x30 && c<=0x39); - } - if(noSpecial) { - noSpecial = "+!@#$%^&*(){}[]?:;,.".indexOf(c)<0; - } - - missingChars = (noLower || noUpper || noDigits || noSpecial); - } - } while(missingChars || repeatingChars); - System.out.println(pass.substring(0,numDigits)); - } else if("urlgen".equalsIgnoreCase(args[0])) { - int numDigits; - if(args.length <= 1) { - numDigits = 24; - } else { - numDigits = Integer.parseInt(args[1]); - } - System.out.println(Symm.randomGen(Symm.base64url.codeset, numDigits).substring(0,numDigits)); - } - } else { - System.out.println("Usage: java -jar ..."); - System.out.println(" keygen [] (Generates Key on file, or Std Out)"); - System.out.println(" digest [|-i|] (Encrypts Password with \"keyfile\""); - System.out.println(" if passwd = -i, will read StdIn"); - System.out.println(" if passwd is blank, will ask securely)"); - System.out.println(" passgen (Generate Password of given size)"); - System.out.println(" urlgen (Generate URL field of given size)"); - System.out.println(" encode64 (Encodes to Base64)"); - System.out.println(" decode64 (Decodes from Base64)"); - System.out.println(" encode64url (Encodes to Base64 URL charset)"); - System.out.println(" decode64url (Decodes from Base64 URL charset)"); - System.out.println(" sha256 (Digest String into SHA256 Hash)"); - System.out.println(" md5 (Digest String into MD5 Hash)"); - } - if (systemExit) { - System.exit(1); - } - } - - public static void setSystemExit(boolean shouldExit) { - systemExit = shouldExit; - } - + } else if("regurgitate".equalsIgnoreCase(args[0]) && args.length>2) { + try { + Symm symm; + FileInputStream fis = new FileInputStream(args[2]); + try { + symm = Symm.obtain(fis); + } finally { + fis.close(); + } + boolean isFile = false; + if("-i".equals(args[1]) || (isFile="-f".equals(args[1]))) { + BufferedReader br; + if(isFile) { + if(args.length<4) { + System.err.println("Filename in 4th position"); + return; + } + br = new BufferedReader(new FileReader(args[3])); + } else { + br = new BufferedReader(new InputStreamReader(System.in)); + } + try { + String line; + boolean cont = false; + StringBuffer sb = new StringBuffer(); + JsonOutputStream jw = new JsonOutputStream(System.out); + while((line=br.readLine())!=null) { + if(cont) { + int end; + if((end=line.indexOf('"'))>=0) { + sb.append(line,0,end); + cont=false; + } else { + sb.append(line); + } + } else { + int idx; + if((idx = line.indexOf(' '))>=0 + && (idx = line.indexOf(' ',++idx))>0 + && (idx = line.indexOf('=',++idx))>0 + ) { + System.out.println(line.substring(0, idx-5)); + int start = idx+2; + int end; + if((end=line.indexOf('"',start))<0) { + end = line.length(); + cont = true; + } + sb.append(line,start,end); + } + } + if(sb.length()>0) { + symm.depass(sb.toString(),jw); + if(!cont) { + System.out.println(); + } + } + System.out.flush(); + sb.setLength(0); + if(!cont) { + jw.resetIndent(); + } + } + } finally { + if(isFile) { + br.close(); + } + } + } else { + symm.depass(args[1], System.out); + } + System.out.println(); + System.out.flush(); + return; + } catch (IOException e) { + System.err.println("Cannot regurgitate password"); + System.err.println(" \""+ e.getMessage() + '"'); + } + } else if("encode64".equalsIgnoreCase(args[0]) && args.length>1) { + try { + Symm.base64.encode(args[1], System.out); + System.out.println(); + System.out.flush(); + return; + } catch (IOException e) { + System.err.println("Cannot encode Base64 with " + args[1]); + System.err.println(" \""+ e.getMessage() + '"'); + } + } else if("decode64".equalsIgnoreCase(args[0]) && args.length>1) { + try { + Symm.base64.decode(args[1], System.out); + System.out.println(); + System.out.flush(); + return; + } catch (IOException e) { + System.err.println("Cannot decode Base64 text from " + args[1]); + System.err.println(" \""+ e.getMessage() + '"'); + } + } else if("encode64url".equalsIgnoreCase(args[0]) && args.length>1) { + try { + Symm.base64url.encode(args[1], System.out); + System.out.println(); + System.out.flush(); + return; + } catch (IOException e) { + System.err.println("Cannot encode Base64url with " + args[1]); + System.err.println(" \""+ e.getMessage() + '"'); + } + } else if("decode64url".equalsIgnoreCase(args[0]) && args.length>1) { + try { + Symm.base64url.decode(args[1], System.out); + System.out.println(); + System.out.flush(); + return; + } catch (IOException e) { + System.err.println("Cannot decode Base64url text from " + args[1]); + System.err.println(" \""+ e.getMessage() + '"'); + } + } else if("md5".equalsIgnoreCase(args[0]) && args.length>1) { + try { + System.out.println(Hash.hashMD5asStringHex(args[1])); + System.out.flush(); + } catch (NoSuchAlgorithmException e) { + System.err.println("Cannot hash MD5 from " + args[1]); + System.err.println(" \""+ e.getMessage() + '"'); + } + return; + } else if("sha256".equalsIgnoreCase(args[0]) && args.length>1) { + try { + if(args.length>2) { + int max = args.length>7?7:args.length; + for(int i=2;i1) { + File f = new File(args[1]); + FileOutputStream fos = new FileOutputStream(f); + try { + fos.write(Symm.keygen()); + fos.flush(); + } finally { + fos.close(); + Chmod.to400.chmod(f); + } + } else { + // create a Symmetric Key out of same characters found in base64 + System.out.write(Symm.keygen()); + System.out.flush(); + } + return; + } catch (IOException e) { + System.err.println("Cannot create a key " + args[0]); + System.err.println(" \""+ e.getMessage() + '"'); + } + + } else if("passgen".equalsIgnoreCase(args[0])) { + int numDigits; + if(args.length <= 1) { + numDigits = 24; + } else { + numDigits = Integer.parseInt(args[1]); + if(numDigits<8)numDigits = 8; + } + String pass; + boolean noLower,noUpper,noDigits,noSpecial,repeatingChars,missingChars; + do { + pass = Symm.randomGen(numDigits); + missingChars=noLower=noUpper=noDigits=noSpecial=true; + repeatingChars=false; + int c=-1,last; + for(int i=0;i=0x61 && c<=0x7A); + } + if(noUpper) { + noUpper=!(c>=0x41 && c<=0x5A); + } + if(noDigits) { + noDigits=!(c>=0x30 && c<=0x39); + } + if(noSpecial) { + noSpecial = "+!@#$%^&*(){}[]?:;,.".indexOf(c)<0; + } + + missingChars = (noLower || noUpper || noDigits || noSpecial); + } + } while(missingChars || repeatingChars); + System.out.println(pass.substring(0,numDigits)); + } else if("urlgen".equalsIgnoreCase(args[0])) { + int numDigits; + if(args.length <= 1) { + numDigits = 24; + } else { + numDigits = Integer.parseInt(args[1]); + } + System.out.println(Symm.randomGen(Symm.base64url.codeset, numDigits).substring(0,numDigits)); + } + } else { + System.out.println("Usage: java -jar ..."); + System.out.println(" keygen [] (Generates Key on file, or Std Out)"); + System.out.println(" digest [|-i|] (Encrypts Password with \"keyfile\""); + System.out.println(" if passwd = -i, will read StdIn"); + System.out.println(" if passwd is blank, will ask securely)"); + System.out.println(" passgen (Generate Password of given size)"); + System.out.println(" urlgen (Generate URL field of given size)"); + System.out.println(" encode64 (Encodes to Base64)"); + System.out.println(" decode64 (Decodes from Base64)"); + System.out.println(" encode64url (Encodes to Base64 URL charset)"); + System.out.println(" decode64url (Decodes from Base64 URL charset)"); + System.out.println(" sha256 (Digest String into SHA256 Hash)"); + System.out.println(" md5 (Digest String into MD5 Hash)"); + } + if (systemExit) { + System.exit(1); + } + } + + public static void setSystemExit(boolean shouldExit) { + systemExit = shouldExit; + } + } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Connector.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Connector.java index 7f47ce78..f88c3fbe 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Connector.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Connector.java @@ -22,5 +22,5 @@ package org.onap.aaf.cadi; public interface Connector { - public Lur newLur() throws CadiException; + public Lur newLur() throws CadiException; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CredVal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CredVal.java index 4e42a5fb..6019f551 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CredVal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CredVal.java @@ -31,12 +31,12 @@ package org.onap.aaf.cadi; * @author Jonathan */ public interface CredVal { - public enum Type{PASSWORD}; - /** - * Validate if the User/Password combination matches records - * @param user - * @param pass - * @return - */ - public boolean validate(String user, Type type, byte[] cred, Object state); + public enum Type{PASSWORD}; + /** + * Validate if the User/Password combination matches records + * @param user + * @param pass + * @return + */ + public boolean validate(String user, Type type, byte[] cred, Object state); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CredValDomain.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CredValDomain.java index e8a5c54b..db5ab0f2 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CredValDomain.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CredValDomain.java @@ -21,5 +21,5 @@ package org.onap.aaf.cadi; public interface CredValDomain extends CredVal { - public String domain(); + public String domain(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/GetCred.java b/cadi/core/src/main/java/org/onap/aaf/cadi/GetCred.java index e64f0dd4..039ba8f7 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/GetCred.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/GetCred.java @@ -22,5 +22,5 @@ package org.onap.aaf.cadi; public interface GetCred { - byte[] getCred(); + byte[] getCred(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java index 6babb4c9..acd45019 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java @@ -26,233 +26,233 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Hash { - private static char hexDigit[] = "0123456789abcdef".toCharArray(); - + private static char hexDigit[] = "0123456789abcdef".toCharArray(); + ///////////////////////////////// // MD5 ///////////////////////////////// - /** - * Encrypt MD5 from Byte Array to Byte Array - * @param input - * @return - * @throws NoSuchAlgorithmException - */ - public static byte[] hashMD5 (byte[] input) throws NoSuchAlgorithmException { - // Note: Protect against Multi-thread issues with new MessageDigest - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(input); - return md.digest(); - } + /** + * Encrypt MD5 from Byte Array to Byte Array + * @param input + * @return + * @throws NoSuchAlgorithmException + */ + public static byte[] hashMD5 (byte[] input) throws NoSuchAlgorithmException { + // Note: Protect against Multi-thread issues with new MessageDigest + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(input); + return md.digest(); + } - /** - * Encrypt MD5 from Byte Array to Byte Array - * @param input - * @return - * @throws NoSuchAlgorithmException - */ - public static byte[] hashMD5 (byte[] input, int offset, int length) throws NoSuchAlgorithmException { - // Note: Protect against Multi-thread issues with new MessageDigest - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(input,offset,length); - return md.digest(); - } + /** + * Encrypt MD5 from Byte Array to Byte Array + * @param input + * @return + * @throws NoSuchAlgorithmException + */ + public static byte[] hashMD5 (byte[] input, int offset, int length) throws NoSuchAlgorithmException { + // Note: Protect against Multi-thread issues with new MessageDigest + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(input,offset,length); + return md.digest(); + } - /** - * Convenience Function: Encrypt MD5 from String to String Hex representation - * - * @param input - * @return - * @throws NoSuchAlgorithmException - */ - public static String hashMD5asStringHex(String input) throws NoSuchAlgorithmException { - byte[] output = hashMD5(input.getBytes()); - StringBuilder sb = new StringBuilder("0x"); - for (byte b : output) { - sb.append(hexDigit[(b >> 4) & 0x0f]); - sb.append(hexDigit[b & 0x0f]); - } - return sb.toString(); - } + /** + * Convenience Function: Encrypt MD5 from String to String Hex representation + * + * @param input + * @return + * @throws NoSuchAlgorithmException + */ + public static String hashMD5asStringHex(String input) throws NoSuchAlgorithmException { + byte[] output = hashMD5(input.getBytes()); + StringBuilder sb = new StringBuilder("0x"); + for (byte b : output) { + sb.append(hexDigit[(b >> 4) & 0x0f]); + sb.append(hexDigit[b & 0x0f]); + } + return sb.toString(); + } ///////////////////////////////// // SHA256 ///////////////////////////////// - /** - * SHA256 Hashing - */ - public static byte[] hashSHA256(byte[] input) throws NoSuchAlgorithmException { - // Note: Protect against Multi-thread issues with new MessageDigest - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(input); - return md.digest(); - } + /** + * SHA256 Hashing + */ + public static byte[] hashSHA256(byte[] input) throws NoSuchAlgorithmException { + // Note: Protect against Multi-thread issues with new MessageDigest + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(input); + return md.digest(); + } - /** - * SHA256 Hashing - */ - public static byte[] hashSHA256(byte[] input, int offset, int length) throws NoSuchAlgorithmException { - // Note: Protect against Multi-thread issues with new MessageDigest - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(input,offset,length); - return md.digest(); - } - - /** - * Convenience Function: Hash from String to String Hex representation - * - * @param input - * @return - * @throws NoSuchAlgorithmException - */ - public static String hashSHA256asStringHex(String input) throws NoSuchAlgorithmException { - return toHex(hashSHA256(input.getBytes())); - } + /** + * SHA256 Hashing + */ + public static byte[] hashSHA256(byte[] input, int offset, int length) throws NoSuchAlgorithmException { + // Note: Protect against Multi-thread issues with new MessageDigest + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(input,offset,length); + return md.digest(); + } + + /** + * Convenience Function: Hash from String to String Hex representation + * + * @param input + * @return + * @throws NoSuchAlgorithmException + */ + public static String hashSHA256asStringHex(String input) throws NoSuchAlgorithmException { + return toHex(hashSHA256(input.getBytes())); + } - /** - * Convenience Function: Hash from String to String Hex representation - * - * @param input - * @return - * @throws NoSuchAlgorithmException - */ - public static String hashSHA256asStringHex(String input, int salt) throws NoSuchAlgorithmException { - byte[] in = input.getBytes(); - ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + in.length); - bb.putInt(salt); - bb.put(input.getBytes()); - return toHex(Hash.hashSHA256(bb.array())); - } - - /** - * Compare two byte arrays for equivalency - * @param ba1 - * @param ba2 - * @return - */ - public static boolean isEqual(byte ba1[], byte ba2[]) { - if(ba1.length!=ba2.length)return false; - for(int i = 0;i> 4) & 0x0f]); - sb.append(hexDigit[b & 0x0f]); - } - return sb.toString(); - } + public static String toHexNo0x(byte[] ba) { + StringBuilder sb = new StringBuilder(); + for (byte b : ba) { + sb.append(hexDigit[(b >> 4) & 0x0f]); + sb.append(hexDigit[b & 0x0f]); + } + return sb.toString(); + } - public static String toHex(byte[] ba) { - StringBuilder sb = new StringBuilder("0x"); - for (byte b : ba) { - sb.append(hexDigit[(b >> 4) & 0x0f]); - sb.append(hexDigit[b & 0x0f]); - } - return sb.toString(); - } - - public static String toHex(byte[] ba, int start, int length) { - StringBuilder sb = new StringBuilder("0x"); - for (int i=start;i> 4) & 0x0f]); - sb.append(hexDigit[ba[i] & 0x0f]); - } - return sb.toString(); - } + public static String toHex(byte[] ba) { + StringBuilder sb = new StringBuilder("0x"); + for (byte b : ba) { + sb.append(hexDigit[(b >> 4) & 0x0f]); + sb.append(hexDigit[b & 0x0f]); + } + return sb.toString(); + } + + public static String toHex(byte[] ba, int start, int length) { + StringBuilder sb = new StringBuilder("0x"); + for (int i=start;i> 4) & 0x0f]); + sb.append(hexDigit[ba[i] & 0x0f]); + } + return sb.toString(); + } - - public static byte[] fromHex(String s) throws CadiException{ - if(!s.startsWith("0x")) { - throw new CadiException("HexString must start with \"0x\""); - } - boolean high = true; - int c; - byte b; - byte[] ba = new byte[(s.length()-2)/2]; - int idx; - for(int i=2;i=0x30 && c<=0x39) { - b=(byte)(c-0x30); - } else if(c>=0x61 && c<=0x66) { - b=(byte)(c-0x57); // account for "A" - } else if(c>=0x41 && c<=0x46) { - b=(byte)(c-0x37); - } else { - throw new CadiException("Invalid char '" + c + "' in HexString"); - } - idx = (i-2)/2; - if(high) { - ba[idx]=(byte)(b<<4); - high = false; - } else { - ba[idx]|=b; - high = true; - } - } - return ba; - } + + public static byte[] fromHex(String s) throws CadiException{ + if(!s.startsWith("0x")) { + throw new CadiException("HexString must start with \"0x\""); + } + boolean high = true; + int c; + byte b; + byte[] ba = new byte[(s.length()-2)/2]; + int idx; + for(int i=2;i=0x30 && c<=0x39) { + b=(byte)(c-0x30); + } else if(c>=0x61 && c<=0x66) { + b=(byte)(c-0x57); // account for "A" + } else if(c>=0x41 && c<=0x46) { + b=(byte)(c-0x37); + } else { + throw new CadiException("Invalid char '" + c + "' in HexString"); + } + idx = (i-2)/2; + if(high) { + ba[idx]=(byte)(b<<4); + high = false; + } else { + ba[idx]|=b; + high = true; + } + } + return ba; + } - /** - * Does not expect to start with "0x" - * if Any Character doesn't match, it returns null; - * - * @param s - * @return - */ - public static byte[] fromHexNo0x(String s) { - int c; - byte b; - byte[] ba; - boolean high; - int start; - if(s.length()%2==0) { - ba = new byte[s.length()/2]; - high=true; - start=0; - } else { - ba = new byte[(s.length()/2)+1]; - high = false; - start=1; - } - int idx; - for(int i=start;i=0x30 && c<=0x39) { - b=(byte)(c-0x30); - } else if(c>=0x61 && c<=0x66) { - b=(byte)(c-0x57); // account for "A" - } else if(c>=0x41 && c<=0x46) { - b=(byte)(c-0x37); - } else { - return null; - } - idx = i/2; - if(high) { - ba[idx]=(byte)(b<<4); - high = false; - } else { - ba[idx]|=b; - high = true; - } - } - return ba; - } + /** + * Does not expect to start with "0x" + * if Any Character doesn't match, it returns null; + * + * @param s + * @return + */ + public static byte[] fromHexNo0x(String s) { + int c; + byte b; + byte[] ba; + boolean high; + int start; + if(s.length()%2==0) { + ba = new byte[s.length()/2]; + high=true; + start=0; + } else { + ba = new byte[(s.length()/2)+1]; + high = false; + start=1; + } + int idx; + for(int i=start;i=0x30 && c<=0x39) { + b=(byte)(c-0x30); + } else if(c>=0x61 && c<=0x66) { + b=(byte)(c-0x57); // account for "A" + } else if(c>=0x41 && c<=0x46) { + b=(byte)(c-0x37); + } else { + return null; + } + idx = i/2; + if(high) { + ba[idx]=(byte)(b<<4); + high = false; + } else { + ba[idx]|=b; + high = true; + } + } + return ba; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Locator.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Locator.java index 22258d12..c40cb998 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Locator.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Locator.java @@ -22,15 +22,15 @@ package org.onap.aaf.cadi; public interface Locator { - public T get(Locator.Item item) throws LocatorException; - public boolean hasItems(); - public void invalidate(Locator.Item item) throws LocatorException; - public Locator.Item best() throws LocatorException; - public Item first() throws LocatorException; - public Item next(Item item) throws LocatorException; - public boolean refresh(); - public void destroy(); - - public interface Item {} + public T get(Locator.Item item) throws LocatorException; + public boolean hasItems(); + public void invalidate(Locator.Item item) throws LocatorException; + public Locator.Item best() throws LocatorException; + public Item first() throws LocatorException; + public Item next(Item item) throws LocatorException; + public boolean refresh(); + public void destroy(); + + public interface Item {} } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/LocatorException.java b/cadi/core/src/main/java/org/onap/aaf/cadi/LocatorException.java index f14fba70..da56d4b2 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/LocatorException.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/LocatorException.java @@ -22,25 +22,25 @@ package org.onap.aaf.cadi; public class LocatorException extends Exception { - /** - * - */ - private static final long serialVersionUID = -4267929804321134469L; + /** + * + */ + private static final long serialVersionUID = -4267929804321134469L; - public LocatorException(String arg0) { - super(arg0); - } + public LocatorException(String arg0) { + super(arg0); + } - public LocatorException(Throwable arg0) { - super(arg0); - } + public LocatorException(Throwable arg0) { + super(arg0); + } - public LocatorException(String arg0, Throwable arg1) { - super(arg0, arg1); - } + public LocatorException(String arg0, Throwable arg1) { + super(arg0, arg1); + } - public LocatorException(CharSequence cs) { - super(cs.toString()); - } + public LocatorException(CharSequence cs) { + super(cs.toString()); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Lur.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Lur.java index 0beb4856..bdc9f643 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Lur.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Lur.java @@ -39,54 +39,54 @@ import java.util.List; * */ public interface Lur { - /** - * Allow the Lur, which has correct Permission access, to create and hand back. - */ - public Permission createPerm(String p); - - /** - * Fish for Principals in a Pond - * - * or more boringly, is the User identified within a named collection representing permission. - * - * @param principalName - * @return - */ - public boolean fish(Principal bait, Permission ... pond); + /** + * Allow the Lur, which has correct Permission access, to create and hand back. + */ + public Permission createPerm(String p); + + /** + * Fish for Principals in a Pond + * + * or more boringly, is the User identified within a named collection representing permission. + * + * @param principalName + * @return + */ + public boolean fish(Principal bait, Permission ... pond); - /** - * Fish all the Principals out a Pond - * - * For additional humor, pronounce the following with a Southern Drawl, "FishOil" - * - * or more boringly, load the List with Permissions found for Principal - * - * @param principalName - * @return - */ - public void fishAll(Principal bait, List permissions); + /** + * Fish all the Principals out a Pond + * + * For additional humor, pronounce the following with a Southern Drawl, "FishOil" + * + * or more boringly, load the List with Permissions found for Principal + * + * @param principalName + * @return + */ + public void fishAll(Principal bait, List permissions); - /** - * Allow implementations to disconnect, or cleanup resources if unneeded - */ - public void destroy(); + /** + * Allow implementations to disconnect, or cleanup resources if unneeded + */ + public void destroy(); - /** - * Does this LUR handle this pond exclusively? Important for EpiLUR to determine whether - * to try another (more expensive) LUR - * @param pond - * @return - */ - public boolean handlesExclusively(Permission ... pond); - - /** - * Does the LUR support a particular kind of Principal - * This can be used to check name's domain, like above, or Principal type - */ - public boolean handles(Principal principal); - - /** - * Clear: Clear any Caching, if exists - */ - public void clear(Principal p, StringBuilder report); + /** + * Does this LUR handle this pond exclusively? Important for EpiLUR to determine whether + * to try another (more expensive) LUR + * @param pond + * @return + */ + public boolean handlesExclusively(Permission ... pond); + + /** + * Does the LUR support a particular kind of Principal + * This can be used to check name's domain, like above, or Principal type + */ + public boolean handles(Principal principal); + + /** + * Clear: Clear any Caching, if exists + */ + public void clear(Principal p, StringBuilder report); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Permission.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Permission.java index f8061290..2537c386 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Permission.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Permission.java @@ -22,7 +22,7 @@ package org.onap.aaf.cadi; public interface Permission { - public String permType(); - public String getKey(); - public boolean match(Permission p); + public String permType(); + public String getKey(); + public boolean match(Permission p); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java b/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java index 3d15b09d..a35777f8 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java @@ -37,365 +37,365 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.config.SecurityInfo; public class PropAccess implements Access { - // Sonar says cannot be static... it's ok. not too many PropAccesses created. - private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + // Sonar says cannot be static... it's ok. not too many PropAccesses created. + private final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - public static final Level DEFAULT = Level.AUDIT; - - private Symm symm; - private int level; - private Properties props; - private List recursionProtection = null; - private LogIt logIt; - private String name; + public static final Level DEFAULT = Level.AUDIT; + + private Symm symm; + private int level; + private Properties props; + private List recursionProtection = null; + private LogIt logIt; + private String name; - public PropAccess() { - logIt = new StreamLogIt(System.out); - init(null); - } - - /** - * This Constructor soly exists to instantiate Servlet Context Based Logging that will call "init" later. - * @param sc - */ - protected PropAccess(Object o) { - logIt = new StreamLogIt(System.out); - props = new Properties(); - } - - public PropAccess(String ... args) { - this(System.out,args); - } - - public PropAccess(PrintStream ps, String[] args) { - logIt = new StreamLogIt(ps==null?System.out:ps); - init(logIt,args); - } - - public PropAccess(LogIt logit, String[] args) { - init(logit, args); - } - - public PropAccess(Properties p) { - this(System.out,p); - } - - public PropAccess(PrintStream ps, Properties p) { - logIt = new StreamLogIt(ps==null?System.out:ps); - init(p); - } - - protected void init(final LogIt logIt, final String[] args) { - this.logIt = logIt; - Properties nprops=new Properties(); - int eq; - for(String arg : args) { - if((eq=arg.indexOf('='))>0) { - nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1)); - } - } - init(nprops); - } - - protected void init(Properties p) { - // Make sure these two are set before any changes in Logging - name = "cadi"; - level=DEFAULT.maskOf(); - - props = new Properties(); - // First, load related System Properties - for(Entry es : System.getProperties().entrySet()) { - String key = es.getKey().toString(); - for(String start : new String[] {"cadi_","aaf_","cm_"}) { - if(key.startsWith(start)) { - props.put(key, es.getValue()); - } - } - } - // Second, overlay or fill in with Passed in Props - if(p!=null) { - props.putAll(p); - } - - // Third, load any Chained Property Files - load(props.getProperty(Config.CADI_PROP_FILES)); - - String sLevel = props.getProperty(Config.CADI_LOGLEVEL); - if(sLevel!=null) { - level=Level.valueOf(sLevel).maskOf(); - } - // Setup local Symmetrical key encryption - if(symm==null) { - try { - symm = Symm.obtain(this); - } catch (CadiException e) { - System.err.append("FATAL ERROR: Cannot obtain Key Information."); - e.printStackTrace(System.err); - System.exit(1); - } - } - - name = props.getProperty(Config.CADI_LOGNAME, name); - - specialConversions(); - } + public PropAccess() { + logIt = new StreamLogIt(System.out); + init(null); + } + + /** + * This Constructor soly exists to instantiate Servlet Context Based Logging that will call "init" later. + * @param sc + */ + protected PropAccess(Object o) { + logIt = new StreamLogIt(System.out); + props = new Properties(); + } + + public PropAccess(String ... args) { + this(System.out,args); + } + + public PropAccess(PrintStream ps, String[] args) { + logIt = new StreamLogIt(ps==null?System.out:ps); + init(logIt,args); + } + + public PropAccess(LogIt logit, String[] args) { + init(logit, args); + } + + public PropAccess(Properties p) { + this(System.out,p); + } + + public PropAccess(PrintStream ps, Properties p) { + logIt = new StreamLogIt(ps==null?System.out:ps); + init(p); + } + + protected void init(final LogIt logIt, final String[] args) { + this.logIt = logIt; + Properties nprops=new Properties(); + int eq; + for(String arg : args) { + if((eq=arg.indexOf('='))>0) { + nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1)); + } + } + init(nprops); + } + + protected void init(Properties p) { + // Make sure these two are set before any changes in Logging + name = "cadi"; + level=DEFAULT.maskOf(); + + props = new Properties(); + // First, load related System Properties + for(Entry es : System.getProperties().entrySet()) { + String key = es.getKey().toString(); + for(String start : new String[] {"cadi_","aaf_","cm_"}) { + if(key.startsWith(start)) { + props.put(key, es.getValue()); + } + } + } + // Second, overlay or fill in with Passed in Props + if(p!=null) { + props.putAll(p); + } + + // Third, load any Chained Property Files + load(props.getProperty(Config.CADI_PROP_FILES)); + + String sLevel = props.getProperty(Config.CADI_LOGLEVEL); + if(sLevel!=null) { + level=Level.valueOf(sLevel).maskOf(); + } + // Setup local Symmetrical key encryption + if(symm==null) { + try { + symm = Symm.obtain(this); + } catch (CadiException e) { + System.err.append("FATAL ERROR: Cannot obtain Key Information."); + e.printStackTrace(System.err); + System.exit(1); + } + } + + name = props.getProperty(Config.CADI_LOGNAME, name); + + specialConversions(); + } - private void specialConversions() { - // Critical - if no Security Protocols set, then set it. We'll just get messed up if not - if(props.get(Config.CADI_PROTOCOLS)==null) { - props.setProperty(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT); - } - - Object temp; - temp=props.get(Config.CADI_PROTOCOLS); - if(props.get(Config.HTTPS_PROTOCOLS)==null && temp!=null) { - props.put(Config.HTTPS_PROTOCOLS, temp); - } - - if(temp!=null) { - if("1.7".equals(System.getProperty("java.specification.version")) - && (temp==null || (temp instanceof String && ((String)temp).contains("TLSv1.2")))) { - System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); - } - } - } + private void specialConversions() { + // Critical - if no Security Protocols set, then set it. We'll just get messed up if not + if(props.get(Config.CADI_PROTOCOLS)==null) { + props.setProperty(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT); + } + + Object temp; + temp=props.get(Config.CADI_PROTOCOLS); + if(props.get(Config.HTTPS_PROTOCOLS)==null && temp!=null) { + props.put(Config.HTTPS_PROTOCOLS, temp); + } + + if(temp!=null) { + if("1.7".equals(System.getProperty("java.specification.version")) + && (temp==null || (temp instanceof String && ((String)temp).contains("TLSv1.2")))) { + System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); + } + } + } - private void load(String cadi_prop_files) { - if(cadi_prop_files==null) { - return; - } - String prevKeyFile = props.getProperty(Config.CADI_KEYFILE); - int prev = 0, end = cadi_prop_files.length(); - int idx; - String filename; - while(prev(); - recursionProtection.add(cadi_prop_files); - } - if(!recursionProtection.contains(chainProp)) { - recursionProtection.add(chainProp); - load(chainProp); // recurse - } - } - } finally { - fis.close(); - } - } catch (Exception e) { - log(e,filename,"cannot be opened"); - } - } else { - printf(Level.WARN,"Warning: recursive CADI Property %s does not exist",file.getAbsolutePath()); - } - prev = idx+1; - } - - // Trim - for(Entry es : props.entrySet()) { - Object value = es.getValue(); - if(value instanceof String) { - String trim = ((String)value).trim(); - // Remove Beginning/End Quotes, which might be there if mixed with Bash Props - int s = 0, e=trim.length()-1; - if(s(); + recursionProtection.add(cadi_prop_files); + } + if(!recursionProtection.contains(chainProp)) { + recursionProtection.add(chainProp); + load(chainProp); // recurse + } + } + } finally { + fis.close(); + } + } catch (Exception e) { + log(e,filename,"cannot be opened"); + } + } else { + printf(Level.WARN,"Warning: recursive CADI Property %s does not exist",file.getAbsolutePath()); + } + prev = idx+1; + } + + // Trim + for(Entry es : props.entrySet()) { + Object value = es.getValue(); + if(value instanceof String) { + String trim = ((String)value).trim(); + // Remove Beginning/End Quotes, which might be there if mixed with Bash Props + int s = 0, e=trim.length()-1; + if(s0) { - switch(s.charAt(l-1)) { - case ' ': - break; - default: - sb.append(' '); - } - } - } - sb.append(s); - } - } - } - return sb; - } + public static StringBuilder buildMsg(final String name, final SimpleDateFormat sdf, Level level, Object[] elements) { + StringBuilder sb = new StringBuilder(sdf.format(new Date())); + sb.append(' '); + sb.append(level.name()); + sb.append(" ["); + sb.append(name); + + int end = elements.length; + if(end<=0) { + sb.append("] "); + } else { + int idx = 0; + if(elements[idx] instanceof Integer) { + sb.append('-'); + sb.append(elements[idx]); + ++idx; + } + sb.append("] "); + String s; + boolean first = true; + for(Object o : elements) { + if(o!=null) { + s=o.toString(); + if(first) { + first = false; + } else { + int l = s.length(); + if(l>0) { + switch(s.charAt(l-1)) { + case ' ': + break; + default: + sb.append(' '); + } + } + } + sb.append(s); + } + } + } + return sb; + } - @Override - public void log(Exception e, Object... elements) { - log(Level.ERROR,e.getMessage(),elements); - e.printStackTrace(System.err); - } + @Override + public void log(Exception e, Object... elements) { + log(Level.ERROR,e.getMessage(),elements); + e.printStackTrace(System.err); + } - @Override - public void printf(Level level, String fmt, Object... elements) { - if(willLog(level)) { - log(level,String.format(fmt, elements)); - } - } + @Override + public void printf(Level level, String fmt, Object... elements) { + if(willLog(level)) { + log(level,String.format(fmt, elements)); + } + } - @Override - public void setLogLevel(Level level) { - this.level = level.maskOf(); - } + @Override + public void setLogLevel(Level level) { + this.level = level.maskOf(); + } - @Override - public boolean willLog(Level level) { - return level.inMask(this.level); - } + @Override + public boolean willLog(Level level) { + return level.inMask(this.level); + } - @Override - public ClassLoader classLoader() { - return ClassLoader.getSystemClassLoader(); - } + @Override + public ClassLoader classLoader() { + return ClassLoader.getSystemClassLoader(); + } - @Override - public String getProperty(String tag, String def) { - return props.getProperty(tag,def); - } + @Override + public String getProperty(String tag, String def) { + return props.getProperty(tag,def); + } - @Override - public String decrypt(String encrypted, boolean anytext) throws IOException { - return (encrypted!=null && (anytext==true || encrypted.startsWith(Symm.ENC))) - ? symm.depass(encrypted) - : encrypted; - } - - public String encrypt(String unencrypted) throws IOException { - return Symm.ENC+symm.enpass(unencrypted); - } + @Override + public String decrypt(String encrypted, boolean anytext) throws IOException { + return (encrypted!=null && (anytext==true || encrypted.startsWith(Symm.ENC))) + ? symm.depass(encrypted) + : encrypted; + } + + public String encrypt(String unencrypted) throws IOException { + return Symm.ENC+symm.enpass(unencrypted); + } - ////////////////// - // Additional - ////////////////// - public String getProperty(String tag) { - return props.getProperty(tag); - } - + ////////////////// + // Additional + ////////////////// + public String getProperty(String tag) { + return props.getProperty(tag); + } + - public Properties getProperties() { - return props; - } + public Properties getProperties() { + return props; + } - public void setProperty(String tag, String value) { - if(value!=null) { - props.put(tag, value); - if(Config.CADI_KEYFILE.equals(tag)) { - // reset decryption too - try { - symm = Symm.obtain(this); - } catch (CadiException e) { - System.err.append("FATAL ERROR: Cannot obtain Key Information."); - e.printStackTrace(System.err); - System.exit(1); - } - } - } - } + public void setProperty(String tag, String value) { + if(value!=null) { + props.put(tag, value); + if(Config.CADI_KEYFILE.equals(tag)) { + // reset decryption too + try { + symm = Symm.obtain(this); + } catch (CadiException e) { + System.err.append("FATAL ERROR: Cannot obtain Key Information."); + e.printStackTrace(System.err); + System.exit(1); + } + } + } + } - public interface LogIt { - public void push(Level level, Object ... elements) ; - } - - private class StreamLogIt implements LogIt { - private PrintStream ps; - - public StreamLogIt(PrintStream ps) { - this.ps = ps; - } - @Override - public void push(Level level, Object ... elements) { - ps.println(buildMsg(level,elements)); - ps.flush(); - } - - } + public interface LogIt { + public void push(Level level, Object ... elements) ; + } + + private class StreamLogIt implements LogIt { + private PrintStream ps; + + public StreamLogIt(PrintStream ps) { + this.ps = ps; + } + @Override + public void push(Level level, Object ... elements) { + ps.println(buildMsg(level,elements)); + ps.flush(); + } + + } - public void set(LogIt logit) { - logIt = logit; - } + public void set(LogIt logit) { + logIt = logit; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Revalidator.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Revalidator.java index 125ac24c..66ba86ae 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Revalidator.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Revalidator.java @@ -23,12 +23,12 @@ package org.onap.aaf.cadi; public interface Revalidator { - /** - * Re-Validate Credential - * - * @param prin - * @return - */ - public CachedPrincipal.Resp revalidate(TRANS trans, CachedPrincipal prin); + /** + * Re-Validate Credential + * + * @param prin + * @return + */ + public CachedPrincipal.Resp revalidate(TRANS trans, CachedPrincipal prin); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/SecuritySetter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/SecuritySetter.java index 31563017..194712e0 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/SecuritySetter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/SecuritySetter.java @@ -31,14 +31,14 @@ package org.onap.aaf.cadi; * */ public interface SecuritySetter { - public String getID(); - - public void setSecurity(CT client) throws CadiException; - - /** - * Returns number of bad logins registered - * @param respCode - * @return - */ - public int setLastResponse(int respCode); + public String getID(); + + public void setSecurity(CT client) throws CadiException; + + /** + * Returns number of bad logins registered + * @param respCode + * @return + */ + public int setLastResponse(int respCode); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java b/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java index 38a01a09..518ea6dd 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java @@ -28,40 +28,40 @@ import javax.servlet.ServletContext; public class ServletContextAccess extends PropAccess { - private ServletContext context; + private ServletContext context; - public ServletContextAccess(FilterConfig filterConfig) { - super(filterConfig); // protected constructor... does not have "init" called. - context = filterConfig.getServletContext(); + public ServletContextAccess(FilterConfig filterConfig) { + super(filterConfig); // protected constructor... does not have "init" called. + context = filterConfig.getServletContext(); - for(Enumeration en = filterConfig.getInitParameterNames();en.hasMoreElements();) { - String name = (String)en.nextElement(); - setProperty(name, filterConfig.getInitParameter(name)); - } - init(getProperties()); - } + for(Enumeration en = filterConfig.getInitParameterNames();en.hasMoreElements();) { + String name = (String)en.nextElement(); + setProperty(name, filterConfig.getInitParameter(name)); + } + init(getProperties()); + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.PropAccess#log(org.onap.aaf.cadi.Access.Level, java.lang.Object[]) - */ - @Override - public void log(Level level, Object... elements) { - if(willLog(level)) { - StringBuilder sb = buildMsg(level, elements); - context.log(sb.toString()); - } - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.PropAccess#log(org.onap.aaf.cadi.Access.Level, java.lang.Object[]) + */ + @Override + public void log(Level level, Object... elements) { + if(willLog(level)) { + StringBuilder sb = buildMsg(level, elements); + context.log(sb.toString()); + } + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.PropAccess#log(java.lang.Exception, java.lang.Object[]) - */ - @Override - public void log(Exception e, Object... elements) { - StringBuilder sb = buildMsg(Level.ERROR, elements); - context.log(sb.toString(),e); - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.PropAccess#log(java.lang.Exception, java.lang.Object[]) + */ + @Override + public void log(Exception e, Object... elements) { + StringBuilder sb = buildMsg(Level.ERROR, elements); + context.log(sb.toString(),e); + } - public ServletContext context() { - return context; - } + public ServletContext context() { + return context; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java index afc1d979..fd60b0c1 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java @@ -69,184 +69,184 @@ import org.onap.aaf.cadi.config.Config; * */ public class Symm { - private static final byte[] DOUBLE_EQ = new byte[] {'=','='}; - public static final String ENC = "enc:"; - private static final Object LOCK = new Object(); - private static final SecureRandom random = new SecureRandom(); - - public final char[] codeset; - private final int splitLinesAt; - private final String encoding; - private final Convert convert; - private final boolean endEquals; - private byte[] keyBytes = null; - //Note: AES Encryption is not Thread Safe. It is Synchronized - //private AES aes = null; // only initialized from File, and only if needed for Passwords - - /** - * This is the standard base64 Key Set. - * RFC 2045 - */ - public static final Symm base64 = new Symm( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() - ,76, Config.UTF_8,true); - - public static final Symm base64noSplit = new Symm( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() - ,Integer.MAX_VALUE, Config.UTF_8,true); - - /** - * This is the standard base64 set suitable for URLs and Filenames - * RFC 4648 - */ - public static final Symm base64url = new Symm( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray() - ,76, Config.UTF_8,true); - - /** - * A Password set, using US-ASCII - * RFC 4648 - */ - public static final Symm encrypt = new Symm(base64url.codeset,1024, "US-ASCII", false); - private static final byte[] EMPTY = new byte[0]; - - /** - * A typical set of Password Chars - * Note, this is too large to fit into the algorithm. Only use with PassGen - */ - private static char passChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+!@#$%^&*(){}[]?:;,.".toCharArray(); - - - private static Symm internalOnly = null; - - /** - * Use this to create special case Case Sets and/or Line breaks - * - * If you don't know why you need this, use the Singleton Method - * - * @param codeset - * @param split - */ - public Symm(char[] codeset, int split, String charset, boolean useEndEquals) { - this.codeset = codeset; - splitLinesAt = split; - encoding = charset; - endEquals = useEndEquals; - char prev = 0, curr=0, first = 0; - int offset=Integer.SIZE; // something that's out of range for integer array - - // There can be time efficiencies gained when the underlying keyset consists mainly of ordered - // data (i.e. abcde...). Therefore, we'll quickly analyze the keyset. If it proves to have - // too much entropy, the "Unordered" algorithm, which is faster in such cases is used. - ArrayList la = new ArrayList<>(); - for(int i=0;icodeset.length/3) { - convert = new Unordered(codeset); - } else { // too random to get speed enhancement from range algorithm - int[][] range = new int[la.size()][]; - la.toArray(range); - convert = new Ordered(range); - } - } - - public Symm copy(int lines) { - return new Symm(codeset,lines,encoding,endEquals); - } - - // Only used by keygen, which is intentionally randomized. Therefore, always use unordered - private Symm(char[] codeset, Symm parent) { - this.codeset = codeset; - splitLinesAt = parent.splitLinesAt; - endEquals = parent.endEquals; - encoding = parent.encoding; - convert = new Unordered(codeset); - } - - /** - * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc. - * @return - */ - @Deprecated - public static final Symm base64() { - return base64; - } - - /** - * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc. - * No Line Splitting - * @return - */ - @Deprecated - public static final Symm base64noSplit() { - return base64noSplit; - } - - /** - * Obtain the base64 "URL" behavior of this class, for use in File Names, etc. (no "/") - */ - @Deprecated - public static final Symm base64url() { - return base64url; - } - - /** - * Obtain a special ASCII version for Scripting, with base set of base64url use in File Names, etc. (no "/") - */ - public static final Symm baseCrypt() { - return encrypt; - } - - public T exec(SyncExec exec) throws Exception { - synchronized(LOCK) { - if(keyBytes == null) { - keyBytes = new byte[AES.AES_KEY_SIZE/8]; - int offset = (Math.abs(codeset[0])+47)%(codeset.length-keyBytes.length); - for(int i=0;i { - public T exec(Encryption enc) throws IOException, Exception; - } - + private static final byte[] DOUBLE_EQ = new byte[] {'=','='}; + public static final String ENC = "enc:"; + private static final Object LOCK = new Object(); + private static final SecureRandom random = new SecureRandom(); + + public final char[] codeset; + private final int splitLinesAt; + private final String encoding; + private final Convert convert; + private final boolean endEquals; + private byte[] keyBytes = null; + //Note: AES Encryption is not Thread Safe. It is Synchronized + //private AES aes = null; // only initialized from File, and only if needed for Passwords + + /** + * This is the standard base64 Key Set. + * RFC 2045 + */ + public static final Symm base64 = new Symm( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() + ,76, Config.UTF_8,true); + + public static final Symm base64noSplit = new Symm( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() + ,Integer.MAX_VALUE, Config.UTF_8,true); + + /** + * This is the standard base64 set suitable for URLs and Filenames + * RFC 4648 + */ + public static final Symm base64url = new Symm( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray() + ,76, Config.UTF_8,true); + + /** + * A Password set, using US-ASCII + * RFC 4648 + */ + public static final Symm encrypt = new Symm(base64url.codeset,1024, "US-ASCII", false); + private static final byte[] EMPTY = new byte[0]; + + /** + * A typical set of Password Chars + * Note, this is too large to fit into the algorithm. Only use with PassGen + */ + private static char passChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+!@#$%^&*(){}[]?:;,.".toCharArray(); + + + private static Symm internalOnly = null; + + /** + * Use this to create special case Case Sets and/or Line breaks + * + * If you don't know why you need this, use the Singleton Method + * + * @param codeset + * @param split + */ + public Symm(char[] codeset, int split, String charset, boolean useEndEquals) { + this.codeset = codeset; + splitLinesAt = split; + encoding = charset; + endEquals = useEndEquals; + char prev = 0, curr=0, first = 0; + int offset=Integer.SIZE; // something that's out of range for integer array + + // There can be time efficiencies gained when the underlying keyset consists mainly of ordered + // data (i.e. abcde...). Therefore, we'll quickly analyze the keyset. If it proves to have + // too much entropy, the "Unordered" algorithm, which is faster in such cases is used. + ArrayList la = new ArrayList<>(); + for(int i=0;icodeset.length/3) { + convert = new Unordered(codeset); + } else { // too random to get speed enhancement from range algorithm + int[][] range = new int[la.size()][]; + la.toArray(range); + convert = new Ordered(range); + } + } + + public Symm copy(int lines) { + return new Symm(codeset,lines,encoding,endEquals); + } + + // Only used by keygen, which is intentionally randomized. Therefore, always use unordered + private Symm(char[] codeset, Symm parent) { + this.codeset = codeset; + splitLinesAt = parent.splitLinesAt; + endEquals = parent.endEquals; + encoding = parent.encoding; + convert = new Unordered(codeset); + } + + /** + * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc. + * @return + */ + @Deprecated + public static final Symm base64() { + return base64; + } + + /** + * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc. + * No Line Splitting + * @return + */ + @Deprecated + public static final Symm base64noSplit() { + return base64noSplit; + } + + /** + * Obtain the base64 "URL" behavior of this class, for use in File Names, etc. (no "/") + */ + @Deprecated + public static final Symm base64url() { + return base64url; + } + + /** + * Obtain a special ASCII version for Scripting, with base set of base64url use in File Names, etc. (no "/") + */ + public static final Symm baseCrypt() { + return encrypt; + } + + public T exec(SyncExec exec) throws Exception { + synchronized(LOCK) { + if(keyBytes == null) { + keyBytes = new byte[AES.AES_KEY_SIZE/8]; + int offset = (Math.abs(codeset[0])+47)%(codeset.length-keyBytes.length); + for(int i=0;i { + public T exec(Encryption enc) throws IOException, Exception; + } + public byte[] encode(byte[] toEncrypt) throws IOException { - if(toEncrypt==null) { - return EMPTY; - } else { - ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(toEncrypt.length*1.25)); - encode(new ByteArrayInputStream(toEncrypt),baos); - return baos.toByteArray(); - } - } + if(toEncrypt==null) { + return EMPTY; + } else { + ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(toEncrypt.length*1.25)); + encode(new ByteArrayInputStream(toEncrypt),baos); + return baos.toByteArray(); + } + } public byte[] decode(byte[] encrypted) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(encrypted.length*1.25)); - decode(new ByteArrayInputStream(encrypted),baos); - return baos.toByteArray(); - } + ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(encrypted.length*1.25)); + decode(new ByteArrayInputStream(encrypted),baos); + return baos.toByteArray(); + } - /** + /** * Helper function for String API of "Encode" * use "getBytes" with appropriate char encoding, etc. * @@ -255,22 +255,22 @@ public class Symm { * @throws IOException */ public String encode(String str) throws IOException { - byte[] array; - boolean useDefaultEncoding = false; - try { - array = str.getBytes(encoding); - } catch (IOException e) { - array = str.getBytes(); // take default - useDefaultEncoding = true; - } - // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code - ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*1.363)); // account for 4 bytes for 3 and a byte or two more - - encode(new ByteArrayInputStream(array),baos); - if (useDefaultEncoding) { - return baos.toString(); - } - return baos.toString(encoding); + byte[] array; + boolean useDefaultEncoding = false; + try { + array = str.getBytes(encoding); + } catch (IOException e) { + array = str.getBytes(); // take default + useDefaultEncoding = true; + } + // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code + ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*1.363)); // account for 4 bytes for 3 and a byte or two more + + encode(new ByteArrayInputStream(array),baos); + if (useDefaultEncoding) { + return baos.toString(); + } + return baos.toString(encoding); } /** @@ -281,24 +281,24 @@ public class Symm { * @throws IOException */ public String decode(String str) throws IOException { - byte[] array; - boolean useDefaultEncoding = false; - try { - array = str.getBytes(encoding); - } catch (IOException e) { - array = str.getBytes(); // take default - useDefaultEncoding = true; - } - // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code - ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*.76)); // Decoding is 3 bytes for 4. Allocate slightly more than 3/4s - decode(new ByteArrayInputStream(array), baos); - if (useDefaultEncoding) { - return baos.toString(); - } - return baos.toString(encoding); - } - - /** + byte[] array; + boolean useDefaultEncoding = false; + try { + array = str.getBytes(encoding); + } catch (IOException e) { + array = str.getBytes(); // take default + useDefaultEncoding = true; + } + // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code + ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*.76)); // Decoding is 3 bytes for 4. Allocate slightly more than 3/4s + decode(new ByteArrayInputStream(array), baos); + if (useDefaultEncoding) { + return baos.toString(); + } + return baos.toString(encoding); + } + + /** * Convenience Function * * encode String into InputStream and call encode(InputStream, OutputStream) @@ -307,29 +307,29 @@ public class Symm { * @param out * @throws IOException */ - public void encode(String string, OutputStream out) throws IOException { - encode(new ByteArrayInputStream(string.getBytes()),out); - } - - /** - * Convenience Function - * - * encode String into InputStream and call decode(InputStream, OutputStream) - * - * @param string - * @param out - * @throws IOException - */ - public void decode(String string, OutputStream out) throws IOException { - decode(new ByteArrayInputStream(string.getBytes()),out); - } + public void encode(String string, OutputStream out) throws IOException { + encode(new ByteArrayInputStream(string.getBytes()),out); + } + + /** + * Convenience Function + * + * encode String into InputStream and call decode(InputStream, OutputStream) + * + * @param string + * @param out + * @throws IOException + */ + public void decode(String string, OutputStream out) throws IOException { + decode(new ByteArrayInputStream(string.getBytes()),out); + } public void encode(InputStream is, OutputStream os, byte[] prefix) throws IOException { - os.write(prefix); - encode(is,os); + os.write(prefix); + encode(is,os); } - /** + /** * encode InputStream onto Output Stream * * @param is @@ -338,95 +338,95 @@ public class Symm { * @throws IOException */ public void encode(InputStream is, OutputStream os) throws IOException { - // StringBuilder sb = new StringBuilder((int)(estimate*1.255)); // try to get the right size of StringBuilder from start.. slightly more than 1.25 times - int prev=0; - int read, idx=0, line=0; - boolean go; - do { - read = is.read(); - if(go = read>=0) { - if(line>=splitLinesAt) { - os.write('\n'); - line = 0; - } - switch(++idx) { // 1 based reading, slightly faster ++ - case 1: // ptr is the first 6 bits of read - os.write(codeset[read>>2]); - prev = read; - break; - case 2: // ptr is the last 2 bits of prev followed by the first 4 bits of read - os.write(codeset[((prev & 0x03)<<4) | (read>>4)]); - prev = read; - break; - default: //(3+) - // Char 1 is last 4 bits of prev plus the first 2 bits of read - // Char 2 is the last 6 bits of read - os.write(codeset[(((prev & 0xF)<<2) | (read>>6))]); - if(line==splitLinesAt) { // deal with line splitting for two characters - os.write('\n'); - line=0; - } - os.write(codeset[(read & 0x3F)]); - ++line; - idx = 0; - prev = 0; - } - ++line; - } else { // deal with any remaining bits from Prev, then pad - switch(idx) { - case 1: // just the last 2 bits of prev - os.write(codeset[(prev & 0x03)<<4]); - if(endEquals)os.write(DOUBLE_EQ); - break; - case 2: // just the last 4 bits of prev - os.write(codeset[(prev & 0xF)<<2]); - if(endEquals)os.write('='); - break; - } - idx = 0; - } - - } while(go); + // StringBuilder sb = new StringBuilder((int)(estimate*1.255)); // try to get the right size of StringBuilder from start.. slightly more than 1.25 times + int prev=0; + int read, idx=0, line=0; + boolean go; + do { + read = is.read(); + if(go = read>=0) { + if(line>=splitLinesAt) { + os.write('\n'); + line = 0; + } + switch(++idx) { // 1 based reading, slightly faster ++ + case 1: // ptr is the first 6 bits of read + os.write(codeset[read>>2]); + prev = read; + break; + case 2: // ptr is the last 2 bits of prev followed by the first 4 bits of read + os.write(codeset[((prev & 0x03)<<4) | (read>>4)]); + prev = read; + break; + default: //(3+) + // Char 1 is last 4 bits of prev plus the first 2 bits of read + // Char 2 is the last 6 bits of read + os.write(codeset[(((prev & 0xF)<<2) | (read>>6))]); + if(line==splitLinesAt) { // deal with line splitting for two characters + os.write('\n'); + line=0; + } + os.write(codeset[(read & 0x3F)]); + ++line; + idx = 0; + prev = 0; + } + ++line; + } else { // deal with any remaining bits from Prev, then pad + switch(idx) { + case 1: // just the last 2 bits of prev + os.write(codeset[(prev & 0x03)<<4]); + if(endEquals)os.write(DOUBLE_EQ); + break; + case 2: // just the last 4 bits of prev + os.write(codeset[(prev & 0xF)<<2]); + if(endEquals)os.write('='); + break; + } + idx = 0; + } + + } while(go); } public void decode(InputStream is, OutputStream os, int skip) throws IOException { - if(is.skip(skip)!=skip) { - throw new IOException("Error skipping on IOStream in Symm"); - } - decode(is,os); + if(is.skip(skip)!=skip) { + throw new IOException("Error skipping on IOStream in Symm"); + } + decode(is,os); } /** - * Decode InputStream onto OutputStream - * @param is - * @param os - * @throws IOException - */ + * Decode InputStream onto OutputStream + * @param is + * @param os + * @throws IOException + */ public void decode(InputStream is, OutputStream os) throws IOException { - int read, idx=0; - int prev=0, index; - while((read = is.read())>=0) { - index = convert.convert(read); - if(index>=0) { - switch(++idx) { // 1 based cases, slightly faster ++ - case 1: // index goes into first 6 bits of prev - prev = index<<2; - break; - case 2: // write second 2 bits of into prev, write byte, last 4 bits go into prev - os.write((byte)(prev|(index>>4))); - prev = index<<4; - break; - case 3: // first 4 bits of index goes into prev, write byte, last 2 bits go into prev - os.write((byte)(prev|(index>>2))); - prev = index<<6; - break; - default: // (3+) | prev and last six of index - os.write((byte)(prev|(index&0x3F))); - idx = prev = 0; - } - } - }; - os.flush(); + int read, idx=0; + int prev=0, index; + while((read = is.read())>=0) { + index = convert.convert(read); + if(index>=0) { + switch(++idx) { // 1 based cases, slightly faster ++ + case 1: // index goes into first 6 bits of prev + prev = index<<2; + break; + case 2: // write second 2 bits of into prev, write byte, last 4 bits go into prev + os.write((byte)(prev|(index>>4))); + prev = index<<4; + break; + case 3: // first 4 bits of index goes into prev, write byte, last 2 bits go into prev + os.write((byte)(prev|(index>>2))); + prev = index<<6; + break; + default: // (3+) | prev and last six of index + os.write((byte)(prev|(index&0x3F))); + idx = prev = 0; + } + } + }; + os.flush(); } /** @@ -435,7 +435,7 @@ public class Symm { * */ private interface Convert { - public int convert(int read) throws IOException; + public int convert(int read) throws IOException; } /** @@ -445,27 +445,27 @@ public class Symm { * */ private static final class Ordered implements Convert { - private int[][] range; - public Ordered(int[][] range) { - this.range = range; - } - public int convert(int read) throws IOException { - // System.out.print((char)read); - switch(read) { - case -1: - case '=': - case ' ': - case '\n': - case '\r': - return -1; - } - for(int i=0;i= range[i][0] && read<=range[i][1]) { - return read-range[i][2]; - } - } - throw new IOException("Unacceptable Character in Stream"); - } + private int[][] range; + public Ordered(int[][] range) { + this.range = range; + } + public int convert(int read) throws IOException { + // System.out.print((char)read); + switch(read) { + case -1: + case '=': + case ' ': + case '\n': + case '\r': + return -1; + } + for(int i=0;i= range[i][0] && read<=range[i][1]) { + return read-range[i][2]; + } + } + throw new IOException("Unacceptable Character in Stream"); + } } /** @@ -475,24 +475,24 @@ public class Symm { * */ private static final class Unordered implements Convert { - private char[] codec; - public Unordered(char[] codec) { - this.codec = codec; - } - public int convert(int read) throws IOException { - switch(read) { - case -1: - case '=': - case '\n': - case '\r': - return -1; - } - for(int i=0;i() { - @Override - public Void exec(Encryption enc) throws Exception { - CipherInputStream cis = enc.inputStream(new ByteArrayInputStream(baos.toByteArray()), true); - try { - encode(cis,os); - } finally { - os.flush(); - cis.close(); - } - return null; - } - }); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new IOException(e); - } - } + if(password==null) { + throw new IOException("Invalid password passed"); + } + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + byte[] bytes = password.getBytes(); + if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization + dos.write(bytes); + } else { + + Random r = new SecureRandom(); + int start = 0; + byte b; + for(int i=0;i<3;++i) { + dos.writeByte(b=(byte)r.nextInt()); + start+=Math.abs(b); + } + start%=0x7; + for(int i=0;i() { + @Override + public Void exec(Encryption enc) throws Exception { + CipherInputStream cis = enc.inputStream(new ByteArrayInputStream(baos.toByteArray()), true); + try { + encode(cis,os); + } finally { + os.flush(); + cis.close(); + } + return null; + } + }); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException(e); + } + } /** * Decrypt a password into a String @@ -733,10 +733,10 @@ public class Symm { * @throws IOException */ public String depass(String password) throws IOException { - if(password==null)return null; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - depass(password,baos); - return new String(baos.toByteArray()); + if(password==null)return null; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + depass(password,baos); + return new String(baos.toByteArray()); } /** @@ -750,68 +750,68 @@ public class Symm { * @throws IOException */ public long depass(final String password, final OutputStream os) throws IOException { - int offset = password.startsWith(ENC)?4:0; - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes(),offset,password.length()-offset); - try { - exec(new SyncExec() { - @Override - public Void exec(Encryption enc) throws IOException { - CipherOutputStream cos = enc.outputStream(baos, false); - decode(bais,cos); - cos.close(); // flush - return null; - } - }); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new IOException(e); - } - - byte[] bytes = baos.toByteArray(); - DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes)); - long time; - if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization - os.write(bytes); - time = 0L; - } else { - int start=0; - for(int i=0;i<3;++i) { - start+=Math.abs(dis.readByte()); - } - start%=0x7; - for(int i=0;i() { + @Override + public Void exec(Encryption enc) throws IOException { + CipherOutputStream cos = enc.outputStream(baos, false); + decode(bais,cos); + cos.close(); // flush + return null; + } + }); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException(e); + } + + byte[] bytes = baos.toByteArray(); + DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes)); + long time; + if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization + os.write(bytes); + time = 0L; + } else { + int start=0; + for(int i=0;i<3;++i) { + start+=Math.abs(dis.readByte()); + } + start%=0x7; + for(int i=0;i=0) { - index = o.next(); - if(index<0 || index>=codeset.length) { - System.out.println("uh, oh"); - } - if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something) - for(int j=index;j=0;--j) { - if(seq[j]==0) { - seq[j]=codeset[filled]; - --filled; - break; - } - } - right = true; - } - } - Symm newSymm = new Symm(seq,this); - // Set the KeyBytes - try { - newSymm.keyBytes = new byte[AES.AES_KEY_SIZE/8]; - int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-newSymm.keyBytes.length); - for(int i=0;i=0) { + index = o.next(); + if(index<0 || index>=codeset.length) { + System.out.println("uh, oh"); + } + if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something) + for(int j=index;j=0;--j) { + if(seq[j]==0) { + seq[j]=codeset[filled]; + --filled; + break; + } + } + right = true; + } + } + Symm newSymm = new Symm(seq,this); + // Set the KeyBytes + try { + newSymm.keyBytes = new byte[AES.AES_KEY_SIZE/8]; + int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-newSymm.keyBytes.length); + for(int i=0;i { - /** - * Mutate the (assumed validated) Principal into the expected Principal name to be used to construct - * - * @param p - * @return - */ - public T mutate(Principal p); + /** + * Mutate the (assumed validated) Principal into the expected Principal name to be used to construct + * + * @param p + * @return + */ + public T mutate(Principal p); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/TrustChecker.java b/cadi/core/src/main/java/org/onap/aaf/cadi/TrustChecker.java index fabec0b0..6b1433f4 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/TrustChecker.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/TrustChecker.java @@ -32,21 +32,21 @@ import org.onap.aaf.cadi.taf.TafResp; * */ public interface TrustChecker { - public TafResp mayTrust(TafResp tresp, HttpServletRequest req); - - /** - * A class that trusts no-one else, so just return same TResp - */ - public static TrustChecker NOTRUST = new TrustChecker() { - @Override - public TafResp mayTrust(TafResp tresp, HttpServletRequest req) { - return tresp; - } + public TafResp mayTrust(TafResp tresp, HttpServletRequest req); + + /** + * A class that trusts no-one else, so just return same TResp + */ + public static TrustChecker NOTRUST = new TrustChecker() { + @Override + public TafResp mayTrust(TafResp tresp, HttpServletRequest req) { + return tresp; + } - @Override - public void setLur(Lur lur) { - } - }; + @Override + public void setLur(Lur lur) { + } + }; - public void setLur(Lur lur); + public void setLur(Lur lur); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/User.java b/cadi/core/src/main/java/org/onap/aaf/cadi/User.java index 34aaf170..512f2e6a 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/User.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/User.java @@ -36,142 +36,142 @@ import org.onap.aaf.cadi.lur.LocalPermission; * */ public final class User { - private static final Map NULL_MAP = new HashMap<>(); - public String name; - private byte[] cred; - public Principal principal; - Map perms ; - long permExpires; - private final long interval; - int count; - - // Note: This should only be used for Local RBAC (in memory) - public User(Principal principal) { - this.principal = principal; - name = principal.getName(); - perms = NULL_MAP; - permExpires = Long.MAX_VALUE; // Never. Well, until 64 bits of millis since 1970 expires... - interval = 0L; - count = 0; - } - - public User(String name, byte[] cred) { - this.principal = null; - this.name = name; - this.cred = cred; - perms = NULL_MAP; - permExpires = Long.MAX_VALUE; // Never. Well, until 64 bits of millis since 1970 expires... - interval = 0L; - count = 0; - } - - public User(Principal principal, long expireInterval) { - this.principal = principal; - this.name = principal.getName(); - perms = NULL_MAP; - expireInterval = Math.max(expireInterval, 0); // avoid < 1 - interval = Math.max(AbsUserCache.MIN_INTERVAL,Math.min(expireInterval,AbsUserCache.MAX_INTERVAL)); - count = 0; - renewPerm(); - renewPerm(); - } - - public User(String name, byte[] cred, long expireInterval) { - this.principal = null; - this.name = name; - this.cred = cred; - perms = NULL_MAP; - expireInterval = Math.max(expireInterval, 0); // avoid < 1 - interval = Math.max(AbsUserCache.MIN_INTERVAL,Math.min(expireInterval,AbsUserCache.MAX_INTERVAL)); - count = 0; - renewPerm(); - } - - public void renewPerm() { - permExpires = System.currentTimeMillis()+interval; - } - - public long permExpires() { - return permExpires; - } - - public boolean permExpired() { - return System.currentTimeMillis() > permExpires; - } - - public boolean noPerms() { - return perms==null || perms==NULL_MAP || perms.values().size()==0; - } - - public synchronized void setNoPerms() { - perms=NULL_MAP; - renewPerm(); - } - - public boolean permsUnloaded() { - return perms==null || perms==NULL_MAP; - } - - public synchronized void incCount() { - ++count; - } - - public synchronized void resetCount() { - count=0; - } - - public Map newMap() { - return new ConcurrentHashMap<>(); - } - - public void add(LocalPermission permission) { - if(perms==NULL_MAP) { - perms=newMap(); - } - perms.put(permission.getKey(),permission); - } - - public void add(Map newMap, PERM permission) { - newMap.put(permission.getKey(),permission); - } - - public synchronized void setMap(Map newMap) { - perms = newMap; - renewPerm(); - } - - public boolean contains(Permission perm) { - for (Permission p : perms.values()) { - if (p.match(perm)) return true; - } - return false; - } - - public void copyPermsTo(List sink) { - sink.addAll(perms.values()); - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(principal.getName()); - sb.append('|'); - boolean first = true; - synchronized(perms) { - for(Permission gp : perms.values()) { - if(first) { - first = false; - sb.append(':'); - } else { - sb.append(','); - } - sb.append(gp.getKey()); - } - } - return sb.toString(); - } - - public byte[] getCred() { - return cred; - } + private static final Map NULL_MAP = new HashMap<>(); + public String name; + private byte[] cred; + public Principal principal; + Map perms ; + long permExpires; + private final long interval; + int count; + + // Note: This should only be used for Local RBAC (in memory) + public User(Principal principal) { + this.principal = principal; + name = principal.getName(); + perms = NULL_MAP; + permExpires = Long.MAX_VALUE; // Never. Well, until 64 bits of millis since 1970 expires... + interval = 0L; + count = 0; + } + + public User(String name, byte[] cred) { + this.principal = null; + this.name = name; + this.cred = cred; + perms = NULL_MAP; + permExpires = Long.MAX_VALUE; // Never. Well, until 64 bits of millis since 1970 expires... + interval = 0L; + count = 0; + } + + public User(Principal principal, long expireInterval) { + this.principal = principal; + this.name = principal.getName(); + perms = NULL_MAP; + expireInterval = Math.max(expireInterval, 0); // avoid < 1 + interval = Math.max(AbsUserCache.MIN_INTERVAL,Math.min(expireInterval,AbsUserCache.MAX_INTERVAL)); + count = 0; + renewPerm(); + renewPerm(); + } + + public User(String name, byte[] cred, long expireInterval) { + this.principal = null; + this.name = name; + this.cred = cred; + perms = NULL_MAP; + expireInterval = Math.max(expireInterval, 0); // avoid < 1 + interval = Math.max(AbsUserCache.MIN_INTERVAL,Math.min(expireInterval,AbsUserCache.MAX_INTERVAL)); + count = 0; + renewPerm(); + } + + public void renewPerm() { + permExpires = System.currentTimeMillis()+interval; + } + + public long permExpires() { + return permExpires; + } + + public boolean permExpired() { + return System.currentTimeMillis() > permExpires; + } + + public boolean noPerms() { + return perms==null || perms==NULL_MAP || perms.values().size()==0; + } + + public synchronized void setNoPerms() { + perms=NULL_MAP; + renewPerm(); + } + + public boolean permsUnloaded() { + return perms==null || perms==NULL_MAP; + } + + public synchronized void incCount() { + ++count; + } + + public synchronized void resetCount() { + count=0; + } + + public Map newMap() { + return new ConcurrentHashMap<>(); + } + + public void add(LocalPermission permission) { + if(perms==NULL_MAP) { + perms=newMap(); + } + perms.put(permission.getKey(),permission); + } + + public void add(Map newMap, PERM permission) { + newMap.put(permission.getKey(),permission); + } + + public synchronized void setMap(Map newMap) { + perms = newMap; + renewPerm(); + } + + public boolean contains(Permission perm) { + for (Permission p : perms.values()) { + if (p.match(perm)) return true; + } + return false; + } + + public void copyPermsTo(List sink) { + sink.addAll(perms.values()); + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(principal.getName()); + sb.append('|'); + boolean first = true; + synchronized(perms) { + for(Permission gp : perms.values()) { + if(first) { + first = false; + sb.append(':'); + } else { + sb.append(','); + } + sb.append(gp.getKey()); + } + } + return sb.toString(); + } + + public byte[] getCred() { + return cred; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/UserChain.java b/cadi/core/src/main/java/org/onap/aaf/cadi/UserChain.java index 9d8f2b04..f6a98085 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/UserChain.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/UserChain.java @@ -38,6 +38,6 @@ package org.onap.aaf.cadi; * */ public interface UserChain { - public enum Protocol {BasicAuth,Cookie,Cert,OAuth}; - public String userChain(); + public enum Protocol {BasicAuth,Cookie,Cert,OAuth}; + public String userChain(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java index 8cb6ae06..4784d1ee 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java @@ -67,739 +67,739 @@ import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf; */ public class Config { - private static final String AAF_V2_0 = "org.onap.aaf.cadi.aaf.v2_0"; - private static final String AAF_V2_0_AAFCON = AAF_V2_0+".AAFCon"; - private static final String AAF_V2_0_AAF_LUR_PERM = AAF_V2_0+".AAFLurPerm"; - private static final String OAUTH = "org.onap.auth.oauth"; - private static final String OAUTH_TOKEN_MGR = OAUTH+".TokenMgr"; - private static final String OAUTH_HTTP_TAF = OAUTH+".OAuth2HttpTaf"; - private static final String OAUTH_DIRECT_TAF = OAUTH+".OAuthDirectTAF"; - public static final String UTF_8 = "UTF-8"; - - // Property Names associated with configurations. - // As of 1.0.2, these have had the dots removed so as to be compatible with JavaBean style - // configurations as well as property list style. - public static final String HOSTNAME = "hostname"; - public static final String CADI_PROP_FILES = "cadi_prop_files"; // Additional Properties files (separate with ;) - public static final String CADI_LOGLEVEL = "cadi_loglevel"; - public static final String CADI_LOGDIR = "cadi_log_dir"; - public static final String CADI_ETCDIR = "cadi_etc_dir"; - public static final String CADI_LOGNAME = "cadi_logname"; - public static final String CADI_KEYFILE = "cadi_keyfile"; - public static final String CADI_KEYSTORE = "cadi_keystore"; - public static final String CADI_KEYSTORE_PASSWORD = "cadi_keystore_password"; - public static final String CADI_ALIAS = "cadi_alias"; - public static final String CADI_LOGINPAGE_URL = "cadi_loginpage_url"; - public static final String CADI_LATITUDE = "cadi_latitude"; - public static final String CADI_LONGITUDE = "cadi_longitude"; - - - public static final String CADI_KEY_PASSWORD = "cadi_key_password"; - public static final String CADI_TRUSTSTORE = "cadi_truststore"; - public static final String CADI_TRUSTSTORE_PASSWORD = "cadi_truststore_password"; - public static final String CADI_X509_ISSUERS = "cadi_x509_issuers"; - public static final String CADI_TRUST_MASKS="cadi_trust_masks"; - public static final String CADI_TRUST_PERM="cadi_trust_perm"; // IDs with this perm can utilize the "AS " user concept - public static final String CADI_PROTOCOLS = "cadi_protocols"; - public static final String CADI_NOAUTHN = "cadi_noauthn"; - public static final String CADI_LOC_LIST = "cadi_loc_list"; - - public static final String CADI_USER_CHAIN_TAG = "cadi_user_chain"; - public static final String CADI_USER_CHAIN = "USER_CHAIN"; - - public static final String CADI_OAUTH2_URL="cadi_oauth2_url"; - public static final String CADI_TOKEN_DIR = "cadi_token_dir"; + private static final String AAF_V2_0 = "org.onap.aaf.cadi.aaf.v2_0"; + private static final String AAF_V2_0_AAFCON = AAF_V2_0+".AAFCon"; + private static final String AAF_V2_0_AAF_LUR_PERM = AAF_V2_0+".AAFLurPerm"; + private static final String OAUTH = "org.onap.auth.oauth"; + private static final String OAUTH_TOKEN_MGR = OAUTH+".TokenMgr"; + private static final String OAUTH_HTTP_TAF = OAUTH+".OAuth2HttpTaf"; + private static final String OAUTH_DIRECT_TAF = OAUTH+".OAuthDirectTAF"; + public static final String UTF_8 = "UTF-8"; + + // Property Names associated with configurations. + // As of 1.0.2, these have had the dots removed so as to be compatible with JavaBean style + // configurations as well as property list style. + public static final String HOSTNAME = "hostname"; + public static final String CADI_PROP_FILES = "cadi_prop_files"; // Additional Properties files (separate with ;) + public static final String CADI_LOGLEVEL = "cadi_loglevel"; + public static final String CADI_LOGDIR = "cadi_log_dir"; + public static final String CADI_ETCDIR = "cadi_etc_dir"; + public static final String CADI_LOGNAME = "cadi_logname"; + public static final String CADI_KEYFILE = "cadi_keyfile"; + public static final String CADI_KEYSTORE = "cadi_keystore"; + public static final String CADI_KEYSTORE_PASSWORD = "cadi_keystore_password"; + public static final String CADI_ALIAS = "cadi_alias"; + public static final String CADI_LOGINPAGE_URL = "cadi_loginpage_url"; + public static final String CADI_LATITUDE = "cadi_latitude"; + public static final String CADI_LONGITUDE = "cadi_longitude"; + + + public static final String CADI_KEY_PASSWORD = "cadi_key_password"; + public static final String CADI_TRUSTSTORE = "cadi_truststore"; + public static final String CADI_TRUSTSTORE_PASSWORD = "cadi_truststore_password"; + public static final String CADI_X509_ISSUERS = "cadi_x509_issuers"; + public static final String CADI_TRUST_MASKS="cadi_trust_masks"; + public static final String CADI_TRUST_PERM="cadi_trust_perm"; // IDs with this perm can utilize the "AS " user concept + public static final String CADI_PROTOCOLS = "cadi_protocols"; + public static final String CADI_NOAUTHN = "cadi_noauthn"; + public static final String CADI_LOC_LIST = "cadi_loc_list"; + + public static final String CADI_USER_CHAIN_TAG = "cadi_user_chain"; + public static final String CADI_USER_CHAIN = "USER_CHAIN"; + + public static final String CADI_OAUTH2_URL="cadi_oauth2_url"; + public static final String CADI_TOKEN_DIR = "cadi_token_dir"; public static final String HTTPS_PROTOCOLS = "https.protocols"; public static final String HTTPS_CIPHER_SUITES = "https.cipherSuites"; public static final String HTTPS_CLIENT_PROTOCOLS="jdk.tls.client.protocols"; public static final String HTTPS_CIPHER_SUITES_DEFAULT="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA," - + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA," - + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA," - + "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_ECDH_ECDSA_WITH_RC4_128_SHA," - + "TLS_ECDH_RSA_WITH_RC4_128_SHA,TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA," - + "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,TLS_EMPTY_RENEGOTIATION_INFO_SCSV"; - - - public static final String LOCALHOST_ALLOW = "localhost_allow"; - public static final String LOCALHOST_DENY = "localhost_deny"; - - public static final String BASIC_REALM = "basic_realm"; // what is sent to the client - public static final String BASIC_WARN = "basic_warn"; // Warning of insecure channel - public static final String USERS = "local_users"; - public static final String GROUPS = "local_groups"; - public static final String WRITE_TO = "local_writeto"; // dump RBAC to local file in Tomcat Style (some apps use) - - public static final String OAUTH_CLIENT_ID="client_id"; - public static final String OAUTH_CLIENT_SECRET="client_secret"; - - public static final String AAF_ENV = "aaf_env"; - public static final String AAF_ROOT_NS = "aaf_root_ns"; - public static final String AAF_ROOT_NS_DEF = "org.osaaf.aaf"; - public static final String AAF_ROOT_COMPANY = "aaf_root_company"; - public static final String AAF_LOCATE_URL = "aaf_locate_url"; //URL for AAF locator - private static final String AAF_LOCATE_URL_TAG = "AAF_LOCATE_URL"; // Name of Above for use in Config Variables. - public static final String AAF_DEFAULT_VERSION = "2.1"; - public static final String AAF_URL = "aaf_url"; //URL for AAF... Use to trigger AAF configuration - public static final String AAF_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.service:" + AAF_DEFAULT_VERSION; - public static final String GUI_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.gui:" + AAF_DEFAULT_VERSION; - public static final String CM_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.cm:" + AAF_DEFAULT_VERSION; - public static final String FS_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.fs:" + AAF_DEFAULT_VERSION; - public static final String HELLO_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.hello:" + AAF_DEFAULT_VERSION; - public static final String OAUTH2_TOKEN_URL = "https://AAF_LOCATE_URL/AAF_NS.token:" + AAF_DEFAULT_VERSION; - public static final String OAUTH2_INTROSPECT_URL = "https://AAF_LOCATE_URL/AAF_NS.introspect:" + AAF_DEFAULT_VERSION; - - public static final String AAF_REGISTER_AS = "aaf_register_as"; - public static final String AAF_APPID = "aaf_id"; - public static final String AAF_APPPASS = "aaf_password"; - public static final String AAF_LUR_CLASS = "aaf_lur_class"; - public static final String AAF_TAF_CLASS = "aaf_taf_class"; - public static final String AAF_CONNECTOR_CLASS = "aaf_connector_class"; - public static final String AAF_LOCATOR_CLASS = "aaf_locator_class"; - public static final String AAF_CONN_TIMEOUT = "aaf_conn_timeout"; - public static final String AAF_CONN_TIMEOUT_DEF = "3000"; - public static final String AAF_CONN_IDLE_TIMEOUT = "aaf_conn_idle_timeout"; // only for Direct Jetty Access. - public static final String AAF_CONN_IDLE_TIMEOUT_DEF = "10000"; // only for Direct Jetty Access. - - // Default Classes: These are for Class loading to avoid direct compile links - public static final String AAF_TAF_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFTaf"; - public static final String AAF_LOCATOR_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFLocator"; - public static final String CADI_OLUR_CLASS_DEF = "org.onap.aaf.cadi.olur.OLur"; - public static final String CADI_OBASIC_HTTP_TAF_DEF = "org.onap.aaf.cadi.obasic.OBasicHttpTaf"; - public static final String CADI_AAF_CON_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFCon"; - - public static final String AAF_CALL_TIMEOUT = "aaf_timeout"; - public static final String AAF_CALL_TIMEOUT_DEF = "5000"; - public static final String AAF_USER_EXPIRES = "aaf_user_expires"; - public static final String AAF_USER_EXPIRES_DEF = "600000"; // Default is 10 mins - public static final String AAF_CLEAN_INTERVAL = "aaf_clean_interval"; - public static final String AAF_CLEAN_INTERVAL_DEF = "30000"; // Default is 30 seconds - public static final String AAF_REFRESH_TRIGGER_COUNT = "aaf_refresh_trigger_count"; - public static final String AAF_REFRESH_TRIGGER_COUNT_DEF = "3"; // Default is 10 mins - - public static final String AAF_HIGH_COUNT = "aaf_high_count"; - public static final String AAF_HIGH_COUNT_DEF = "1000"; // Default is 1000 entries - public static final String AAF_PERM_MAP = "aaf_perm_map"; - public static final String AAF_COMPONENT = "aaf_component"; - public static final String AAF_CERT_IDS = "aaf_cert_ids"; - public static final String AAF_DEBUG_IDS = "aaf_debug_ids"; // comma delimited - public static final String AAF_DATA_DIR = "aaf_data_dir"; // AAF processes and Components only. - - public static final String GW_URL = "gw_url"; - public static final String CM_URL = "cm_url"; - public static final String CM_TRUSTED_CAS = "cm_trusted_cas"; - - public static final String PATHFILTER_URLPATTERN = "pathfilter_urlpattern"; - public static final String PATHFILTER_STACK = "pathfilter_stack"; - public static final String PATHFILTER_NS = "pathfilter_ns"; - public static final String PATHFILTER_NOT_AUTHORIZED_MSG = "pathfilter_not_authorized_msg"; - - // This one should go unpublic - public static final String AAF_DEFAULT_REALM = "aaf_default_realm"; - private static String defaultRealm="none"; - - public static final String AAF_DOMAIN_SUPPORT = "aaf_domain_support"; - public static final String AAF_DOMAIN_SUPPORT_DEF = ".com:.org"; - - // OAUTH2 - public static final String AAF_OAUTH2_TOKEN_URL = "aaf_oauth2_token_url"; - public static final String AAF_OAUTH2_INTROSPECT_URL = "aaf_oauth2_introspect_url"; - public static final String AAF_ALT_OAUTH2_TOKEN_URL = "aaf_alt_oauth2_token_url"; - public static final String AAF_ALT_OAUTH2_INTROSPECT_URL = "aaf_alt_oauth2_introspect_url"; - public static final String AAF_ALT_OAUTH2_DOMAIN = "aaf_alt_oauth2_domain"; - public static final String AAF_ALT_CLIENT_ID = "aaf_alt_oauth2_client_id"; - public static final String AAF_ALT_CLIENT_SECRET = "aaf_alt_oauth2_client_secret"; - public static final String AAF_OAUTH2_HELLO_URL = "aaf_oauth2_hello_url"; - - private static final String AAF_V2_0_AAF_CON_HTTP = "org.onap.aaf.cadi.aaf.v2_0.AAFConHttp"; - - - public static void setDefaultRealm(Access access) { - try { - defaultRealm = logProp(access,Config.AAF_DEFAULT_REALM, - logProp(access,Config.BASIC_REALM, - logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName()) - ) - ); - } catch (UnknownHostException e) { - access.log(Level.INIT, "Unable to determine Hostname",e); - } - } - - public static HttpTaf configHttpTaf(Connector con, SecurityInfoC si, TrustChecker tc, CredVal up, Lur lur, Object ... additionalTafLurs) throws CadiException, LocatorException { - Access access = si.access; - ///////////////////////////////////////////////////// - // Setup AAFCon for any following - ///////////////////////////////////////////////////// - Class aafConClass = loadClass(access,CADI_AAF_CON_DEF); - Object aafcon = null; - if(con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) { - aafcon = con; - } else if(lur != null) { - Field f; - try { - f = lur.getClass().getField("aaf"); - aafcon = f.get(lur); - } catch (Exception e) { - access.log(Level.INIT, e); - } - } - - boolean hasDirectAAF = hasDirect("DirectAAFLur",additionalTafLurs); - // IMPORTANT! Don't attempt to load AAF Connector if there is no AAF URL - String aafURL = access.getProperty(AAF_URL,null); - if(!hasDirectAAF && aafcon==null && aafURL!=null) { - aafcon = loadAAFConnector(si, aafURL); - } - - HttpTaf taf; - // Setup Host, in case Network reports an unusable Hostname (i.e. VTiers, VPNs, etc) - String hostname = logProp(access, HOSTNAME,null); - if(hostname==null) { - try { - hostname = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e1) { - throw new CadiException("Unable to determine Hostname",e1); - } - } - - access.log(Level.INIT, "Hostname set to",hostname); - // Get appropriate TAFs - ArrayList htlist = new ArrayList<>(); - - ///////////////////////////////////////////////////// - // Add a Denial of Service TAF - // Note: how IPs and IDs are added are up to service type. - // They call "DenialOfServiceTaf.denyIP(String) or denyID(String) - ///////////////////////////////////////////////////// - htlist.add(new DenialOfServiceTaf(access)); - - ///////////////////////////////////////////////////// - // Configure Client Cert TAF - ///////////////////////////////////////////////////// - X509Taf x509TAF = null; - String truststore = logProp(access, CADI_TRUSTSTORE,null); - if(truststore!=null) { - String truststorePwd = access.getProperty(CADI_TRUSTSTORE_PASSWORD,null); - if(truststorePwd!=null) { - if(truststorePwd.startsWith(Symm.ENC)) { - try { - access.decrypt(truststorePwd,false); - } catch (IOException e) { - throw new CadiException(CADI_TRUSTSTORE_PASSWORD + " cannot be decrypted",e); - } - } - try { - x509TAF=new X509Taf(access,lur); - htlist.add(x509TAF); - access.log(Level.INIT,"Certificate Authorization enabled"); - } catch (SecurityException | IllegalArgumentException e) { - access.log(Level.INIT,"AAFListedCertIdentity cannot be instantiated. Certificate Authorization is now disabled",e); - } catch (CertificateException e) { - access.log(Level.INIT,"Certificate Authorization failed, it is disabled",e); - } catch (NoSuchAlgorithmException e) { - access.log(Level.INIT,"Certificate Authorization failed, wrong Security Algorithm",e); - } - } - } else { - access.log(Level.INIT,"Certificate Authorization not enabled"); - } - - ///////////////////////////////////////////////////// - // Configure Basic Auth (local content) - ///////////////////////////////////////////////////// - boolean hasOAuthDirectTAF = hasDirect("DirectOAuthTAF", additionalTafLurs); - String basicRealm = logProp(access, BASIC_REALM,null); - String aafCleanup = logProp(access, AAF_USER_EXPIRES,AAF_USER_EXPIRES_DEF); // Default is 10 mins - long userExp = Long.parseLong(aafCleanup); - boolean basicWarn = "TRUE".equals(access.getProperty(BASIC_WARN,"FALSE")); - - if(!hasDirectAAF) { - HttpTaf aaftaf=null; - if(!hasOAuthDirectTAF) { - if(basicRealm!=null) { - @SuppressWarnings("unchecked") - Class obasicCls = (Class)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF); - if(obasicCls!=null) { - try { - String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null); - String introspecturl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL, null); - if(tokenurl==null || introspecturl==null) { - access.log(Level.INIT,"Both tokenurl and introspecturl are required. Oauth Authorization is disabled."); - } - Constructor obasicConst = obasicCls.getConstructor(PropAccess.class,String.class, String.class, String.class); - htlist.add(obasicConst.newInstance(access,basicRealm,tokenurl,introspecturl)); - access.log(Level.INIT,"Oauth supported Basic Authorization is enabled"); - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - access.log(Level.INIT, e); - } - } else if(up!=null) { - access.log(Level.INIT,"Basic Authorization is enabled using realm",basicRealm); - // Allow warning about insecure channel to be turned off - if(!basicWarn) { - access.log(Level.INIT, "WARNING! The basicWarn property has been set to false.", - " There will be no additional warning if Basic Auth is used on an insecure channel"); - } - BasicHttpTaf bht = new BasicHttpTaf(access, up, basicRealm, userExp, basicWarn); - for(Object o : additionalTafLurs) { - if(o instanceof CredValDomain) { - bht.add((CredValDomain)o); - } - } - if(x509TAF!=null) { - x509TAF.add(bht); - } - htlist.add(bht); - access.log(Level.INIT,"Basic Authorization is enabled"); - } - } else { - access.log(Level.INIT,"Local Basic Authorization is disabled. Enable by setting basicRealm="); - } - - ///////////////////////////////////////////////////// - // Configure AAF Driven Basic Auth - ///////////////////////////////////////////////////// - if(aafcon==null) { - access.log(Level.INIT,"AAF Connection (AAFcon) is null. Cannot create an AAF TAF"); - } else if(aafURL==null) { - access.log(Level.INIT,"No AAF URL in properties, Cannot create an AAF TAF"); - } else {// There's an AAF_URL... try to configure an AAF - String aafTafClassName = logProp(access, AAF_TAF_CLASS,AAF_TAF_CLASS_DEF); - // Only 2.0 available at this time - if(AAF_TAF_CLASS_DEF.equals(aafTafClassName)) { - try { - Class aafTafClass = loadClass(access,aafTafClassName); - if(aafTafClass!=null) { - Constructor cstr = aafTafClass.getConstructor(Connector.class,boolean.class,AbsUserCache.class); - if(cstr!=null) { - if(lur instanceof AbsUserCache) { - aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn,lur); - } else { - cstr = aafTafClass.getConstructor(Connector.class,boolean.class); - if(cstr!=null) { - aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn); - } - } - if(aaftaf==null) { - access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured"); - } else { - access.log(Level.INIT,"AAF TAF Configured to ",aafURL); - // Note: will add later, after all others configured - } - } - } else { - access.log(Level.INIT, "There is no AAF TAF class available: %s. AAF TAF not configured.",aafTafClassName); - } - } catch(Exception e) { - access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured",e); - } - } - } - } - - ///////////////////////////////////////////////////// - // Configure OAuth TAF - ///////////////////////////////////////////////////// - if(!hasOAuthDirectTAF) { - String oauthTokenUrl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null); - Class oadtClss; - try { - oadtClss = Class.forName(OAUTH_DIRECT_TAF); - } catch (ClassNotFoundException e1) { - oadtClss = null; - access.log(Level.INIT, e1); - } - if(additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) { - htlist.add((HttpTaf)additionalTafLurs[0]); - String[] array= new String[additionalTafLurs.length-1]; - if(array.length>0) { - System.arraycopy(htlist, 1, array, 0, array.length); - } - additionalTafLurs = array; - access.log(Level.INIT,"OAuth2 Direct is enabled"); - } else if(oauthTokenUrl!=null) { - String oauthIntrospectUrl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null); - @SuppressWarnings("unchecked") - Class oaTCls = (Class)loadClass(access,OAUTH_HTTP_TAF); - if(oaTCls!=null) { - Class oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR); - if(oaTTmgrCls!=null) { - try { - Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class); - Object oaTTmgr = oaTTmgrGI.invoke(null /*this is static method*/,access,oauthTokenUrl,oauthIntrospectUrl); - Constructor oaTConst = oaTCls.getConstructor(Access.class,oaTTmgrCls); - htlist.add(oaTConst.newInstance(access,oaTTmgr)); - access.log(Level.INIT,"OAuth2 TAF is enabled"); - } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) { - access.log(Level.INIT,"OAuth2HttpTaf cannot be instantiated. OAuth2 is disabled",e); - } - } - } - } else { - access.log(Level.INIT,"OAuth TAF is not configured"); - } - } - - ///////////////////////////////////////////////////// - // Adding BasicAuth (AAF) last, after other primary Cookie Based - // Needs to be before Cert... see below - ///////////////////////////////////////////////////// - if(aaftaf!=null) { - htlist.add(aaftaf); - } - } - - ///////////////////////////////////////////////////// - // Any Additional Lurs passed in Constructor - ///////////////////////////////////////////////////// - if(additionalTafLurs!=null) { - for(Object additional : additionalTafLurs) { - if(additional instanceof BasicHttpTaf) { - BasicHttpTaf ht = (BasicHttpTaf)additional; - for(Object cv : additionalTafLurs) { - if(cv instanceof CredValDomain) { - ht.add((CredValDomain)cv); - access.printf(Level.INIT,"%s Authentication is enabled",cv); - } - } - htlist.add(ht); - } else if(additional instanceof HttpTaf) { - HttpTaf ht = (HttpTaf)additional; - htlist.add(ht); - access.printf(Level.INIT,"%s Authentication is enabled",additional.getClass().getSimpleName()); - } else if(hasOAuthDirectTAF) { - Class daupCls; - try { - daupCls = Class.forName("org.onap.aaf.auth.direct.DirectAAFUserPass"); - } catch (ClassNotFoundException e) { - daupCls = null; - access.log(Level.INIT, e); - } - if(daupCls != null && additional.getClass().isAssignableFrom(daupCls)) { - htlist.add(new BasicHttpTaf(access, (CredVal)additional , basicRealm, userExp, basicWarn)); - access.printf(Level.INIT,"Direct BasicAuth Authentication is enabled",additional.getClass().getSimpleName()); - } - } - } - } - - // Add BasicAuth, if any, to x509Taf - if(x509TAF!=null) { - for( HttpTaf ht : htlist) { - if(ht instanceof BasicHttpTaf) { - x509TAF.add((BasicHttpTaf)ht); - } - } - } - ///////////////////////////////////////////////////// - // Create EpiTaf from configured TAFs - ///////////////////////////////////////////////////// - if(htlist.size()==1) { - // just return the one - taf = htlist.get(0); - } else { - HttpTaf[] htarray = new HttpTaf[htlist.size()]; - htlist.toArray(htarray); - Locator locator = loadLocator(si, logProp(access, AAF_LOCATE_URL, null)); - - taf = new HttpEpiTaf(access,locator, tc, htarray); // ok to pass locator == null - String level = logProp(access, CADI_LOGLEVEL, null); - if(level!=null) { - access.setLogLevel(Level.valueOf(level)); - } - } - - return taf; - } - - public static String logProp(Access access,String tag, String def) { - String rv = access.getProperty(tag, def); - if(rv == null) { - access.log(Level.INIT,tag,"is not explicitly set"); - } else { - access.log(Level.INIT,tag,"is set to",rv); - } - return rv; - } - - public static Lur configLur(SecurityInfoC si, Connector con, Object ... additionalTafLurs) throws CadiException { - Access access = si.access; - List lurs = new ArrayList<>(); - - ///////////////////////////////////////////////////// - // Configure a Local Property Based RBAC/LUR - ///////////////////////////////////////////////////// - try { - String users = access.getProperty(USERS,null); - String groups = access.getProperty(GROUPS,null); - - if(groups!=null || users!=null) { - LocalLur ll = new LocalLur(access, users, groups); // note b64==null is ok.. just means no encryption. - lurs.add(ll); - - String writeto = access.getProperty(WRITE_TO,null); - if(writeto!=null) { - String msg = UsersDump.updateUsers(writeto, ll); - if(msg!=null) { - access.log(Level.INIT,"ERROR! Error Updating ",writeto,"with roles and users:",msg); - } - } - } - } catch (IOException e) { - throw new CadiException(e); - } - - ///////////////////////////////////////////////////// - // Configure the OAuth Lur (if any) - ///////////////////////////////////////////////////// - String tokenUrl = logProp(access,AAF_OAUTH2_TOKEN_URL, null); - String introspectUrl = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null); - if(tokenUrl!=null && introspectUrl !=null) { - try { - Class olurCls = loadClass(access, CADI_OLUR_CLASS_DEF); - if(olurCls!=null) { - Constructor olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class); - Lur olur = (Lur)olurCnst.newInstance(access,tokenUrl,introspectUrl); - lurs.add(olur); - access.log(Level.INIT, "OAuth2 LUR enabled"); - } else { - access.log(Level.INIT,"AAF/OAuth LUR plugin is not available."); - } - } catch (NoSuchMethodException| SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - String msg = e.getMessage(); - if(msg==null && e.getCause()!=null) { - msg = e.getCause().getMessage(); - } - access.log(Level.INIT,"AAF/OAuth LUR is not instantiated.",msg,e); - } - } else { - access.log(Level.INIT, "OAuth2 Lur disabled"); - } - - if(con!=null) { // try to reutilize connector - lurs.add(con.newLur()); - } else { - ///////////////////////////////////////////////////// - // Configure the AAF Lur (if any) - ///////////////////////////////////////////////////// - String aafURL = logProp(access,AAF_URL,null); // Trigger Property - String aafEnv = access.getProperty(AAF_ENV,null); - if(aafEnv == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL - int ec = aafURL.indexOf("envContext="); - if(ec>0) { - ec += 11; // length of envContext= - int slash = aafURL.indexOf('/', ec); - if(slash>0) { - aafEnv = aafURL.substring(ec, slash); - ((PropAccess)access).setProperty(AAF_ENV, aafEnv); - access.printf(Level.INIT, "Setting aafEnv to %s from aaf_url value",aafEnv); - } - } - } - - // Don't configure AAF if it is using DirectAccess - if(!hasDirect("DirectAAFLur",additionalTafLurs)) { - if(aafURL==null) { - access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded"); - } else {// There's an AAF_URL... try to configure an AAF - String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM); - ////////////AAF Lur 2.0 ///////////// - if(aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { - try { - Object aafcon = loadAAFConnector(si, aafURL); - if(aafcon==null) { - access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object."); - } else { - Class aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON); - if(aafAbsAAFCon!=null) { - Method mNewLur = aafAbsAAFCon.getMethod("newLur"); - Object aaflur = mNewLur.invoke(aafcon); - - if(aaflur==null) { - access.log(Level.INIT,"ERROR! AAF LUR Failed construction. NOT Configured"); - } else { - access.log(Level.INIT,"AAF LUR Configured to ",aafURL); - lurs.add((Lur)aaflur); - String debugIDs = logProp(access,Config.AAF_DEBUG_IDS, null); - if(debugIDs !=null && aaflur instanceof CachingLur) { - ((CachingLur)aaflur).setDebug(debugIDs); - } - } - } - } - } catch (Exception e) { - access.log(e,"AAF LUR class,",aafLurClassStr,"could not be constructed with given Constructors."); - } - } - } - } - } - - ///////////////////////////////////////////////////// - // Any Additional passed in Constructor - ///////////////////////////////////////////////////// - if(additionalTafLurs!=null) { - for(Object additional : additionalTafLurs) { - if(additional instanceof Lur) { - lurs.add((Lur)additional); - access.log(Level.INIT, additional); - } - } - } - - ///////////////////////////////////////////////////// - // Return a Lur based on how many there are... - ///////////////////////////////////////////////////// - switch(lurs.size()) { - case 0: - access.log(Level.INIT,"WARNING! No CADI LURs configured"); - // Return a NULL Lur that does nothing. - return new NullLur(); - case 1: - return lurs.get(0); // Only one, just return it, save processing - default: - // Multiple Lurs, use EpiLUR to handle - Lur[] la = new Lur[lurs.size()]; - lurs.toArray(la); - return new EpiLur(la); - } - } - - private static boolean hasDirect(String simpleClassName, Object[] additionalTafLurs) { - if(additionalTafLurs!=null) { - for(Object tf : additionalTafLurs) { - if(tf.getClass().getSimpleName().equals(simpleClassName)) { - return true; - } - } - } - return false; - } - - public static Object loadAAFConnector(SecurityInfoC si, String aafURL) { - Access access = si.access; - Object aafcon = null; - Class aafConClass = null; - - try { - if (aafURL!=null) { - String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, AAF_V2_0_AAF_CON_HTTP); - if (AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) { - aafConClass = loadClass(access, AAF_V2_0_AAF_CON_HTTP); - if (aafConClass != null) { - for (Constructor c : aafConClass.getConstructors()) { - List lo = new ArrayList<>(); - for (Class pc : c.getParameterTypes()) { - if (pc.equals(Access.class)) { - lo.add(access); - } else if (pc.equals(Locator.class)) { - lo.add(loadLocator(si, aafURL)); - } - } - if (c.getParameterTypes().length != lo.size()) { - continue; // back to another Constructor - } else { - aafcon = c.newInstance(lo.toArray()); - } - break; - } - } - } - if (aafcon != null) { - String mechid = logProp(access, Config.AAF_APPID, null); - String pass = access.getProperty(Config.AAF_APPPASS, null); - if (mechid != null && pass != null) { - try { - Method basicAuth = aafConClass.getMethod("basicAuth", String.class, String.class); - basicAuth.invoke(aafcon, mechid, pass); - } catch (NoSuchMethodException nsme) { - access.log(Level.NONE, nsme); - // it's ok, don't use - } - } - } - } - } catch (Exception e) { - access.log(e, "AAF Connector could not be constructed with given Constructors."); - } - - return aafcon; - } - - public static Class loadClass(Access access, String className) { - Class cls=null; - try { - cls = access.classLoader().loadClass(className); - } catch (ClassNotFoundException cnfe) { - access.log(Level.NONE, cnfe); - try { - cls = access.getClass().getClassLoader().loadClass(className); - } catch (ClassNotFoundException cnfe2) { - access.log(Level.NONE, cnfe2); - // just return null - } - } - return cls; - } - - @SuppressWarnings("unchecked") - public static Locator loadLocator(SecurityInfoC si, final String _url) throws LocatorException { - Access access = si.access; - Locator locator = null; - if(_url==null) { - access.log(Level.INIT,"No URL passed to 'loadLocator'. Disabled"); - } else { - String url = _url; - String replacement; - int idxAAFLocateUrl; - if((idxAAFLocateUrl=_url.indexOf(AAF_LOCATE_URL_TAG))>0 && ((replacement=access.getProperty(AAF_LOCATE_URL, null))!=null)) { - StringBuilder sb = new StringBuilder(replacement); - if(!replacement.endsWith("/locate")) { - sb.append("/locate"); - } - sb.append(_url,idxAAFLocateUrl+AAF_LOCATE_URL_TAG.length(),_url.length()); - url = sb.toString(); - } - - try { - Class lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF); - if(lcls==null) { - throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator"); - } - // First check for preloaded - try { - Method meth = lcls.getMethod("create",String.class); - locator = (Locator)meth.invoke(null,url); - } catch (Exception e) { - access.log(Level.INIT, e); - } - if(locator==null) { - URI locatorURI = new URI(url); - Constructor cnst = lcls.getConstructor(SecurityInfoC.class,URI.class); - locator = (Locator)cnst.newInstance(new Object[] {si,locatorURI}); - int port = locatorURI.getPort(); - String portS = port<0?"":(":"+locatorURI.getPort()); - - access.log(Level.INFO, "AAFLocator enabled using " + locatorURI.getScheme() +"://"+locatorURI.getHost() + portS); - } else { - access.log(Level.INFO, "AAFLocator enabled using preloaded " + locator.getClass().getSimpleName()); - } - } catch (InvocationTargetException e) { - if(e.getTargetException() instanceof LocatorException) { - throw (LocatorException)e.getTargetException(); - } - access.log(Level.INIT,e.getTargetException().getMessage(),"AAFLocator for",url,"could not be created.",e); - } catch (Exception e) { - access.log(Level.INIT,"AAFLocator for",url,"could not be created.",e); - } - } - return locator; - } - - // Set by CSP, or is hostname. - public static String getDefaultRealm() { - return defaultRealm; - } + + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA," + + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA," + + "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_ECDH_ECDSA_WITH_RC4_128_SHA," + + "TLS_ECDH_RSA_WITH_RC4_128_SHA,TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA," + + "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,TLS_EMPTY_RENEGOTIATION_INFO_SCSV"; + + + public static final String LOCALHOST_ALLOW = "localhost_allow"; + public static final String LOCALHOST_DENY = "localhost_deny"; + + public static final String BASIC_REALM = "basic_realm"; // what is sent to the client + public static final String BASIC_WARN = "basic_warn"; // Warning of insecure channel + public static final String USERS = "local_users"; + public static final String GROUPS = "local_groups"; + public static final String WRITE_TO = "local_writeto"; // dump RBAC to local file in Tomcat Style (some apps use) + + public static final String OAUTH_CLIENT_ID="client_id"; + public static final String OAUTH_CLIENT_SECRET="client_secret"; + + public static final String AAF_ENV = "aaf_env"; + public static final String AAF_ROOT_NS = "aaf_root_ns"; + public static final String AAF_ROOT_NS_DEF = "org.osaaf.aaf"; + public static final String AAF_ROOT_COMPANY = "aaf_root_company"; + public static final String AAF_LOCATE_URL = "aaf_locate_url"; //URL for AAF locator + private static final String AAF_LOCATE_URL_TAG = "AAF_LOCATE_URL"; // Name of Above for use in Config Variables. + public static final String AAF_DEFAULT_VERSION = "2.1"; + public static final String AAF_URL = "aaf_url"; //URL for AAF... Use to trigger AAF configuration + public static final String AAF_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.service:" + AAF_DEFAULT_VERSION; + public static final String GUI_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.gui:" + AAF_DEFAULT_VERSION; + public static final String CM_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.cm:" + AAF_DEFAULT_VERSION; + public static final String FS_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.fs:" + AAF_DEFAULT_VERSION; + public static final String HELLO_URL_DEF = "https://AAF_LOCATE_URL/AAF_NS.hello:" + AAF_DEFAULT_VERSION; + public static final String OAUTH2_TOKEN_URL = "https://AAF_LOCATE_URL/AAF_NS.token:" + AAF_DEFAULT_VERSION; + public static final String OAUTH2_INTROSPECT_URL = "https://AAF_LOCATE_URL/AAF_NS.introspect:" + AAF_DEFAULT_VERSION; + + public static final String AAF_REGISTER_AS = "aaf_register_as"; + public static final String AAF_APPID = "aaf_id"; + public static final String AAF_APPPASS = "aaf_password"; + public static final String AAF_LUR_CLASS = "aaf_lur_class"; + public static final String AAF_TAF_CLASS = "aaf_taf_class"; + public static final String AAF_CONNECTOR_CLASS = "aaf_connector_class"; + public static final String AAF_LOCATOR_CLASS = "aaf_locator_class"; + public static final String AAF_CONN_TIMEOUT = "aaf_conn_timeout"; + public static final String AAF_CONN_TIMEOUT_DEF = "3000"; + public static final String AAF_CONN_IDLE_TIMEOUT = "aaf_conn_idle_timeout"; // only for Direct Jetty Access. + public static final String AAF_CONN_IDLE_TIMEOUT_DEF = "10000"; // only for Direct Jetty Access. + + // Default Classes: These are for Class loading to avoid direct compile links + public static final String AAF_TAF_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFTaf"; + public static final String AAF_LOCATOR_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFLocator"; + public static final String CADI_OLUR_CLASS_DEF = "org.onap.aaf.cadi.olur.OLur"; + public static final String CADI_OBASIC_HTTP_TAF_DEF = "org.onap.aaf.cadi.obasic.OBasicHttpTaf"; + public static final String CADI_AAF_CON_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFCon"; + + public static final String AAF_CALL_TIMEOUT = "aaf_timeout"; + public static final String AAF_CALL_TIMEOUT_DEF = "5000"; + public static final String AAF_USER_EXPIRES = "aaf_user_expires"; + public static final String AAF_USER_EXPIRES_DEF = "600000"; // Default is 10 mins + public static final String AAF_CLEAN_INTERVAL = "aaf_clean_interval"; + public static final String AAF_CLEAN_INTERVAL_DEF = "30000"; // Default is 30 seconds + public static final String AAF_REFRESH_TRIGGER_COUNT = "aaf_refresh_trigger_count"; + public static final String AAF_REFRESH_TRIGGER_COUNT_DEF = "3"; // Default is 10 mins + + public static final String AAF_HIGH_COUNT = "aaf_high_count"; + public static final String AAF_HIGH_COUNT_DEF = "1000"; // Default is 1000 entries + public static final String AAF_PERM_MAP = "aaf_perm_map"; + public static final String AAF_COMPONENT = "aaf_component"; + public static final String AAF_CERT_IDS = "aaf_cert_ids"; + public static final String AAF_DEBUG_IDS = "aaf_debug_ids"; // comma delimited + public static final String AAF_DATA_DIR = "aaf_data_dir"; // AAF processes and Components only. + + public static final String GW_URL = "gw_url"; + public static final String CM_URL = "cm_url"; + public static final String CM_TRUSTED_CAS = "cm_trusted_cas"; + + public static final String PATHFILTER_URLPATTERN = "pathfilter_urlpattern"; + public static final String PATHFILTER_STACK = "pathfilter_stack"; + public static final String PATHFILTER_NS = "pathfilter_ns"; + public static final String PATHFILTER_NOT_AUTHORIZED_MSG = "pathfilter_not_authorized_msg"; + + // This one should go unpublic + public static final String AAF_DEFAULT_REALM = "aaf_default_realm"; + private static String defaultRealm="none"; + + public static final String AAF_DOMAIN_SUPPORT = "aaf_domain_support"; + public static final String AAF_DOMAIN_SUPPORT_DEF = ".com:.org"; + + // OAUTH2 + public static final String AAF_OAUTH2_TOKEN_URL = "aaf_oauth2_token_url"; + public static final String AAF_OAUTH2_INTROSPECT_URL = "aaf_oauth2_introspect_url"; + public static final String AAF_ALT_OAUTH2_TOKEN_URL = "aaf_alt_oauth2_token_url"; + public static final String AAF_ALT_OAUTH2_INTROSPECT_URL = "aaf_alt_oauth2_introspect_url"; + public static final String AAF_ALT_OAUTH2_DOMAIN = "aaf_alt_oauth2_domain"; + public static final String AAF_ALT_CLIENT_ID = "aaf_alt_oauth2_client_id"; + public static final String AAF_ALT_CLIENT_SECRET = "aaf_alt_oauth2_client_secret"; + public static final String AAF_OAUTH2_HELLO_URL = "aaf_oauth2_hello_url"; + + private static final String AAF_V2_0_AAF_CON_HTTP = "org.onap.aaf.cadi.aaf.v2_0.AAFConHttp"; + + + public static void setDefaultRealm(Access access) { + try { + defaultRealm = logProp(access,Config.AAF_DEFAULT_REALM, + logProp(access,Config.BASIC_REALM, + logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName()) + ) + ); + } catch (UnknownHostException e) { + access.log(Level.INIT, "Unable to determine Hostname",e); + } + } + + public static HttpTaf configHttpTaf(Connector con, SecurityInfoC si, TrustChecker tc, CredVal up, Lur lur, Object ... additionalTafLurs) throws CadiException, LocatorException { + Access access = si.access; + ///////////////////////////////////////////////////// + // Setup AAFCon for any following + ///////////////////////////////////////////////////// + Class aafConClass = loadClass(access,CADI_AAF_CON_DEF); + Object aafcon = null; + if(con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) { + aafcon = con; + } else if(lur != null) { + Field f; + try { + f = lur.getClass().getField("aaf"); + aafcon = f.get(lur); + } catch (Exception e) { + access.log(Level.INIT, e); + } + } + + boolean hasDirectAAF = hasDirect("DirectAAFLur",additionalTafLurs); + // IMPORTANT! Don't attempt to load AAF Connector if there is no AAF URL + String aafURL = access.getProperty(AAF_URL,null); + if(!hasDirectAAF && aafcon==null && aafURL!=null) { + aafcon = loadAAFConnector(si, aafURL); + } + + HttpTaf taf; + // Setup Host, in case Network reports an unusable Hostname (i.e. VTiers, VPNs, etc) + String hostname = logProp(access, HOSTNAME,null); + if(hostname==null) { + try { + hostname = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e1) { + throw new CadiException("Unable to determine Hostname",e1); + } + } + + access.log(Level.INIT, "Hostname set to",hostname); + // Get appropriate TAFs + ArrayList htlist = new ArrayList<>(); + + ///////////////////////////////////////////////////// + // Add a Denial of Service TAF + // Note: how IPs and IDs are added are up to service type. + // They call "DenialOfServiceTaf.denyIP(String) or denyID(String) + ///////////////////////////////////////////////////// + htlist.add(new DenialOfServiceTaf(access)); + + ///////////////////////////////////////////////////// + // Configure Client Cert TAF + ///////////////////////////////////////////////////// + X509Taf x509TAF = null; + String truststore = logProp(access, CADI_TRUSTSTORE,null); + if(truststore!=null) { + String truststorePwd = access.getProperty(CADI_TRUSTSTORE_PASSWORD,null); + if(truststorePwd!=null) { + if(truststorePwd.startsWith(Symm.ENC)) { + try { + access.decrypt(truststorePwd,false); + } catch (IOException e) { + throw new CadiException(CADI_TRUSTSTORE_PASSWORD + " cannot be decrypted",e); + } + } + try { + x509TAF=new X509Taf(access,lur); + htlist.add(x509TAF); + access.log(Level.INIT,"Certificate Authorization enabled"); + } catch (SecurityException | IllegalArgumentException e) { + access.log(Level.INIT,"AAFListedCertIdentity cannot be instantiated. Certificate Authorization is now disabled",e); + } catch (CertificateException e) { + access.log(Level.INIT,"Certificate Authorization failed, it is disabled",e); + } catch (NoSuchAlgorithmException e) { + access.log(Level.INIT,"Certificate Authorization failed, wrong Security Algorithm",e); + } + } + } else { + access.log(Level.INIT,"Certificate Authorization not enabled"); + } + + ///////////////////////////////////////////////////// + // Configure Basic Auth (local content) + ///////////////////////////////////////////////////// + boolean hasOAuthDirectTAF = hasDirect("DirectOAuthTAF", additionalTafLurs); + String basicRealm = logProp(access, BASIC_REALM,null); + String aafCleanup = logProp(access, AAF_USER_EXPIRES,AAF_USER_EXPIRES_DEF); // Default is 10 mins + long userExp = Long.parseLong(aafCleanup); + boolean basicWarn = "TRUE".equals(access.getProperty(BASIC_WARN,"FALSE")); + + if(!hasDirectAAF) { + HttpTaf aaftaf=null; + if(!hasOAuthDirectTAF) { + if(basicRealm!=null) { + @SuppressWarnings("unchecked") + Class obasicCls = (Class)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF); + if(obasicCls!=null) { + try { + String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null); + String introspecturl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL, null); + if(tokenurl==null || introspecturl==null) { + access.log(Level.INIT,"Both tokenurl and introspecturl are required. Oauth Authorization is disabled."); + } + Constructor obasicConst = obasicCls.getConstructor(PropAccess.class,String.class, String.class, String.class); + htlist.add(obasicConst.newInstance(access,basicRealm,tokenurl,introspecturl)); + access.log(Level.INIT,"Oauth supported Basic Authorization is enabled"); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + access.log(Level.INIT, e); + } + } else if(up!=null) { + access.log(Level.INIT,"Basic Authorization is enabled using realm",basicRealm); + // Allow warning about insecure channel to be turned off + if(!basicWarn) { + access.log(Level.INIT, "WARNING! The basicWarn property has been set to false.", + " There will be no additional warning if Basic Auth is used on an insecure channel"); + } + BasicHttpTaf bht = new BasicHttpTaf(access, up, basicRealm, userExp, basicWarn); + for(Object o : additionalTafLurs) { + if(o instanceof CredValDomain) { + bht.add((CredValDomain)o); + } + } + if(x509TAF!=null) { + x509TAF.add(bht); + } + htlist.add(bht); + access.log(Level.INIT,"Basic Authorization is enabled"); + } + } else { + access.log(Level.INIT,"Local Basic Authorization is disabled. Enable by setting basicRealm="); + } + + ///////////////////////////////////////////////////// + // Configure AAF Driven Basic Auth + ///////////////////////////////////////////////////// + if(aafcon==null) { + access.log(Level.INIT,"AAF Connection (AAFcon) is null. Cannot create an AAF TAF"); + } else if(aafURL==null) { + access.log(Level.INIT,"No AAF URL in properties, Cannot create an AAF TAF"); + } else {// There's an AAF_URL... try to configure an AAF + String aafTafClassName = logProp(access, AAF_TAF_CLASS,AAF_TAF_CLASS_DEF); + // Only 2.0 available at this time + if(AAF_TAF_CLASS_DEF.equals(aafTafClassName)) { + try { + Class aafTafClass = loadClass(access,aafTafClassName); + if(aafTafClass!=null) { + Constructor cstr = aafTafClass.getConstructor(Connector.class,boolean.class,AbsUserCache.class); + if(cstr!=null) { + if(lur instanceof AbsUserCache) { + aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn,lur); + } else { + cstr = aafTafClass.getConstructor(Connector.class,boolean.class); + if(cstr!=null) { + aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn); + } + } + if(aaftaf==null) { + access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured"); + } else { + access.log(Level.INIT,"AAF TAF Configured to ",aafURL); + // Note: will add later, after all others configured + } + } + } else { + access.log(Level.INIT, "There is no AAF TAF class available: %s. AAF TAF not configured.",aafTafClassName); + } + } catch(Exception e) { + access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured",e); + } + } + } + } + + ///////////////////////////////////////////////////// + // Configure OAuth TAF + ///////////////////////////////////////////////////// + if(!hasOAuthDirectTAF) { + String oauthTokenUrl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null); + Class oadtClss; + try { + oadtClss = Class.forName(OAUTH_DIRECT_TAF); + } catch (ClassNotFoundException e1) { + oadtClss = null; + access.log(Level.INIT, e1); + } + if(additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) { + htlist.add((HttpTaf)additionalTafLurs[0]); + String[] array= new String[additionalTafLurs.length-1]; + if(array.length>0) { + System.arraycopy(htlist, 1, array, 0, array.length); + } + additionalTafLurs = array; + access.log(Level.INIT,"OAuth2 Direct is enabled"); + } else if(oauthTokenUrl!=null) { + String oauthIntrospectUrl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null); + @SuppressWarnings("unchecked") + Class oaTCls = (Class)loadClass(access,OAUTH_HTTP_TAF); + if(oaTCls!=null) { + Class oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR); + if(oaTTmgrCls!=null) { + try { + Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class); + Object oaTTmgr = oaTTmgrGI.invoke(null /*this is static method*/,access,oauthTokenUrl,oauthIntrospectUrl); + Constructor oaTConst = oaTCls.getConstructor(Access.class,oaTTmgrCls); + htlist.add(oaTConst.newInstance(access,oaTTmgr)); + access.log(Level.INIT,"OAuth2 TAF is enabled"); + } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) { + access.log(Level.INIT,"OAuth2HttpTaf cannot be instantiated. OAuth2 is disabled",e); + } + } + } + } else { + access.log(Level.INIT,"OAuth TAF is not configured"); + } + } + + ///////////////////////////////////////////////////// + // Adding BasicAuth (AAF) last, after other primary Cookie Based + // Needs to be before Cert... see below + ///////////////////////////////////////////////////// + if(aaftaf!=null) { + htlist.add(aaftaf); + } + } + + ///////////////////////////////////////////////////// + // Any Additional Lurs passed in Constructor + ///////////////////////////////////////////////////// + if(additionalTafLurs!=null) { + for(Object additional : additionalTafLurs) { + if(additional instanceof BasicHttpTaf) { + BasicHttpTaf ht = (BasicHttpTaf)additional; + for(Object cv : additionalTafLurs) { + if(cv instanceof CredValDomain) { + ht.add((CredValDomain)cv); + access.printf(Level.INIT,"%s Authentication is enabled",cv); + } + } + htlist.add(ht); + } else if(additional instanceof HttpTaf) { + HttpTaf ht = (HttpTaf)additional; + htlist.add(ht); + access.printf(Level.INIT,"%s Authentication is enabled",additional.getClass().getSimpleName()); + } else if(hasOAuthDirectTAF) { + Class daupCls; + try { + daupCls = Class.forName("org.onap.aaf.auth.direct.DirectAAFUserPass"); + } catch (ClassNotFoundException e) { + daupCls = null; + access.log(Level.INIT, e); + } + if(daupCls != null && additional.getClass().isAssignableFrom(daupCls)) { + htlist.add(new BasicHttpTaf(access, (CredVal)additional , basicRealm, userExp, basicWarn)); + access.printf(Level.INIT,"Direct BasicAuth Authentication is enabled",additional.getClass().getSimpleName()); + } + } + } + } + + // Add BasicAuth, if any, to x509Taf + if(x509TAF!=null) { + for( HttpTaf ht : htlist) { + if(ht instanceof BasicHttpTaf) { + x509TAF.add((BasicHttpTaf)ht); + } + } + } + ///////////////////////////////////////////////////// + // Create EpiTaf from configured TAFs + ///////////////////////////////////////////////////// + if(htlist.size()==1) { + // just return the one + taf = htlist.get(0); + } else { + HttpTaf[] htarray = new HttpTaf[htlist.size()]; + htlist.toArray(htarray); + Locator locator = loadLocator(si, logProp(access, AAF_LOCATE_URL, null)); + + taf = new HttpEpiTaf(access,locator, tc, htarray); // ok to pass locator == null + String level = logProp(access, CADI_LOGLEVEL, null); + if(level!=null) { + access.setLogLevel(Level.valueOf(level)); + } + } + + return taf; + } + + public static String logProp(Access access,String tag, String def) { + String rv = access.getProperty(tag, def); + if(rv == null) { + access.log(Level.INIT,tag,"is not explicitly set"); + } else { + access.log(Level.INIT,tag,"is set to",rv); + } + return rv; + } + + public static Lur configLur(SecurityInfoC si, Connector con, Object ... additionalTafLurs) throws CadiException { + Access access = si.access; + List lurs = new ArrayList<>(); + + ///////////////////////////////////////////////////// + // Configure a Local Property Based RBAC/LUR + ///////////////////////////////////////////////////// + try { + String users = access.getProperty(USERS,null); + String groups = access.getProperty(GROUPS,null); + + if(groups!=null || users!=null) { + LocalLur ll = new LocalLur(access, users, groups); // note b64==null is ok.. just means no encryption. + lurs.add(ll); + + String writeto = access.getProperty(WRITE_TO,null); + if(writeto!=null) { + String msg = UsersDump.updateUsers(writeto, ll); + if(msg!=null) { + access.log(Level.INIT,"ERROR! Error Updating ",writeto,"with roles and users:",msg); + } + } + } + } catch (IOException e) { + throw new CadiException(e); + } + + ///////////////////////////////////////////////////// + // Configure the OAuth Lur (if any) + ///////////////////////////////////////////////////// + String tokenUrl = logProp(access,AAF_OAUTH2_TOKEN_URL, null); + String introspectUrl = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null); + if(tokenUrl!=null && introspectUrl !=null) { + try { + Class olurCls = loadClass(access, CADI_OLUR_CLASS_DEF); + if(olurCls!=null) { + Constructor olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class); + Lur olur = (Lur)olurCnst.newInstance(access,tokenUrl,introspectUrl); + lurs.add(olur); + access.log(Level.INIT, "OAuth2 LUR enabled"); + } else { + access.log(Level.INIT,"AAF/OAuth LUR plugin is not available."); + } + } catch (NoSuchMethodException| SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + String msg = e.getMessage(); + if(msg==null && e.getCause()!=null) { + msg = e.getCause().getMessage(); + } + access.log(Level.INIT,"AAF/OAuth LUR is not instantiated.",msg,e); + } + } else { + access.log(Level.INIT, "OAuth2 Lur disabled"); + } + + if(con!=null) { // try to reutilize connector + lurs.add(con.newLur()); + } else { + ///////////////////////////////////////////////////// + // Configure the AAF Lur (if any) + ///////////////////////////////////////////////////// + String aafURL = logProp(access,AAF_URL,null); // Trigger Property + String aafEnv = access.getProperty(AAF_ENV,null); + if(aafEnv == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL + int ec = aafURL.indexOf("envContext="); + if(ec>0) { + ec += 11; // length of envContext= + int slash = aafURL.indexOf('/', ec); + if(slash>0) { + aafEnv = aafURL.substring(ec, slash); + ((PropAccess)access).setProperty(AAF_ENV, aafEnv); + access.printf(Level.INIT, "Setting aafEnv to %s from aaf_url value",aafEnv); + } + } + } + + // Don't configure AAF if it is using DirectAccess + if(!hasDirect("DirectAAFLur",additionalTafLurs)) { + if(aafURL==null) { + access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded"); + } else {// There's an AAF_URL... try to configure an AAF + String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM); + ////////////AAF Lur 2.0 ///////////// + if(aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { + try { + Object aafcon = loadAAFConnector(si, aafURL); + if(aafcon==null) { + access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object."); + } else { + Class aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON); + if(aafAbsAAFCon!=null) { + Method mNewLur = aafAbsAAFCon.getMethod("newLur"); + Object aaflur = mNewLur.invoke(aafcon); + + if(aaflur==null) { + access.log(Level.INIT,"ERROR! AAF LUR Failed construction. NOT Configured"); + } else { + access.log(Level.INIT,"AAF LUR Configured to ",aafURL); + lurs.add((Lur)aaflur); + String debugIDs = logProp(access,Config.AAF_DEBUG_IDS, null); + if(debugIDs !=null && aaflur instanceof CachingLur) { + ((CachingLur)aaflur).setDebug(debugIDs); + } + } + } + } + } catch (Exception e) { + access.log(e,"AAF LUR class,",aafLurClassStr,"could not be constructed with given Constructors."); + } + } + } + } + } + + ///////////////////////////////////////////////////// + // Any Additional passed in Constructor + ///////////////////////////////////////////////////// + if(additionalTafLurs!=null) { + for(Object additional : additionalTafLurs) { + if(additional instanceof Lur) { + lurs.add((Lur)additional); + access.log(Level.INIT, additional); + } + } + } + + ///////////////////////////////////////////////////// + // Return a Lur based on how many there are... + ///////////////////////////////////////////////////// + switch(lurs.size()) { + case 0: + access.log(Level.INIT,"WARNING! No CADI LURs configured"); + // Return a NULL Lur that does nothing. + return new NullLur(); + case 1: + return lurs.get(0); // Only one, just return it, save processing + default: + // Multiple Lurs, use EpiLUR to handle + Lur[] la = new Lur[lurs.size()]; + lurs.toArray(la); + return new EpiLur(la); + } + } + + private static boolean hasDirect(String simpleClassName, Object[] additionalTafLurs) { + if(additionalTafLurs!=null) { + for(Object tf : additionalTafLurs) { + if(tf.getClass().getSimpleName().equals(simpleClassName)) { + return true; + } + } + } + return false; + } + + public static Object loadAAFConnector(SecurityInfoC si, String aafURL) { + Access access = si.access; + Object aafcon = null; + Class aafConClass = null; + + try { + if (aafURL!=null) { + String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, AAF_V2_0_AAF_CON_HTTP); + if (AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) { + aafConClass = loadClass(access, AAF_V2_0_AAF_CON_HTTP); + if (aafConClass != null) { + for (Constructor c : aafConClass.getConstructors()) { + List lo = new ArrayList<>(); + for (Class pc : c.getParameterTypes()) { + if (pc.equals(Access.class)) { + lo.add(access); + } else if (pc.equals(Locator.class)) { + lo.add(loadLocator(si, aafURL)); + } + } + if (c.getParameterTypes().length != lo.size()) { + continue; // back to another Constructor + } else { + aafcon = c.newInstance(lo.toArray()); + } + break; + } + } + } + if (aafcon != null) { + String mechid = logProp(access, Config.AAF_APPID, null); + String pass = access.getProperty(Config.AAF_APPPASS, null); + if (mechid != null && pass != null) { + try { + Method basicAuth = aafConClass.getMethod("basicAuth", String.class, String.class); + basicAuth.invoke(aafcon, mechid, pass); + } catch (NoSuchMethodException nsme) { + access.log(Level.NONE, nsme); + // it's ok, don't use + } + } + } + } + } catch (Exception e) { + access.log(e, "AAF Connector could not be constructed with given Constructors."); + } + + return aafcon; + } + + public static Class loadClass(Access access, String className) { + Class cls=null; + try { + cls = access.classLoader().loadClass(className); + } catch (ClassNotFoundException cnfe) { + access.log(Level.NONE, cnfe); + try { + cls = access.getClass().getClassLoader().loadClass(className); + } catch (ClassNotFoundException cnfe2) { + access.log(Level.NONE, cnfe2); + // just return null + } + } + return cls; + } + + @SuppressWarnings("unchecked") + public static Locator loadLocator(SecurityInfoC si, final String _url) throws LocatorException { + Access access = si.access; + Locator locator = null; + if(_url==null) { + access.log(Level.INIT,"No URL passed to 'loadLocator'. Disabled"); + } else { + String url = _url; + String replacement; + int idxAAFLocateUrl; + if((idxAAFLocateUrl=_url.indexOf(AAF_LOCATE_URL_TAG))>0 && ((replacement=access.getProperty(AAF_LOCATE_URL, null))!=null)) { + StringBuilder sb = new StringBuilder(replacement); + if(!replacement.endsWith("/locate")) { + sb.append("/locate"); + } + sb.append(_url,idxAAFLocateUrl+AAF_LOCATE_URL_TAG.length(),_url.length()); + url = sb.toString(); + } + + try { + Class lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF); + if(lcls==null) { + throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator"); + } + // First check for preloaded + try { + Method meth = lcls.getMethod("create",String.class); + locator = (Locator)meth.invoke(null,url); + } catch (Exception e) { + access.log(Level.INIT, e); + } + if(locator==null) { + URI locatorURI = new URI(url); + Constructor cnst = lcls.getConstructor(SecurityInfoC.class,URI.class); + locator = (Locator)cnst.newInstance(new Object[] {si,locatorURI}); + int port = locatorURI.getPort(); + String portS = port<0?"":(":"+locatorURI.getPort()); + + access.log(Level.INFO, "AAFLocator enabled using " + locatorURI.getScheme() +"://"+locatorURI.getHost() + portS); + } else { + access.log(Level.INFO, "AAFLocator enabled using preloaded " + locator.getClass().getSimpleName()); + } + } catch (InvocationTargetException e) { + if(e.getTargetException() instanceof LocatorException) { + throw (LocatorException)e.getTargetException(); + } + access.log(Level.INIT,e.getTargetException().getMessage(),"AAFLocator for",url,"could not be created.",e); + } catch (Exception e) { + access.log(Level.INIT,"AAFLocator for",url,"could not be created.",e); + } + } + return locator; + } + + // Set by CSP, or is hostname. + public static String getDefaultRealm() { + return defaultRealm; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java index dfb7b4d3..56ac4dd5 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java @@ -27,71 +27,71 @@ import org.onap.aaf.cadi.Access; import org.onap.aaf.cadi.Access.Level; public interface Get { - public String get(String name, String def, boolean print); - - - /** - * A class for Getting info out of "JavaBean" format - * @author Jonathan - * - */ - public static class Bean implements Get { - private Object bean; - private Class bc; - private Class[] params; - private Object[] args; - - public Bean(Object bean) { - this.bean = bean; - bc = bean.getClass(); - params = new Class[0]; // note, this will allow to go out of scope after config - args = new Object[0]; - } - - public String get(String name, String def, boolean print) { - String str = null; - String gname = "get"+Character.toUpperCase(name.charAt(0))+name.substring(1); - try { - Method meth = bc.getMethod(gname, params); - Object obj = meth.invoke(bean, args); - str = obj==null?null:obj.toString(); // easy string convert... - } catch (Exception e) { - } - - // Take def if nothing else - if(str==null) { - str = def; - // don't log defaults - } else { - str = str.trim(); // this is vital in Property File based values, as spaces can hide easily - } - // Note: Can't log during configuration - return str; - } - } + public String get(String name, String def, boolean print); + + + /** + * A class for Getting info out of "JavaBean" format + * @author Jonathan + * + */ + public static class Bean implements Get { + private Object bean; + private Class bc; + private Class[] params; + private Object[] args; + + public Bean(Object bean) { + this.bean = bean; + bc = bean.getClass(); + params = new Class[0]; // note, this will allow to go out of scope after config + args = new Object[0]; + } + + public String get(String name, String def, boolean print) { + String str = null; + String gname = "get"+Character.toUpperCase(name.charAt(0))+name.substring(1); + try { + Method meth = bc.getMethod(gname, params); + Object obj = meth.invoke(bean, args); + str = obj==null?null:obj.toString(); // easy string convert... + } catch (Exception e) { + } + + // Take def if nothing else + if(str==null) { + str = def; + // don't log defaults + } else { + str = str.trim(); // this is vital in Property File based values, as spaces can hide easily + } + // Note: Can't log during configuration + return str; + } + } - public static Get NULL = new Get() { - public String get(String name, String def, boolean print) { - return def; - } - }; + public static Get NULL = new Get() { + public String get(String name, String def, boolean print) { + return def; + } + }; - public static class AccessGet implements Get { - private Access access; - public AccessGet(Access access) { - this.access = access; - } - public String get(String name, String def, boolean print) { - String gotten = access.getProperty(name, def); - if(print) { - if(gotten == null) { - access.log(Level.INIT,name, "is not set"); - } else { - access.log(Level.INIT,name, "is set to", gotten); - } - } - return gotten; - } - } + public static class AccessGet implements Get { + private Access access; + public AccessGet(Access access) { + this.access = access; + } + public String get(String name, String def, boolean print) { + String gotten = access.getProperty(name, def); + if(print) { + if(gotten == null) { + access.log(Level.INIT,name, "is not set"); + } else { + access.log(Level.INIT,name, "is set to", gotten); + } + } + return gotten; + } + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java index b44de05f..4655dfa1 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java @@ -24,34 +24,34 @@ package org.onap.aaf.cadi.config; import org.onap.aaf.cadi.PropAccess; public class GetAccess extends PropAccess { - private final Get getter; - - public GetAccess(Get getter) { - super(new String[]{"cadi_prop_files="+getter.get("cadi_prop_files", null, true)}); - this.getter = getter; - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.PropAccess#getProperty(java.lang.String, java.lang.String) - */ - @Override - public String getProperty(String tag, String def) { - String rv; - rv = super.getProperty(tag, null); - if(rv==null && getter!=null) { - rv = getter.get(tag, null, true); - } - return rv==null?def:rv; - } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.PropAccess#getProperty(java.lang.String) - */ - @Override - public String getProperty(String tag) { - return getProperty(tag, null); - } + private final Get getter; + + public GetAccess(Get getter) { + super(new String[]{"cadi_prop_files="+getter.get("cadi_prop_files", null, true)}); + this.getter = getter; + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.PropAccess#getProperty(java.lang.String, java.lang.String) + */ + @Override + public String getProperty(String tag, String def) { + String rv; + rv = super.getProperty(tag, null); + if(rv==null && getter!=null) { + rv = getter.get(tag, null, true); + } + return rv==null?def:rv; + } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.PropAccess#getProperty(java.lang.String) + */ + @Override + public String getProperty(String tag) { + return getProperty(tag, null); + } - public Get get() { - return getter; - } + public Get get() { + return getter; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java index f63de20c..bb9981bf 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java @@ -55,230 +55,230 @@ import org.onap.aaf.cadi.util.MaskFormatException; import org.onap.aaf.cadi.util.NetMask; public class SecurityInfo { - private static final String SECURITY_ALGO = "RSA"; - private static final String HTTPS_PROTOCOLS = "https.protocols"; - private static final String JDK_TLS_CLIENT_PROTOCOLS = "jdk.tls.client.protocols"; + private static final String SECURITY_ALGO = "RSA"; + private static final String HTTPS_PROTOCOLS = "https.protocols"; + private static final String JDK_TLS_CLIENT_PROTOCOLS = "jdk.tls.client.protocols"; - public static final String HTTPS_PROTOCOLS_DEFAULT = "TLSv1.1,TLSv1.2"; - public static final String REGEX_COMMA = "\\s*,\\s*"; - public static final String SSL_KEY_MANAGER_FACTORY_ALGORITHM; - - private SSLSocketFactory socketFactory; - private X509KeyManager[] x509KeyManager; - private X509TrustManager[] x509TrustManager; - public final String defaultAlias; - private NetMask[] trustMasks; - private SSLContext context; - private HostnameVerifier maskHV; - public final Access access; + public static final String HTTPS_PROTOCOLS_DEFAULT = "TLSv1.1,TLSv1.2"; + public static final String REGEX_COMMA = "\\s*,\\s*"; + public static final String SSL_KEY_MANAGER_FACTORY_ALGORITHM; + + private SSLSocketFactory socketFactory; + private X509KeyManager[] x509KeyManager; + private X509TrustManager[] x509TrustManager; + public final String defaultAlias; + private NetMask[] trustMasks; + private SSLContext context; + private HostnameVerifier maskHV; + public final Access access; - // Change Key Algorithms for IBM's VM. Could put in others, if needed. - static { - if ("IBM Corporation".equalsIgnoreCase(System.getProperty("java.vm.vendor"))) { - SSL_KEY_MANAGER_FACTORY_ALGORITHM = "IbmX509"; - } else { - SSL_KEY_MANAGER_FACTORY_ALGORITHM = "SunX509"; - } - } - + // Change Key Algorithms for IBM's VM. Could put in others, if needed. + static { + if ("IBM Corporation".equalsIgnoreCase(System.getProperty("java.vm.vendor"))) { + SSL_KEY_MANAGER_FACTORY_ALGORITHM = "IbmX509"; + } else { + SSL_KEY_MANAGER_FACTORY_ALGORITHM = "SunX509"; + } + } + - public SecurityInfo(final Access access) throws CadiException { - try { - this.access = access; - // reuse DME2 Properties for convenience if specific Properties don't exist - - initializeKeyManager(); - - initializeTrustManager(); - - defaultAlias = access.getProperty(Config.CADI_ALIAS, null); - - initializeTrustMasks(); + public SecurityInfo(final Access access) throws CadiException { + try { + this.access = access; + // reuse DME2 Properties for convenience if specific Properties don't exist + + initializeKeyManager(); + + initializeTrustManager(); + + defaultAlias = access.getProperty(Config.CADI_ALIAS, null); + + initializeTrustMasks(); - String httpsProtocols = Config.logProp(access, Config.CADI_PROTOCOLS, - access.getProperty(HTTPS_PROTOCOLS, HTTPS_PROTOCOLS_DEFAULT) - ); - System.setProperty(HTTPS_PROTOCOLS, httpsProtocols); - System.setProperty(JDK_TLS_CLIENT_PROTOCOLS, httpsProtocols); - if ("1.7".equals(System.getProperty("java.specification.version")) && httpsProtocols.contains("TLSv1.2")) { - System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); - } + String httpsProtocols = Config.logProp(access, Config.CADI_PROTOCOLS, + access.getProperty(HTTPS_PROTOCOLS, HTTPS_PROTOCOLS_DEFAULT) + ); + System.setProperty(HTTPS_PROTOCOLS, httpsProtocols); + System.setProperty(JDK_TLS_CLIENT_PROTOCOLS, httpsProtocols); + if ("1.7".equals(System.getProperty("java.specification.version")) && httpsProtocols.contains("TLSv1.2")) { + System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); + } - context = SSLContext.getInstance("TLS"); - context.init(x509KeyManager, x509TrustManager, null); - SSLContext.setDefault(context); - socketFactory = context.getSocketFactory(); - } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException e) { - throw new CadiException(e); - } - } + context = SSLContext.getInstance("TLS"); + context.init(x509KeyManager, x509TrustManager, null); + SSLContext.setDefault(context); + socketFactory = context.getSocketFactory(); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException e) { + throw new CadiException(e); + } + } - /** - * @return the scf - */ - public SSLSocketFactory getSSLSocketFactory() { - return socketFactory; - } + /** + * @return the scf + */ + public SSLSocketFactory getSSLSocketFactory() { + return socketFactory; + } - public SSLContext getSSLContext() { - return context; - } + public SSLContext getSSLContext() { + return context; + } - /** - * @return the km - */ - public X509KeyManager[] getKeyManagers() { - return x509KeyManager; - } + /** + * @return the km + */ + public X509KeyManager[] getKeyManagers() { + return x509KeyManager; + } - public void checkClientTrusted(X509Certificate[] certarr) throws CertificateException { - for (X509TrustManager xtm : x509TrustManager) { - xtm.checkClientTrusted(certarr, SECURITY_ALGO); - } - } + public void checkClientTrusted(X509Certificate[] certarr) throws CertificateException { + for (X509TrustManager xtm : x509TrustManager) { + xtm.checkClientTrusted(certarr, SECURITY_ALGO); + } + } - public void checkServerTrusted(X509Certificate[] certarr) throws CertificateException { - for (X509TrustManager xtm : x509TrustManager) { - xtm.checkServerTrusted(certarr, SECURITY_ALGO); - } - } + public void checkServerTrusted(X509Certificate[] certarr) throws CertificateException { + for (X509TrustManager xtm : x509TrustManager) { + xtm.checkServerTrusted(certarr, SECURITY_ALGO); + } + } - public void setSocketFactoryOn(HttpsURLConnection hsuc) { - hsuc.setSSLSocketFactory(socketFactory); - if (maskHV != null && !maskHV.equals(hsuc.getHostnameVerifier())) { - hsuc.setHostnameVerifier(maskHV); - } - } - - protected void initializeKeyManager() throws CadiException, IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException { - String keyStore = access.getProperty(Config.CADI_KEYSTORE, null); - if (keyStore != null && !new File(keyStore).exists()) { - throw new CadiException(keyStore + " does not exist"); - } + public void setSocketFactoryOn(HttpsURLConnection hsuc) { + hsuc.setSSLSocketFactory(socketFactory); + if (maskHV != null && !maskHV.equals(hsuc.getHostnameVerifier())) { + hsuc.setHostnameVerifier(maskHV); + } + } + + protected void initializeKeyManager() throws CadiException, IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException { + String keyStore = access.getProperty(Config.CADI_KEYSTORE, null); + if (keyStore != null && !new File(keyStore).exists()) { + throw new CadiException(keyStore + " does not exist"); + } - String keyStorePasswd = access.getProperty(Config.CADI_KEYSTORE_PASSWORD, null); - keyStorePasswd = (keyStorePasswd == null) ? null : access.decrypt(keyStorePasswd, false); - if (keyStore == null || keyStorePasswd == null) { - x509KeyManager = new X509KeyManager[0]; - return; - } + String keyStorePasswd = access.getProperty(Config.CADI_KEYSTORE_PASSWORD, null); + keyStorePasswd = (keyStorePasswd == null) ? null : access.decrypt(keyStorePasswd, false); + if (keyStore == null || keyStorePasswd == null) { + x509KeyManager = new X509KeyManager[0]; + return; + } - String keyPasswd = access.getProperty(Config.CADI_KEY_PASSWORD, null); - keyPasswd = (keyPasswd == null) ? keyStorePasswd : access.decrypt(keyPasswd, false); + String keyPasswd = access.getProperty(Config.CADI_KEY_PASSWORD, null); + keyPasswd = (keyPasswd == null) ? keyStorePasswd : access.decrypt(keyPasswd, false); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(SSL_KEY_MANAGER_FACTORY_ALGORITHM); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(SSL_KEY_MANAGER_FACTORY_ALGORITHM); - ArrayList keyManagers = new ArrayList<>(); - File file; - for (String ksname : keyStore.split(REGEX_COMMA)) { - String keystoreFormat; - if (ksname.endsWith(".p12") || ksname.endsWith(".pkcs12")) { - keystoreFormat = "PKCS12"; - } else { - keystoreFormat = "JKS"; - } + ArrayList keyManagers = new ArrayList<>(); + File file; + for (String ksname : keyStore.split(REGEX_COMMA)) { + String keystoreFormat; + if (ksname.endsWith(".p12") || ksname.endsWith(".pkcs12")) { + keystoreFormat = "PKCS12"; + } else { + keystoreFormat = "JKS"; + } - file = new File(ksname); - if (file.exists()) { - FileInputStream fis = new FileInputStream(file); - try { - KeyStore ks = KeyStore.getInstance(keystoreFormat); - ks.load(fis, keyStorePasswd.toCharArray()); - keyManagerFactory.init(ks, keyPasswd.toCharArray()); - } finally { - fis.close(); - } - } - } - for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) { - if (keyManager instanceof X509KeyManager) { - keyManagers.add((X509KeyManager)keyManager); - } - } - x509KeyManager = new X509KeyManager[keyManagers.size()]; - keyManagers.toArray(x509KeyManager); - } + file = new File(ksname); + if (file.exists()) { + FileInputStream fis = new FileInputStream(file); + try { + KeyStore ks = KeyStore.getInstance(keystoreFormat); + ks.load(fis, keyStorePasswd.toCharArray()); + keyManagerFactory.init(ks, keyPasswd.toCharArray()); + } finally { + fis.close(); + } + } + } + for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) { + if (keyManager instanceof X509KeyManager) { + keyManagers.add((X509KeyManager)keyManager); + } + } + x509KeyManager = new X509KeyManager[keyManagers.size()]; + keyManagers.toArray(x509KeyManager); + } - protected void initializeTrustManager() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, CadiException { - String trustStore = access.getProperty(Config.CADI_TRUSTSTORE, null); - if (trustStore != null && !new File(trustStore).exists()) { - throw new CadiException(trustStore + " does not exist"); - } + protected void initializeTrustManager() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, CadiException { + String trustStore = access.getProperty(Config.CADI_TRUSTSTORE, null); + if (trustStore != null && !new File(trustStore).exists()) { + throw new CadiException(trustStore + " does not exist"); + } - if (trustStore == null) { - return; - } + if (trustStore == null) { + return; + } - String trustStorePasswd = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD, null); - trustStorePasswd = (trustStorePasswd == null) ? "changeit"/*defacto Java Trust Pass*/ : access.decrypt(trustStorePasswd, false); + String trustStorePasswd = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD, null); + trustStorePasswd = (trustStorePasswd == null) ? "changeit"/*defacto Java Trust Pass*/ : access.decrypt(trustStorePasswd, false); - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SSL_KEY_MANAGER_FACTORY_ALGORITHM); - File file; - for (String trustStoreName : trustStore.split(REGEX_COMMA)) { - file = new File(trustStoreName); - if (file.exists()) { - FileInputStream fis = new FileInputStream(file); - try { - KeyStore ts = KeyStore.getInstance("JKS"); - ts.load(fis, trustStorePasswd.toCharArray()); - trustManagerFactory.init(ts); - } finally { - fis.close(); - } - } - } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SSL_KEY_MANAGER_FACTORY_ALGORITHM); + File file; + for (String trustStoreName : trustStore.split(REGEX_COMMA)) { + file = new File(trustStoreName); + if (file.exists()) { + FileInputStream fis = new FileInputStream(file); + try { + KeyStore ts = KeyStore.getInstance("JKS"); + ts.load(fis, trustStorePasswd.toCharArray()); + trustManagerFactory.init(ts); + } finally { + fis.close(); + } + } + } - TrustManager trustManagers[] = trustManagerFactory.getTrustManagers(); - if (trustManagers == null || trustManagers.length == 0) { - return; - } + TrustManager trustManagers[] = trustManagerFactory.getTrustManagers(); + if (trustManagers == null || trustManagers.length == 0) { + return; + } - x509TrustManager = new X509TrustManager[trustManagers.length]; - for (int i = 0; i < trustManagers.length; ++i) { - try { - x509TrustManager[i] = (X509TrustManager)trustManagers[i]; - } catch (ClassCastException e) { - access.log(Level.WARN, "Non X509 TrustManager", x509TrustManager[i].getClass().getName(), "skipped in SecurityInfo"); - } - } - } - - protected void initializeTrustMasks() throws AccessException { - String tips = access.getProperty(Config.CADI_TRUST_MASKS, null); - if (tips == null) { - return; - } + x509TrustManager = new X509TrustManager[trustManagers.length]; + for (int i = 0; i < trustManagers.length; ++i) { + try { + x509TrustManager[i] = (X509TrustManager)trustManagers[i]; + } catch (ClassCastException e) { + access.log(Level.WARN, "Non X509 TrustManager", x509TrustManager[i].getClass().getName(), "skipped in SecurityInfo"); + } + } + } + + protected void initializeTrustMasks() throws AccessException { + String tips = access.getProperty(Config.CADI_TRUST_MASKS, null); + if (tips == null) { + return; + } - access.log(Level.INIT, "Explicitly accepting valid X509s from", tips); - String[] ipsplit = tips.split(REGEX_COMMA); - trustMasks = new NetMask[ipsplit.length]; - for (int i = 0; i < ipsplit.length; ++i) { - try { - trustMasks[i] = new NetMask(ipsplit[i]); - } catch (MaskFormatException e) { - throw new AccessException("Invalid IP Mask in " + Config.CADI_TRUST_MASKS, e); - } - } - - final HostnameVerifier origHV = HttpsURLConnection.getDefaultHostnameVerifier(); - maskHV = new HostnameVerifier() { - @Override - public boolean verify(final String urlHostName, final SSLSession session) { - try { - // This will pick up /etc/host entries as well as DNS - InetAddress ia = InetAddress.getByName(session.getPeerHost()); - for (NetMask tmask : trustMasks) { - if (tmask.isInNet(ia.getHostAddress())) { - return true; - } - } - } catch (UnknownHostException e) { - // It's ok. do normal Verify - } - return origHV.verify(urlHostName, session); - }; - }; - HttpsURLConnection.setDefaultHostnameVerifier(maskHV); - } - + access.log(Level.INIT, "Explicitly accepting valid X509s from", tips); + String[] ipsplit = tips.split(REGEX_COMMA); + trustMasks = new NetMask[ipsplit.length]; + for (int i = 0; i < ipsplit.length; ++i) { + try { + trustMasks[i] = new NetMask(ipsplit[i]); + } catch (MaskFormatException e) { + throw new AccessException("Invalid IP Mask in " + Config.CADI_TRUST_MASKS, e); + } + } + + final HostnameVerifier origHV = HttpsURLConnection.getDefaultHostnameVerifier(); + maskHV = new HostnameVerifier() { + @Override + public boolean verify(final String urlHostName, final SSLSession session) { + try { + // This will pick up /etc/host entries as well as DNS + InetAddress ia = InetAddress.getByName(session.getPeerHost()); + for (NetMask tmask : trustMasks) { + if (tmask.isInNet(ia.getHostAddress())) { + return true; + } + } + } catch (UnknownHostException e) { + // It's ok. do normal Verify + } + return origHV.verify(urlHostName, session); + }; + }; + HttpsURLConnection.setDefaultHostnameVerifier(maskHV); + } + } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java index 8e5faf4c..45e1dd1c 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java @@ -31,64 +31,64 @@ import org.onap.aaf.cadi.SecuritySetter; public class SecurityInfoC extends SecurityInfo { - public static final String DEF_ID = "ID not Set"; - private static Map,SecurityInfoC> sicMap = new HashMap<>(); - public SecuritySetter defSS; + public static final String DEF_ID = "ID not Set"; + private static Map,SecurityInfoC> sicMap = new HashMap<>(); + public SecuritySetter defSS; - public SecurityInfoC(Access access) throws CadiException { - super(access); - defSS = new DEFSS(); - } - - @SuppressWarnings("unchecked") - public static synchronized SecurityInfoC instance(Access access, Class cls) throws CadiException { - SecurityInfoInit sii; - if(cls.isAssignableFrom(HttpURLConnection.class)) { - try { - @SuppressWarnings("rawtypes") - Class initCls = (Class)Class.forName("org.onap.aaf.cadi.http.HSecurityInfoInit"); - sii = initCls.newInstance(); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { - throw new CadiException("CADI using HttpURLConnection requires cadi-client jar",e); - } - } else { - sii = new SecurityInfoInit() { - @Override - public SecuritySetter bestDefault(SecurityInfoC si) throws CadiException { - return new DEFSS(); - } - }; - } - - SecurityInfoC sic = (SecurityInfoC) sicMap.get(cls); - if(sic==null) { - sic = new SecurityInfoC(access); - sic.set(sii.bestDefault(sic)); - sicMap.put(cls, sic); - } - return sic; - } + public SecurityInfoC(Access access) throws CadiException { + super(access); + defSS = new DEFSS(); + } + + @SuppressWarnings("unchecked") + public static synchronized SecurityInfoC instance(Access access, Class cls) throws CadiException { + SecurityInfoInit sii; + if(cls.isAssignableFrom(HttpURLConnection.class)) { + try { + @SuppressWarnings("rawtypes") + Class initCls = (Class)Class.forName("org.onap.aaf.cadi.http.HSecurityInfoInit"); + sii = initCls.newInstance(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { + throw new CadiException("CADI using HttpURLConnection requires cadi-client jar",e); + } + } else { + sii = new SecurityInfoInit() { + @Override + public SecuritySetter bestDefault(SecurityInfoC si) throws CadiException { + return new DEFSS(); + } + }; + } + + SecurityInfoC sic = (SecurityInfoC) sicMap.get(cls); + if(sic==null) { + sic = new SecurityInfoC(access); + sic.set(sii.bestDefault(sic)); + sicMap.put(cls, sic); + } + return sic; + } - public SecurityInfoC set(SecuritySetter defSS) { - this.defSS = defSS; - return this; - } + public SecurityInfoC set(SecuritySetter defSS) { + this.defSS = defSS; + return this; + } - private static class DEFSS implements SecuritySetter { - @Override - public String getID() { - return DEF_ID; - } + private static class DEFSS implements SecuritySetter { + @Override + public String getID() { + return DEF_ID; + } - @Override - public void setSecurity(C client) throws CadiException { - throw new CadiException("No Client Credentials set."); - } + @Override + public void setSecurity(C client) throws CadiException { + throw new CadiException("No Client Credentials set."); + } - @Override - public int setLastResponse(int respCode) { - return 0; - } - }; + @Override + public int setLastResponse(int respCode) { + return 0; + } + }; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoInit.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoInit.java index d77a7196..614f363b 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoInit.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoInit.java @@ -24,5 +24,5 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.SecuritySetter; public interface SecurityInfoInit { - public SecuritySetter bestDefault(SecurityInfoC si) throws CadiException; + public SecuritySetter bestDefault(SecurityInfoC si) throws CadiException; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java index 5aea719e..de25cb7f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java @@ -36,127 +36,127 @@ import org.onap.aaf.cadi.lur.LocalLur; public class UsersDump { - /** - * @param args - */ - public static boolean write(OutputStream os, AbsUserCache lur) { - PrintStream ps; - if(os instanceof PrintStream) { - ps = (PrintStream)os; - } else { - ps = new PrintStream(os); - } - try { - ps.println(""); - ps.println(""); - ps.println(""); + /** + * @param args + */ + public static boolean write(OutputStream os, AbsUserCache lur) { + PrintStream ps; + if(os instanceof PrintStream) { + ps = (PrintStream)os; + } else { + ps = new PrintStream(os); + } + try { + ps.println(""); + ps.println(""); + ps.println(""); - // We loop through Users, but want to write Groups first... therefore, save off print - StringBuilder sb = new StringBuilder(); - - // Obtain all unique role names - HashSet groups = new HashSet<>(); - for(AbsUserCache.DumpInfo di : lur.dumpInfo()) { - sb.append("\n "); + // We loop through Users, but want to write Groups first... therefore, save off print + StringBuilder sb = new StringBuilder(); + + // Obtain all unique role names + HashSet groups = new HashSet<>(); + for(AbsUserCache.DumpInfo di : lur.dumpInfo()) { + sb.append("\n "); - } + } - // Print roles - for(String group : groups) { - ps.print(" "); - } - - ps.println(sb); + // Print roles + for(String group : groups) { + ps.print(" "); + } + + ps.println(sb); - ps.println(""); - ps.flush(); - } catch (Exception t) { - t.printStackTrace(ps); - return false; - } - return true; - } - - /** - * - * Note: This method returns a String if there's an error, or null if ok. - * This unusual style is necessitated by the fact that any Exceptions thrown are likely to - * be unlogged and hidden from view, making debugging almost impossible. - * - * @param writeto - * @param up - * @return - */ - public static String updateUsers(String writeto, LocalLur up) { - // Dump a Tomcat-user.xml lookalike (anywhere) - if(writeto!=null) { - // First read content - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - if(UsersDump.write(baos, up)) { - byte[] postulate = baos.toByteArray(); - // now get contents of file - File file = new File(writeto); - boolean writeIt; - if(file.exists()) { - try { - FileInputStream fis = new FileInputStream(file); - byte[] orig = new byte[(int)file.length()]; - int read; - try { - read = fis.read(orig); - } finally { - fis.close(); - } - if(read<=0) { - writeIt = false; - } else { - // Starting at third "<" ( line) - int startA=0, startB=0; - for(int i=0;startA"); + ps.flush(); + } catch (Exception t) { + t.printStackTrace(ps); + return false; + } + return true; + } + + /** + * + * Note: This method returns a String if there's an error, or null if ok. + * This unusual style is necessitated by the fact that any Exceptions thrown are likely to + * be unlogged and hidden from view, making debugging almost impossible. + * + * @param writeto + * @param up + * @return + */ + public static String updateUsers(String writeto, LocalLur up) { + // Dump a Tomcat-user.xml lookalike (anywhere) + if(writeto!=null) { + // First read content + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + if(UsersDump.write(baos, up)) { + byte[] postulate = baos.toByteArray(); + // now get contents of file + File file = new File(writeto); + boolean writeIt; + if(file.exists()) { + try { + FileInputStream fis = new FileInputStream(file); + byte[] orig = new byte[(int)file.length()]; + int read; + try { + read = fis.read(orig); + } finally { + fis.close(); + } + if(read<=0) { + writeIt = false; + } else { + // Starting at third "<" ( line) + int startA=0, startB=0; + for(int i=0;startA value(); + Class value(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java index f72a99bf..0bd87d98 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java @@ -37,62 +37,62 @@ import javax.servlet.http.HttpServletResponse; * */ public class AUTHZServlet implements Servlet { - private String[] roles; - private Servlet delegate; + private String[] roles; + private Servlet delegate; - protected AUTHZServlet(Class cls) { - try { - delegate = cls.newInstance(); - } catch (Exception e) { - delegate = null; - } - RolesAllowed rolesAllowed = cls.getAnnotation(RolesAllowed.class); - if (rolesAllowed == null) { - roles = null; - } else { - roles = rolesAllowed.value(); - } - } - - public void init(ServletConfig sc) throws ServletException { - if (delegate == null) { - throw new ServletException("Invalid Servlet Delegate"); - } - delegate.init(sc); - } - - public ServletConfig getServletConfig() { - return delegate.getServletConfig(); - } + protected AUTHZServlet(Class cls) { + try { + delegate = cls.newInstance(); + } catch (Exception e) { + delegate = null; + } + RolesAllowed rolesAllowed = cls.getAnnotation(RolesAllowed.class); + if (rolesAllowed == null) { + roles = null; + } else { + roles = rolesAllowed.value(); + } + } + + public void init(ServletConfig sc) throws ServletException { + if (delegate == null) { + throw new ServletException("Invalid Servlet Delegate"); + } + delegate.init(sc); + } + + public ServletConfig getServletConfig() { + return delegate.getServletConfig(); + } - public String getServletInfo() { - return delegate.getServletInfo(); - } + public String getServletInfo() { + return delegate.getServletInfo(); + } - public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { - if (roles == null) { - delegate.service(req, resp); - return; - } + public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { + if (roles == null) { + delegate.service(req, resp); + return; + } - // Validate - try { - HttpServletRequest hreq = (HttpServletRequest)req; - for (String role : roles) { - if (hreq.isUserInRole(role)) { - delegate.service(req, resp); - return; - } - } + // Validate + try { + HttpServletRequest hreq = (HttpServletRequest)req; + for (String role : roles) { + if (hreq.isUserInRole(role)) { + delegate.service(req, resp); + return; + } + } - ((HttpServletResponse)resp).sendError(403); // forbidden - } catch (ClassCastException e) { - throw new ServletException("JASPIServlet only supports HTTPServletRequest/HttpServletResponse"); - } - } + ((HttpServletResponse)resp).sendError(403); // forbidden + } catch (ClassCastException e) { + throw new ServletException("JASPIServlet only supports HTTPServletRequest/HttpServletResponse"); + } + } - public void destroy() { - delegate.destroy(); - } + public void destroy() { + delegate.destroy(); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AccessGetter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AccessGetter.java index ab34a0a4..ae4347d3 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AccessGetter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AccessGetter.java @@ -24,12 +24,12 @@ import org.onap.aaf.cadi.Access; import org.onap.aaf.cadi.config.Get; public class AccessGetter implements Get { - private final Access access; - public AccessGetter(Access access) { - this.access = access; - } - public String get(String name, String def, boolean print) { - return access.getProperty(name, def); - } + private final Access access; + public AccessGetter(Access access) { + this.access = access; + } + public String get(String name, String def, boolean print) { + return access.getProperty(name, def); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java index 29234ed7..affb8f96 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java @@ -66,286 +66,286 @@ import org.onap.aaf.cadi.util.Timing; * */ public class CadiFilter implements Filter { - private static CadiHTTPManip httpChecker; - private static String[] pathExceptions; - private static List mapPairs; - private Access access; - private Object[] additionalTafLurs; - private Filter oauthFilter; - private static int count=0; - - public Lur getLur() { - return httpChecker.getLur(); - } - - /** - * Construct a viable Filter - * - * Due to the vagaries of many containers, there is a tendency to create Objects and call "Init" on - * them at a later time. Therefore, this object creates with an object that denies all access - * until appropriate Init happens, just in case the container lets something slip by in the meantime. - * - */ - public CadiFilter() { - additionalTafLurs = CadiHTTPManip.noAdditional; - } + private static CadiHTTPManip httpChecker; + private static String[] pathExceptions; + private static List mapPairs; + private Access access; + private Object[] additionalTafLurs; + private Filter oauthFilter; + private static int count=0; + + public Lur getLur() { + return httpChecker.getLur(); + } + + /** + * Construct a viable Filter + * + * Due to the vagaries of many containers, there is a tendency to create Objects and call "Init" on + * them at a later time. Therefore, this object creates with an object that denies all access + * until appropriate Init happens, just in case the container lets something slip by in the meantime. + * + */ + public CadiFilter() { + additionalTafLurs = CadiHTTPManip.noAdditional; + } - /** - * This constructor to be used when directly constructing and placing in HTTP Engine - * - * @param access - * @param moreTafLurs - * @throws ServletException - */ - public CadiFilter(Access access, Object ... moreTafLurs) throws ServletException { - additionalTafLurs = moreTafLurs; - init(new AccessGetter(this.access = access)); - } + /** + * This constructor to be used when directly constructing and placing in HTTP Engine + * + * @param access + * @param moreTafLurs + * @throws ServletException + */ + public CadiFilter(Access access, Object ... moreTafLurs) throws ServletException { + additionalTafLurs = moreTafLurs; + init(new AccessGetter(this.access = access)); + } - /** - * Use this to pass in a PreContructed CADI Filter, but with initializing... let Servlet do it - * @param init - * @param access - * @param moreTafLurs - * @throws ServletException - */ - public CadiFilter(boolean init, PropAccess access, Object ... moreTafLurs) throws ServletException { - this.access = access; - additionalTafLurs = moreTafLurs; - if(init) { - init(new AccessGetter(access)); - } - } + /** + * Use this to pass in a PreContructed CADI Filter, but with initializing... let Servlet do it + * @param init + * @param access + * @param moreTafLurs + * @throws ServletException + */ + public CadiFilter(boolean init, PropAccess access, Object ... moreTafLurs) throws ServletException { + this.access = access; + additionalTafLurs = moreTafLurs; + if(init) { + init(new AccessGetter(access)); + } + } - /** - * Init - * - * Standard Filter "init" call with FilterConfig to obtain properties. POJOs can construct a - * FilterConfig with the mechanism of their choice, and standard J2EE Servlet engines utilize this - * mechanism already. - */ - //TODO Always validate changes against Tomcat AbsCadiValve and Jaspi CadiSAM Init functions - public void init(FilterConfig filterConfig) throws ServletException { - // need the Context for Logging, instantiating ClassLoader, etc - ServletContextAccess sca=new ServletContextAccess(filterConfig); - if(access==null) { - access = sca; - } - - // Set Protected getter with base Access, for internal class instantiations - init(new FCGet(access, sca.context(), filterConfig)); - } - + /** + * Init + * + * Standard Filter "init" call with FilterConfig to obtain properties. POJOs can construct a + * FilterConfig with the mechanism of their choice, and standard J2EE Servlet engines utilize this + * mechanism already. + */ + //TODO Always validate changes against Tomcat AbsCadiValve and Jaspi CadiSAM Init functions + public void init(FilterConfig filterConfig) throws ServletException { + // need the Context for Logging, instantiating ClassLoader, etc + ServletContextAccess sca=new ServletContextAccess(filterConfig); + if(access==null) { + access = sca; + } + + // Set Protected getter with base Access, for internal class instantiations + init(new FCGet(access, sca.context(), filterConfig)); + } + - @SuppressWarnings("unchecked") - private void init(Get getter) throws ServletException { + @SuppressWarnings("unchecked") + private void init(Get getter) throws ServletException { // Start with the assumption of "Don't trust anyone". - TrustChecker tc = TrustChecker.NOTRUST; // default position - try { - Class ctc = (Class) Class.forName("org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker"); - if(ctc!=null) { - Constructor contc = ctc.getConstructor(Access.class); - if(contc!=null) { - tc = contc.newInstance(access); - } - } - } catch (Exception e) { - access.log(Level.INIT, "AAFTrustChecker cannot be loaded",e.getMessage()); - } - - try { - Class cf=null; - try { - cf= (Class) Class.forName("org.onap.aaf.cadi.oauth.OAuthFilter"); - oauthFilter = cf.newInstance(); - } catch (ClassNotFoundException e) { - oauthFilter = new Filter() { // Null Filter - @Override - public void destroy() { - } - - @Override - public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)throws IOException, ServletException { - chain.doFilter(req, resp); - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - } - }; - } - } catch (Exception e) { - access.log(Level.INIT, "AAFTrustChecker cannot be loaded",e.getMessage()); - } + TrustChecker tc = TrustChecker.NOTRUST; // default position + try { + Class ctc = (Class) Class.forName("org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker"); + if(ctc!=null) { + Constructor contc = ctc.getConstructor(Access.class); + if(contc!=null) { + tc = contc.newInstance(access); + } + } + } catch (Exception e) { + access.log(Level.INIT, "AAFTrustChecker cannot be loaded",e.getMessage()); + } + + try { + Class cf=null; + try { + cf= (Class) Class.forName("org.onap.aaf.cadi.oauth.OAuthFilter"); + oauthFilter = cf.newInstance(); + } catch (ClassNotFoundException e) { + oauthFilter = new Filter() { // Null Filter + @Override + public void destroy() { + } + + @Override + public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)throws IOException, ServletException { + chain.doFilter(req, resp); + } + + @Override + public void init(FilterConfig arg0) throws ServletException { + } + }; + } + } catch (Exception e) { + access.log(Level.INIT, "AAFTrustChecker cannot be loaded",e.getMessage()); + } // Synchronize, because some instantiations call init several times on the same object // In this case, the epiTaf will be changed to a non-NullTaf, and thus not instantiate twice. - synchronized(CadiHTTPManip.noAdditional /*will always remain same Object*/) { - ++count; - if(httpChecker == null) { - if(access==null) { - access = new PropAccess(); - } - try { - httpChecker = new CadiHTTPManip(access,null /*reuseable Con*/,tc, additionalTafLurs); - } catch (CadiException | LocatorException e1) { - throw new ServletException(e1); - } - } else if(access==null) { - access= httpChecker.getAccess(); - } + synchronized(CadiHTTPManip.noAdditional /*will always remain same Object*/) { + ++count; + if(httpChecker == null) { + if(access==null) { + access = new PropAccess(); + } + try { + httpChecker = new CadiHTTPManip(access,null /*reuseable Con*/,tc, additionalTafLurs); + } catch (CadiException | LocatorException e1) { + throw new ServletException(e1); + } + } else if(access==null) { + access= httpChecker.getAccess(); + } - /* - * Setup Authn Path Exceptions - */ - if(pathExceptions==null) { - String str = getter.get(Config.CADI_NOAUTHN, null, true); - if(str!=null) { - pathExceptions = str.split("\\s*:\\s*"); - } - } - - /* - * SETUP Permission Converters... those that can take Strings from a Vendor Product, and convert to appropriate AAF Permissions - */ - if(mapPairs==null) { - String str = getter.get(Config.AAF_PERM_MAP, null, true); - if(str!=null) { - String mstr = getter.get(Config.AAF_PERM_MAP, null, true); - if(mstr!=null) { - String map[] = mstr.split("\\s*:\\s*"); - if(map.length>0) { - MapPermConverter mpc=null; - int idx; - mapPairs = new ArrayList<>(); - for(String entry : map) { - if((idx=entry.indexOf('='))<0) { // it's a Path, so create a new converter - access.log(Level.INIT,"Loading Perm Conversions for:",entry); - mapPairs.add(new Pair(entry,mpc=new MapPermConverter())); - } else { - if(mpc!=null) { - mpc.map().put(entry.substring(0,idx),entry.substring(idx+1)); - } else { - access.log(Level.ERROR,"cadi_perm_map is malformed; ",entry, "is skipped"); - } - } - } - } - } - } - } - } + /* + * Setup Authn Path Exceptions + */ + if(pathExceptions==null) { + String str = getter.get(Config.CADI_NOAUTHN, null, true); + if(str!=null) { + pathExceptions = str.split("\\s*:\\s*"); + } + } + + /* + * SETUP Permission Converters... those that can take Strings from a Vendor Product, and convert to appropriate AAF Permissions + */ + if(mapPairs==null) { + String str = getter.get(Config.AAF_PERM_MAP, null, true); + if(str!=null) { + String mstr = getter.get(Config.AAF_PERM_MAP, null, true); + if(mstr!=null) { + String map[] = mstr.split("\\s*:\\s*"); + if(map.length>0) { + MapPermConverter mpc=null; + int idx; + mapPairs = new ArrayList<>(); + for(String entry : map) { + if((idx=entry.indexOf('='))<0) { // it's a Path, so create a new converter + access.log(Level.INIT,"Loading Perm Conversions for:",entry); + mapPairs.add(new Pair(entry,mpc=new MapPermConverter())); + } else { + if(mpc!=null) { + mpc.map().put(entry.substring(0,idx),entry.substring(idx+1)); + } else { + access.log(Level.ERROR,"cadi_perm_map is malformed; ",entry, "is skipped"); + } + } + } + } + } + } + } + } - // Remove Getter + // Remove Getter getter = Get.NULL; - } + } - /** - * Containers call "destroy" when time to cleanup - */ - public void destroy() { - // Synchronize, in case multiCadiFilters are used. - synchronized(CadiHTTPManip.noAdditional) { - if(--count<=0 && httpChecker!=null) { - httpChecker.destroy(); - httpChecker=null; - access=null; - pathExceptions=null; - } - } - } + /** + * Containers call "destroy" when time to cleanup + */ + public void destroy() { + // Synchronize, in case multiCadiFilters are used. + synchronized(CadiHTTPManip.noAdditional) { + if(--count<=0 && httpChecker!=null) { + httpChecker.destroy(); + httpChecker=null; + access=null; + pathExceptions=null; + } + } + } - /** - * doFilter - * - * This is the standard J2EE invocation. Analyze the request, modify response as necessary, and - * only call the next item in the filterChain if request is suitably Authenticated. - */ - //TODO Always validate changes against Tomcat AbsCadiValve and Jaspi CadiSAM functions - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - final long startAll = System.nanoTime(); - long startCode, startValidate; - float code=0f, validate=0f; - String user = "n/a"; - String tag = ""; - try { - HttpServletRequest hreq = (HttpServletRequest)request; - if(noAuthn(hreq)) { - startCode=System.nanoTime(); - chain.doFilter(request, response); - code = Timing.millis(startCode); - } else { - HttpServletResponse hresp = (HttpServletResponse)response; - startValidate=System.nanoTime(); - TafResp tresp = httpChecker.validate(hreq, hresp, hreq); - validate = Timing.millis(startValidate); - if(tresp.isAuthenticated()==RESP.IS_AUTHENTICATED) { - user = tresp.getPrincipal().personalName(); - tag = tresp.getPrincipal().tag(); - CadiWrap cw = new CadiWrap(hreq, tresp, httpChecker.getLur(),getConverter(hreq)); - if(httpChecker.notCadi(cw, hresp)) { - startCode=System.nanoTime(); - oauthFilter.doFilter(cw,response,chain); - code = Timing.millis(startCode); - } - } - } - } catch (ClassCastException e) { - throw new ServletException("CadiFilter expects Servlet to be an HTTP Servlet",e); - } finally { - access.printf(Level.WARN, "Trans: user=%s[%s],ip=%s,ms=%f,validate=%f,code=%f", - user,tag,request.getRemoteAddr(), - Timing.millis(startAll),validate,code); - } - } + /** + * doFilter + * + * This is the standard J2EE invocation. Analyze the request, modify response as necessary, and + * only call the next item in the filterChain if request is suitably Authenticated. + */ + //TODO Always validate changes against Tomcat AbsCadiValve and Jaspi CadiSAM functions + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + final long startAll = System.nanoTime(); + long startCode, startValidate; + float code=0f, validate=0f; + String user = "n/a"; + String tag = ""; + try { + HttpServletRequest hreq = (HttpServletRequest)request; + if(noAuthn(hreq)) { + startCode=System.nanoTime(); + chain.doFilter(request, response); + code = Timing.millis(startCode); + } else { + HttpServletResponse hresp = (HttpServletResponse)response; + startValidate=System.nanoTime(); + TafResp tresp = httpChecker.validate(hreq, hresp, hreq); + validate = Timing.millis(startValidate); + if(tresp.isAuthenticated()==RESP.IS_AUTHENTICATED) { + user = tresp.getPrincipal().personalName(); + tag = tresp.getPrincipal().tag(); + CadiWrap cw = new CadiWrap(hreq, tresp, httpChecker.getLur(),getConverter(hreq)); + if(httpChecker.notCadi(cw, hresp)) { + startCode=System.nanoTime(); + oauthFilter.doFilter(cw,response,chain); + code = Timing.millis(startCode); + } + } + } + } catch (ClassCastException e) { + throw new ServletException("CadiFilter expects Servlet to be an HTTP Servlet",e); + } finally { + access.printf(Level.WARN, "Trans: user=%s[%s],ip=%s,ms=%f,validate=%f,code=%f", + user,tag,request.getRemoteAddr(), + Timing.millis(startAll),validate,code); + } + } - /** - * If PathExceptions exist, report if these should not have Authn applied. - * @param hreq - * @return - */ - private boolean noAuthn(HttpServletRequest hreq) { - if(pathExceptions!=null) { - String pi = hreq.getPathInfo(); - if(pi==null) return false; // JBoss sometimes leaves null - for(String pe : pathExceptions) { - if(pi.startsWith(pe))return true; - } - } - return false; - } - - /** - * Get Converter by Path - */ - private PermConverter getConverter(HttpServletRequest hreq) { - if(mapPairs!=null) { - String pi = hreq.getPathInfo(); - if(pi !=null) { - for(Pair p: mapPairs) { - if(pi.startsWith(p.name))return p.pc; - } - } - } - return NullPermConverter.singleton(); - } - - /** - * store PermConverters by Path prefix - * @author Jonathan - * - */ - private class Pair { - public Pair(String key, PermConverter pc) { - name = key; - this.pc = pc; - } - public String name; - public PermConverter pc; - } + /** + * If PathExceptions exist, report if these should not have Authn applied. + * @param hreq + * @return + */ + private boolean noAuthn(HttpServletRequest hreq) { + if(pathExceptions!=null) { + String pi = hreq.getPathInfo(); + if(pi==null) return false; // JBoss sometimes leaves null + for(String pe : pathExceptions) { + if(pi.startsWith(pe))return true; + } + } + return false; + } + + /** + * Get Converter by Path + */ + private PermConverter getConverter(HttpServletRequest hreq) { + if(mapPairs!=null) { + String pi = hreq.getPathInfo(); + if(pi !=null) { + for(Pair p: mapPairs) { + if(pi.startsWith(p.name))return p.pc; + } + } + } + return NullPermConverter.singleton(); + } + + /** + * store PermConverters by Path prefix + * @author Jonathan + * + */ + private class Pair { + public Pair(String key, PermConverter pc) { + name = key; + this.pc = pc; + } + public String name; + public PermConverter pc; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java index 9d1653fa..3c0f139b 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java @@ -55,159 +55,159 @@ import org.onap.aaf.cadi.util.UserChainManip; * */ public class CadiHTTPManip { - private static final String ACCESS_CADI_CONTROL = ".access|cadi|control"; - private static final String METH = "OPTIONS"; - private static final String CADI = "/cadi/"; - private static final String CADI_CACHE_PRINT = "/cadi/cache/print"; - private static final String CADI_CACHE_CLEAR = "/cadi/cache/clear"; - private static final String CADI_LOG_SET = "/cadi/log/set/"; - private static final Object LOCK = new Object(); - private Access access; - private HttpTaf taf; - private CredVal up; - private Lur lur; - private String thisPerm,companyPerm,aaf_id; - - public static final Object[] noAdditional = new Object[0]; // CadiFilter can be created each call in some systems + private static final String ACCESS_CADI_CONTROL = ".access|cadi|control"; + private static final String METH = "OPTIONS"; + private static final String CADI = "/cadi/"; + private static final String CADI_CACHE_PRINT = "/cadi/cache/print"; + private static final String CADI_CACHE_CLEAR = "/cadi/cache/clear"; + private static final String CADI_LOG_SET = "/cadi/log/set/"; + private static final Object LOCK = new Object(); + private Access access; + private HttpTaf taf; + private CredVal up; + private Lur lur; + private String thisPerm,companyPerm,aaf_id; + + public static final Object[] noAdditional = new Object[0]; // CadiFilter can be created each call in some systems - public CadiHTTPManip(Access access, Connector con, TrustChecker tc, Object ... additionalTafLurs) throws CadiException, LocatorException { - synchronized(LOCK) { - this.access = access; -// Get getter = new AccessGetter(access); - Config.setDefaultRealm(access); - - aaf_id = access.getProperty(Config.CADI_ALIAS,access.getProperty(Config.AAF_APPID, null)); - if(aaf_id==null) { - access.printf(Level.INIT, "%s is not set. %s can be used instead",Config.AAF_APPID,Config.CADI_ALIAS); - } else { - access.printf(Level.INIT, "%s is set to %s",Config.AAF_APPID,aaf_id); - } - String ns = aaf_id==null?null:UserChainManip.idToNS(aaf_id); - if(ns!=null) { - thisPerm = ns+ACCESS_CADI_CONTROL; - int dot = ns.indexOf('.'); - if(dot>=0) { - int dot2=ns.indexOf('.',dot+1); - if(dot2<0) { - dot2=dot; - } - companyPerm = ns.substring(0, dot2)+ACCESS_CADI_CONTROL; - } else { - companyPerm = "com"+ACCESS_CADI_CONTROL; - } - } else { - thisPerm = companyPerm = "com"+ACCESS_CADI_CONTROL; - } - SecurityInfoC si; - si = SecurityInfoC.instance(access, HttpURLConnection.class); - - lur = Config.configLur(si, con, additionalTafLurs); - - tc.setLur(lur); - if(lur instanceof EpiLur) { - up = ((EpiLur)lur).getUserPassImpl(); - } else if(lur instanceof CredVal) { - up = (CredVal)lur; - } else { - up = null; - } - taf = Config.configHttpTaf(con,si, tc, up, lur, additionalTafLurs); - } - } + public CadiHTTPManip(Access access, Connector con, TrustChecker tc, Object ... additionalTafLurs) throws CadiException, LocatorException { + synchronized(LOCK) { + this.access = access; +// Get getter = new AccessGetter(access); + Config.setDefaultRealm(access); + + aaf_id = access.getProperty(Config.CADI_ALIAS,access.getProperty(Config.AAF_APPID, null)); + if(aaf_id==null) { + access.printf(Level.INIT, "%s is not set. %s can be used instead",Config.AAF_APPID,Config.CADI_ALIAS); + } else { + access.printf(Level.INIT, "%s is set to %s",Config.AAF_APPID,aaf_id); + } + String ns = aaf_id==null?null:UserChainManip.idToNS(aaf_id); + if(ns!=null) { + thisPerm = ns+ACCESS_CADI_CONTROL; + int dot = ns.indexOf('.'); + if(dot>=0) { + int dot2=ns.indexOf('.',dot+1); + if(dot2<0) { + dot2=dot; + } + companyPerm = ns.substring(0, dot2)+ACCESS_CADI_CONTROL; + } else { + companyPerm = "com"+ACCESS_CADI_CONTROL; + } + } else { + thisPerm = companyPerm = "com"+ACCESS_CADI_CONTROL; + } + SecurityInfoC si; + si = SecurityInfoC.instance(access, HttpURLConnection.class); + + lur = Config.configLur(si, con, additionalTafLurs); + + tc.setLur(lur); + if(lur instanceof EpiLur) { + up = ((EpiLur)lur).getUserPassImpl(); + } else if(lur instanceof CredVal) { + up = (CredVal)lur; + } else { + up = null; + } + taf = Config.configHttpTaf(con,si, tc, up, lur, additionalTafLurs); + } + } - public TafResp validate(HttpServletRequest hreq, HttpServletResponse hresp, Object state) throws IOException { - TafResp tresp = taf.validate(Taf.LifeForm.LFN, hreq, hresp); - switch(tresp.isAuthenticated()) { - case IS_AUTHENTICATED: - access.printf(Level.INFO,"Authenticated: %s from %s:%d", - tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); - break; - case TRY_AUTHENTICATING: - switch (tresp.authenticate()) { - case IS_AUTHENTICATED: - access.printf(Level.INFO,"Authenticated: %s from %s:%d", - tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); - break; - case HTTP_REDIRECT_INVOKED: - access.log(Level.INFO,"Authenticating via redirection: ", tresp.desc()); - break; - case NO_FURTHER_PROCESSING: - access.printf(Level.AUDIT,"Authentication Failure: %s from %s:%d" - , tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); - hresp.sendError(403, tresp.desc()); // Forbidden - break; + public TafResp validate(HttpServletRequest hreq, HttpServletResponse hresp, Object state) throws IOException { + TafResp tresp = taf.validate(Taf.LifeForm.LFN, hreq, hresp); + switch(tresp.isAuthenticated()) { + case IS_AUTHENTICATED: + access.printf(Level.INFO,"Authenticated: %s from %s:%d", + tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); + break; + case TRY_AUTHENTICATING: + switch (tresp.authenticate()) { + case IS_AUTHENTICATED: + access.printf(Level.INFO,"Authenticated: %s from %s:%d", + tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); + break; + case HTTP_REDIRECT_INVOKED: + access.log(Level.INFO,"Authenticating via redirection: ", tresp.desc()); + break; + case NO_FURTHER_PROCESSING: + access.printf(Level.AUDIT,"Authentication Failure: %s from %s:%d" + , tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); + hresp.sendError(403, tresp.desc()); // Forbidden + break; - default: - access.printf(Level.AUDIT,"No TAF will authorize for request from %s:%d" - , hreq.getRemoteAddr(), hreq.getRemotePort()); - hresp.sendError(403, tresp.desc()); // Forbidden - } - break; - case NO_FURTHER_PROCESSING: - access.printf(Level.AUDIT,"Authentication Failure: %s from %s:%d", - tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); - hresp.sendError(403, "Access Denied"); // FORBIDDEN - break; - default: - access.printf(Level.AUDIT,"No TAF will authorize for request from %s:%d" - , hreq.getRemoteAddr(), hreq.getRemotePort()); - hresp.sendError(403, "Access Denied"); // FORBIDDEN - } - return tresp; - } - - public boolean notCadi(CadiWrap req, HttpServletResponse resp) { - - String pathInfo = req.getPathInfo(); - if(METH.equalsIgnoreCase(req.getMethod()) && pathInfo!=null && pathInfo.contains(CADI)) { - if(req.getUser().equals(aaf_id) || req.isUserInRole(thisPerm) || req.isUserInRole(companyPerm)) { - try { - if(pathInfo.contains(CADI_CACHE_PRINT)) { - resp.getOutputStream().println(lur.toString()); - resp.setStatus(200); - return false; - } else if(pathInfo.contains(CADI_CACHE_CLEAR)) { - StringBuilder report = new StringBuilder(); - lur.clear(req.getUserPrincipal(), report); - resp.getOutputStream().println(report.toString()); - resp.setStatus(200); - return false; - } else if(pathInfo.contains(CADI_LOG_SET)) { - Level l; - int slash = pathInfo.lastIndexOf('/'); - String level = pathInfo.substring(slash+1); - try { - l = Level.valueOf(level); - access.printf(Level.AUDIT, "%s has set CADI Log Level to '%s'",req.getUser(),l.name()); - access.setLogLevel(l); - } catch (IllegalArgumentException e) { - access.printf(Level.AUDIT, "'%s' is not a valid CADI Log Level",level); - } - return false; - } - } catch (IOException e) { - access.log(e); - } - } - } - return true; - } + default: + access.printf(Level.AUDIT,"No TAF will authorize for request from %s:%d" + , hreq.getRemoteAddr(), hreq.getRemotePort()); + hresp.sendError(403, tresp.desc()); // Forbidden + } + break; + case NO_FURTHER_PROCESSING: + access.printf(Level.AUDIT,"Authentication Failure: %s from %s:%d", + tresp.desc(), hreq.getRemoteAddr(), hreq.getRemotePort()); + hresp.sendError(403, "Access Denied"); // FORBIDDEN + break; + default: + access.printf(Level.AUDIT,"No TAF will authorize for request from %s:%d" + , hreq.getRemoteAddr(), hreq.getRemotePort()); + hresp.sendError(403, "Access Denied"); // FORBIDDEN + } + return tresp; + } + + public boolean notCadi(CadiWrap req, HttpServletResponse resp) { + + String pathInfo = req.getPathInfo(); + if(METH.equalsIgnoreCase(req.getMethod()) && pathInfo!=null && pathInfo.contains(CADI)) { + if(req.getUser().equals(aaf_id) || req.isUserInRole(thisPerm) || req.isUserInRole(companyPerm)) { + try { + if(pathInfo.contains(CADI_CACHE_PRINT)) { + resp.getOutputStream().println(lur.toString()); + resp.setStatus(200); + return false; + } else if(pathInfo.contains(CADI_CACHE_CLEAR)) { + StringBuilder report = new StringBuilder(); + lur.clear(req.getUserPrincipal(), report); + resp.getOutputStream().println(report.toString()); + resp.setStatus(200); + return false; + } else if(pathInfo.contains(CADI_LOG_SET)) { + Level l; + int slash = pathInfo.lastIndexOf('/'); + String level = pathInfo.substring(slash+1); + try { + l = Level.valueOf(level); + access.printf(Level.AUDIT, "%s has set CADI Log Level to '%s'",req.getUser(),l.name()); + access.setLogLevel(l); + } catch (IllegalArgumentException e) { + access.printf(Level.AUDIT, "'%s' is not a valid CADI Log Level",level); + } + return false; + } + } catch (IOException e) { + access.log(e); + } + } + } + return true; + } - public Lur getLur() { - return lur; - } - - public void destroy() { - access.log(Level.INFO,"CadiHttpChecker destroyed."); - if(lur!=null) { - lur.destroy(); - lur=null; - } - } + public Lur getLur() { + return lur; + } + + public void destroy() { + access.log(Level.INFO,"CadiHttpChecker destroyed."); + if(lur!=null) { + lur.destroy(); + lur=null; + } + } - public Access getAccess() { - return access; - } + public Access getAccess() { + return access; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java index 9c4cca10..f56cbf27 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java @@ -33,44 +33,44 @@ import org.onap.aaf.cadi.config.Get; * cleans up the initialization code. */ class FCGet implements Get { - /** - * - */ - private final Access access; - private FilterConfig filterConfig; - private ServletContext context; + /** + * + */ + private final Access access; + private FilterConfig filterConfig; + private ServletContext context; - public FCGet(Access access, ServletContext context, FilterConfig filterConfig) { - this.access = access; - this.context = context; - this.filterConfig = filterConfig; - } + public FCGet(Access access, ServletContext context, FilterConfig filterConfig) { + this.access = access; + this.context = context; + this.filterConfig = filterConfig; + } - public String get(String name, String def, boolean print) { - String str = null; - // Try Server Context First - if(context!=null) { - str = context.getInitParameter(name); - } - - // Try Filter Context next - if(str==null && filterConfig != null) { - str = filterConfig.getInitParameter(name); - } - - if(str==null) { - str = access.getProperty(name, def); - } - // Take def if nothing else - if(str==null) { - str = def; - // don't log defaults - } else { - str = str.trim(); // this is vital in Property File based values, as spaces can hide easily - if(print) { - access.log(Level.INFO,"Setting", name, "to", str); - } - } - return str; - } + public String get(String name, String def, boolean print) { + String str = null; + // Try Server Context First + if(context!=null) { + str = context.getInitParameter(name); + } + + // Try Filter Context next + if(str==null && filterConfig != null) { + str = filterConfig.getInitParameter(name); + } + + if(str==null) { + str = access.getProperty(name, def); + } + // Take def if nothing else + if(str==null) { + str = def; + // don't log defaults + } else { + str = str.trim(); // this is vital in Property File based values, as spaces can hide easily + if(print) { + access.log(Level.INFO,"Setting", name, "to", str); + } + } + return str; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java index f0786b12..7953e076 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java @@ -25,30 +25,30 @@ import java.util.HashMap; import java.util.Map; public class MapPermConverter implements PermConverter { - private HashMap map; + private HashMap map; - /** - * Create with colon separated name value pairs - * i.e. teAdmin=com.att.myNS.myPerm|*|*:teUser=... - * - * @param value - */ - public MapPermConverter() { - map = new HashMap<>(); - } + /** + * Create with colon separated name value pairs + * i.e. teAdmin=com.att.myNS.myPerm|*|*:teUser=... + * + * @param value + */ + public MapPermConverter() { + map = new HashMap<>(); + } - /** - * use to instantiate entries - * - * @return - */ - public Map map() { - return map; - } + /** + * use to instantiate entries + * + * @return + */ + public Map map() { + return map; + } - public String convert(String minimal) { - String rv = map.get(minimal); - return (rv == null) ? minimal : rv; - } + public String convert(String minimal) { + String rv = map.get(minimal); + return (rv == null) ? minimal : rv; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java index 8b70d95d..bb63d097 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java @@ -32,14 +32,14 @@ package org.onap.aaf.cadi.filter; */ public class NullPermConverter implements PermConverter { - private static final NullPermConverter singleton = new NullPermConverter(); + private static final NullPermConverter singleton = new NullPermConverter(); - private NullPermConverter() {} + private NullPermConverter() {} - public static NullPermConverter singleton() { return singleton; } + public static NullPermConverter singleton() { return singleton; } - public String convert(String minimal) { - return minimal; - } + public String convert(String minimal) { + return minimal; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java index cf87c840..f0de0481 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java @@ -48,133 +48,133 @@ import org.onap.aaf.cadi.config.Config; * */ public class PathFilter implements Filter { - private final Log log; - - private ServletContext context; - private String aafType; - private String notAuthorizedMsg; - - /** - * Construct a viable Filter for installing in Container WEB.XML, etc. - * - */ - public PathFilter() { - log = new Log() { - public void info(String ... msg) { - context.log(build("INFO:", msg)); - } - public void audit(String ... msg) { - context.log(build("AUDIT:", msg)); - } - private String build(String type, String []msg) { - StringBuilder sb = new StringBuilder(type); - for (String s : msg) { - sb.append(' '); - sb.append(s); - } - return sb.toString(); - } - }; - } - - /** - * Filter that can be constructed within Java - * @param access - */ - public PathFilter(final Access access) { - log = new Log() { - public void info(String ... msg) { - access.log(Level.INFO, (Object[])msg); - } - public void audit(String ... msg) { - access.log(Level.AUDIT, (Object[])msg); - } - }; - } - - /** - * Init - * - * Standard Filter "init" call with FilterConfig to obtain properties. POJOs can construct a - * FilterConfig with the mechanism of their choice, and standard J2EE Servlet engines utilize this - * mechanism already. - */ - public void init(FilterConfig filterConfig) throws ServletException { - // need the Context for Logging, instantiating ClassLoader, etc - context = filterConfig.getServletContext(); - StringBuilder sb = new StringBuilder(); - StringBuilder err = new StringBuilder(); - Object attr = context.getAttribute(Config.PATHFILTER_NS); - if (attr == null) { - err.append("PathFilter - pathfilter_ns is not set"); - } else { - sb.append(attr.toString()); - } - - attr = context.getAttribute(Config.PATHFILTER_STACK); - if (attr == null) { - log.info("PathFilter - No pathfilter_stack set, ignoring"); - } else { - sb.append('.'); - sb.append(attr.toString()); - } - - attr = context.getAttribute(Config.PATHFILTER_URLPATTERN); - if (attr == null) { - log.info("PathFilter - No pathfilter_urlpattern set, defaulting to 'urlpattern'"); - sb.append(".urlpattern"); - } else { - sb.append('.'); - sb.append(attr.toString()); - } - - log.info("PathFilter - AAF Permission Type is", sb.toString()); - - sb.append('|'); - - aafType = sb.toString(); - - attr = context.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG); - if (attr == null) { - notAuthorizedMsg = "Forbidden - Not Authorized to access this Path"; - } else { - notAuthorizedMsg = attr.toString(); - } - - if (err.length() > 0) { - throw new ServletException(err.toString()); - } - } - - private interface Log { - public void info(String ... msg); - public void audit(String ... msg); - } - - /** - * doFilter - * - * This is the standard J2EE invocation. Analyze the request, modify response as necessary, and - * only call the next item in the filterChain if request is suitably Authenticated. - */ - //TODO Always validate changes against Tomcat AbsCadiValve and Jaspi CadiSAM functions - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - HttpServletRequest hreq = (HttpServletRequest)request; - HttpServletResponse hresp = (HttpServletResponse)response; - String perm = aafType + hreq.getPathInfo() + '|' + hreq.getMethod(); - if (hreq.isUserInRole(perm)) { - chain.doFilter(request, response); - } else { - log.audit("PathFilter has denied", hreq.getUserPrincipal().getName(), "access to", perm); - hresp.sendError(403, notAuthorizedMsg); - } - } - - /** - * Containers call "destroy" when time to cleanup - */ - public void destroy() { - log.info("PathFilter destroyed."); - } + private final Log log; + + private ServletContext context; + private String aafType; + private String notAuthorizedMsg; + + /** + * Construct a viable Filter for installing in Container WEB.XML, etc. + * + */ + public PathFilter() { + log = new Log() { + public void info(String ... msg) { + context.log(build("INFO:", msg)); + } + public void audit(String ... msg) { + context.log(build("AUDIT:", msg)); + } + private String build(String type, String []msg) { + StringBuilder sb = new StringBuilder(type); + for (String s : msg) { + sb.append(' '); + sb.append(s); + } + return sb.toString(); + } + }; + } + + /** + * Filter that can be constructed within Java + * @param access + */ + public PathFilter(final Access access) { + log = new Log() { + public void info(String ... msg) { + access.log(Level.INFO, (Object[])msg); + } + public void audit(String ... msg) { + access.log(Level.AUDIT, (Object[])msg); + } + }; + } + + /** + * Init + * + * Standard Filter "init" call with FilterConfig to obtain properties. POJOs can construct a + * FilterConfig with the mechanism of their choice, and standard J2EE Servlet engines utilize this + * mechanism already. + */ + public void init(FilterConfig filterConfig) throws ServletException { + // need the Context for Logging, instantiating ClassLoader, etc + context = filterConfig.getServletContext(); + StringBuilder sb = new StringBuilder(); + StringBuilder err = new StringBuilder(); + Object attr = context.getAttribute(Config.PATHFILTER_NS); + if (attr == null) { + err.append("PathFilter - pathfilter_ns is not set"); + } else { + sb.append(attr.toString()); + } + + attr = context.getAttribute(Config.PATHFILTER_STACK); + if (attr == null) { + log.info("PathFilter - No pathfilter_stack set, ignoring"); + } else { + sb.append('.'); + sb.append(attr.toString()); + } + + attr = context.getAttribute(Config.PATHFILTER_URLPATTERN); + if (attr == null) { + log.info("PathFilter - No pathfilter_urlpattern set, defaulting to 'urlpattern'"); + sb.append(".urlpattern"); + } else { + sb.append('.'); + sb.append(attr.toString()); + } + + log.info("PathFilter - AAF Permission Type is", sb.toString()); + + sb.append('|'); + + aafType = sb.toString(); + + attr = context.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG); + if (attr == null) { + notAuthorizedMsg = "Forbidden - Not Authorized to access this Path"; + } else { + notAuthorizedMsg = attr.toString(); + } + + if (err.length() > 0) { + throw new ServletException(err.toString()); + } + } + + private interface Log { + public void info(String ... msg); + public void audit(String ... msg); + } + + /** + * doFilter + * + * This is the standard J2EE invocation. Analyze the request, modify response as necessary, and + * only call the next item in the filterChain if request is suitably Authenticated. + */ + //TODO Always validate changes against Tomcat AbsCadiValve and Jaspi CadiSAM functions + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest hreq = (HttpServletRequest)request; + HttpServletResponse hresp = (HttpServletResponse)response; + String perm = aafType + hreq.getPathInfo() + '|' + hreq.getMethod(); + if (hreq.isUserInRole(perm)) { + chain.doFilter(request, response); + } else { + log.audit("PathFilter has denied", hreq.getUserPrincipal().getName(), "access to", perm); + hresp.sendError(403, notAuthorizedMsg); + } + } + + /** + * Containers call "destroy" when time to cleanup + */ + public void destroy() { + log.info("PathFilter destroyed."); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PermConverter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PermConverter.java index bb97894b..dfd0f64b 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PermConverter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PermConverter.java @@ -28,5 +28,5 @@ package org.onap.aaf.cadi.filter; * */ public interface PermConverter { - public String convert(String minimal); + public String convert(String minimal); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/RolesAllowed.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/RolesAllowed.java index 5f709f12..ac61a5c6 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/RolesAllowed.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/RolesAllowed.java @@ -47,10 +47,10 @@ import java.lang.annotation.Target; @Target({TYPE}) @Retention(RUNTIME) public @interface RolesAllowed { - /** - * Security role of the implementation, which doesn't have to be an EJB or CORBA like object. Can be just a - * Handler - * @return - */ - String[] value(); + /** + * Security role of the implementation, which doesn't have to be an EJB or CORBA like object. Can be just a + * Handler + * @return + */ + String[] value(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/ServletImpl.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/ServletImpl.java index 02c2600f..5386eb2d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/ServletImpl.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/ServletImpl.java @@ -47,10 +47,10 @@ import javax.servlet.Servlet; @Target({TYPE}) @Retention(RUNTIME) public @interface ServletImpl { - /** - * Security role of the implementation, which doesn't have to be an EJB or CORBA like object. Can be just a - * Handler - * @return - */ - Class value(); + /** + * Security role of the implementation, which doesn't have to be an EJB or CORBA like object. Can be just a + * Handler + * @return + */ + Class value(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java index 43dd1018..c1b477b1 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java @@ -28,42 +28,42 @@ import org.onap.aaf.cadi.GetCred; import org.onap.aaf.cadi.Symm; public class ConfigPrincipal implements Principal, GetCred { - private String name; - private byte[] cred; - private String content; + private String name; + private byte[] cred; + private String content; - public ConfigPrincipal(String name, String passwd) { - this.name = name; - this.cred = passwd.getBytes(); - content = null; - } + public ConfigPrincipal(String name, String passwd) { + this.name = name; + this.cred = passwd.getBytes(); + content = null; + } - public ConfigPrincipal(String name, byte[] cred) { - this.name = name; - this.cred = cred; - content = null; - } + public ConfigPrincipal(String name, byte[] cred) { + this.name = name; + this.cred = cred; + content = null; + } - public String getName() { - return name; - } - - public byte[] getCred() { - return cred; - } + public String getName() { + return name; + } + + public byte[] getCred() { + return cred; + } - public String toString() { - return name; - } - - public String getAsBasicAuthHeader() throws IOException { - if(content ==null) { - String s = name + ':' + new String(cred); - content = "Basic " + Symm.base64.encode(s); - } else if(!content.startsWith("Basic ")) { // content is the saved password from construction - String s = name + ':' + content; - content = "Basic " + Symm.base64.encode(s); - } - return content; - } + public String toString() { + return name; + } + + public String getAsBasicAuthHeader() throws IOException { + if(content ==null) { + String s = name + ':' + new String(cred); + content = "Basic " + Symm.base64.encode(s); + } else if(!content.startsWith("Basic ")) { // content is the saved password from construction + String s = name + ':' + content; + content = "Basic " + Symm.base64.encode(s); + } + return content; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java index b442c7d9..2c5e1957 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java @@ -46,124 +46,124 @@ import org.onap.aaf.cadi.Permission; * */ public final class EpiLur implements Lur { - private final Lur[] lurs; - - /** - * EpiLur constructor - * - * Construct the EpiLur from variable TAF parameters - * @param lurs - * @throws CadiException - */ - public EpiLur(Lur ... lurs) throws CadiException{ - this.lurs = lurs; - if(lurs.length==0) throw new CadiException("Need at least one Lur implementation in constructor"); - } + private final Lur[] lurs; + + /** + * EpiLur constructor + * + * Construct the EpiLur from variable TAF parameters + * @param lurs + * @throws CadiException + */ + public EpiLur(Lur ... lurs) throws CadiException{ + this.lurs = lurs; + if(lurs.length==0) throw new CadiException("Need at least one Lur implementation in constructor"); + } - public boolean fish(Principal bait, Permission ... pond) { - if(pond==null) { - return false; - } - boolean rv = false; - Lur lur; - for(int i=0;!rv && i permissions) { - for(Lur lur : lurs) { - lur.fishAll(bait, permissions); - } - } + public void fishAll(Principal bait, List permissions) { + for(Lur lur : lurs) { + lur.fishAll(bait, permissions); + } + } - public void destroy() { - for(Lur lur : lurs) { - lur.destroy(); - } - } + public void destroy() { + for(Lur lur : lurs) { + lur.destroy(); + } + } - /** - * Return the first Lur (if any) which also implements UserPass - * @return - */ - public CredVal getUserPassImpl() { - for(Lur lur : lurs) { - if(lur instanceof CredVal) { - return (CredVal)lur; - } - } - return null; - } + /** + * Return the first Lur (if any) which also implements UserPass + * @return + */ + public CredVal getUserPassImpl() { + for(Lur lur : lurs) { + if(lur instanceof CredVal) { + return (CredVal)lur; + } + } + return null; + } - // Never needed... Only EpiLur uses... - public boolean handlesExclusively(Permission ... pond) { - return false; - } - - /** - * Get Lur for index. Returns null if out of range - * @param idx - * @return - */ - public Lur get(int idx) { - if(idx>=0 && idx=0 && idx)l).remove(id); - } - } - } - - public Lur subLur(Class cls ) { - for(Lur l : lurs) { - if(l.getClass().isAssignableFrom(cls)) { - return l; - } - } - return null; - } + public void remove(String id) { + for(Lur l : lurs) { + if(l instanceof CachingLur) { + ((CachingLur)l).remove(id); + } + } + } + + public Lur subLur(Class cls ) { + for(Lur l : lurs) { + if(l.getClass().isAssignableFrom(cls)) { + return l; + } + } + return null; + } - @Override - public Permission createPerm(String p) { - return new LocalPermission(p); - } + @Override + public Permission createPerm(String p) { + return new LocalPermission(p); + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#clear(java.security.Principal, java.lang.StringBuilder) - */ - @Override - public void clear(Principal p, StringBuilder report) { - for(Lur lur : lurs) { - lur.clear(p, report); - } - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - for(Lur lur : lurs) { - sb.append(lur.getClass().getSimpleName()); - sb.append(": Report\n"); - sb.append(lur.toString()); - sb.append('\n'); - } - return sb.toString(); - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#clear(java.security.Principal, java.lang.StringBuilder) + */ + @Override + public void clear(Principal p, StringBuilder report) { + for(Lur lur : lurs) { + lur.clear(p, report); + } + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + for(Lur lur : lurs) { + sb.append(lur.getClass().getSimpleName()); + sb.append(": Report\n"); + sb.append(lur.toString()); + sb.append('\n'); + } + return sb.toString(); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java index e177a22f..d2b6f1aa 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java @@ -45,177 +45,177 @@ import org.onap.aaf.cadi.config.Config; * */ public final class LocalLur extends AbsUserCache implements Lur, CredVal { - public static final String SEMI = "\\s*;\\s*"; - public static final String COLON = "\\s*:\\s*"; - public static final String COMMA = "\\s*,\\s*"; - public static final String PERCENT = "\\s*%\\s*"; - - // Use to quickly determine whether any given group is supported by this LUR - private final Set supportingGroups; - private String supportedRealm; - - /** - * Construct by building structure, see "build" - * - * Reconstruct with "build" - * - * @param userProperties - * @param groupProperties - * @param decryptor - * @throws IOException - */ - public LocalLur(Access access, String userProperties, String groupProperties) throws IOException { - super(access, 0, 0, Integer.MAX_VALUE); // data doesn't expire - supportedRealm = access.getProperty(Config.BASIC_REALM, "localized"); - supportingGroups = new TreeSet<>(); - - if (userProperties != null) { - parseUserProperties(userProperties); - } - - if (groupProperties != null) { - parseGroupProperties(groupProperties); - } - } - - public boolean validate(String user, CredVal.Type type, byte[] cred, Object state) { - if (cred == null) { - return false; - } - User usr = getUser(user, cred); - if (usr == null) { - return false; - } - // covers null as well as bad pass - if ((type == Type.PASSWORD) && (usr.principal instanceof ConfigPrincipal)) {; - return Hash.isEqual(cred, ((ConfigPrincipal)usr.principal).getCred()); - } - return false; - } - - // @Override - public boolean fish(Principal bait, Permission ... pond) { - if (pond == null) { - return false; - } - for(Permission p : pond) { - if (handles(bait) && p instanceof LocalPermission) { // local Users only have LocalPermissions - User user = getUser(bait); - if (user != null) { - return user.contains((LocalPermission)p); - } - } - } - return false; - } - - // We do not want to expose the actual Group, so make a copy. - public void fishAll(Principal bait, List perms) { - if (handles(bait)) { - User user = getUser(bait); - if (user != null) { - user.copyPermsTo(perms); - } - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#handles(java.security.Principal) - */ - @Override - public boolean handles(Principal principal) { - if (principal == null) { - return false; - } - return principal.getName().endsWith(supportedRealm); - } - - @Override - public boolean handlesExclusively(Permission ... pond) { - boolean rv = false; - for (Permission p : pond) { - if(rv=supportingGroups.contains(p.getKey())) { - break; - } - } - return rv; - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) - */ - @Override - public Permission createPerm(String p) { - return new LocalPermission(p); - } - - private void parseUserProperties(String userProperties) throws IOException { - // For each User name... - for (String userProperty : userProperties.trim().split(SEMI)) { - String[] userInfo = userProperty.split(COLON, 2); - String[] userPass = userInfo[0].split(PERCENT, 2); - String userName = userPass[0]; - - byte[] password = null; - if (userPass.length > 1) { - password = access.decrypt(userPass[1], true).getBytes(); - if (userName.indexOf('@') < 0) { - userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm()); - } - } - User usr; - usr = new User<>(new ConfigPrincipal(userName, password)); - addUser(usr); - access.log(Level.INIT, "Local User:", usr.principal); - - if (userInfo.length > 1) { - Map newMap = usr.newMap(); - for (String group : userInfo[1].split(COMMA)) { - supportingGroups.add(group); - usr.add(newMap, new LocalPermission(group)); - } - usr.setMap(newMap); - } - } - } - - - private void parseGroupProperties(String groupProperties) throws IOException { - // For each Group name... - for (String group : groupProperties.trim().split(SEMI)) { - String[] groups = group.split(COLON, 2); - if (groups.length <= 1) { - continue; - } - supportingGroups.add(groups[0]); - LocalPermission p = new LocalPermission(groups[0]); - - // Add all users (known by comma separators) - for (String groupMember : groups[1].split(COMMA)) { - // look for password, if so, put in passMap - String[] userPass = groupMember.split(PERCENT, 2); - String userName = userPass[0]; - if (userName.indexOf('@') < 0) { - userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm()); - } - - User usr = null; - byte[] password = null; - if (userPass.length > 1) { - password = access.decrypt(userPass[1], true).getBytes(); - } - usr = getUser(userName, password); - if (usr == null) { - usr = new User<>(new ConfigPrincipal(userName, password)); - addUser(usr); - } - else { - usr.principal = new ConfigPrincipal(userName, password); - } - usr.add(p); - access.log(Level.INIT, "Local User:", usr.principal); - } - } - } + public static final String SEMI = "\\s*;\\s*"; + public static final String COLON = "\\s*:\\s*"; + public static final String COMMA = "\\s*,\\s*"; + public static final String PERCENT = "\\s*%\\s*"; + + // Use to quickly determine whether any given group is supported by this LUR + private final Set supportingGroups; + private String supportedRealm; + + /** + * Construct by building structure, see "build" + * + * Reconstruct with "build" + * + * @param userProperties + * @param groupProperties + * @param decryptor + * @throws IOException + */ + public LocalLur(Access access, String userProperties, String groupProperties) throws IOException { + super(access, 0, 0, Integer.MAX_VALUE); // data doesn't expire + supportedRealm = access.getProperty(Config.BASIC_REALM, "localized"); + supportingGroups = new TreeSet<>(); + + if (userProperties != null) { + parseUserProperties(userProperties); + } + + if (groupProperties != null) { + parseGroupProperties(groupProperties); + } + } + + public boolean validate(String user, CredVal.Type type, byte[] cred, Object state) { + if (cred == null) { + return false; + } + User usr = getUser(user, cred); + if (usr == null) { + return false; + } + // covers null as well as bad pass + if ((type == Type.PASSWORD) && (usr.principal instanceof ConfigPrincipal)) {; + return Hash.isEqual(cred, ((ConfigPrincipal)usr.principal).getCred()); + } + return false; + } + + // @Override + public boolean fish(Principal bait, Permission ... pond) { + if (pond == null) { + return false; + } + for(Permission p : pond) { + if (handles(bait) && p instanceof LocalPermission) { // local Users only have LocalPermissions + User user = getUser(bait); + if (user != null) { + return user.contains((LocalPermission)p); + } + } + } + return false; + } + + // We do not want to expose the actual Group, so make a copy. + public void fishAll(Principal bait, List perms) { + if (handles(bait)) { + User user = getUser(bait); + if (user != null) { + user.copyPermsTo(perms); + } + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#handles(java.security.Principal) + */ + @Override + public boolean handles(Principal principal) { + if (principal == null) { + return false; + } + return principal.getName().endsWith(supportedRealm); + } + + @Override + public boolean handlesExclusively(Permission ... pond) { + boolean rv = false; + for (Permission p : pond) { + if(rv=supportingGroups.contains(p.getKey())) { + break; + } + } + return rv; + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) + */ + @Override + public Permission createPerm(String p) { + return new LocalPermission(p); + } + + private void parseUserProperties(String userProperties) throws IOException { + // For each User name... + for (String userProperty : userProperties.trim().split(SEMI)) { + String[] userInfo = userProperty.split(COLON, 2); + String[] userPass = userInfo[0].split(PERCENT, 2); + String userName = userPass[0]; + + byte[] password = null; + if (userPass.length > 1) { + password = access.decrypt(userPass[1], true).getBytes(); + if (userName.indexOf('@') < 0) { + userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm()); + } + } + User usr; + usr = new User<>(new ConfigPrincipal(userName, password)); + addUser(usr); + access.log(Level.INIT, "Local User:", usr.principal); + + if (userInfo.length > 1) { + Map newMap = usr.newMap(); + for (String group : userInfo[1].split(COMMA)) { + supportingGroups.add(group); + usr.add(newMap, new LocalPermission(group)); + } + usr.setMap(newMap); + } + } + } + + + private void parseGroupProperties(String groupProperties) throws IOException { + // For each Group name... + for (String group : groupProperties.trim().split(SEMI)) { + String[] groups = group.split(COLON, 2); + if (groups.length <= 1) { + continue; + } + supportingGroups.add(groups[0]); + LocalPermission p = new LocalPermission(groups[0]); + + // Add all users (known by comma separators) + for (String groupMember : groups[1].split(COMMA)) { + // look for password, if so, put in passMap + String[] userPass = groupMember.split(PERCENT, 2); + String userName = userPass[0]; + if (userName.indexOf('@') < 0) { + userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm()); + } + + User usr = null; + byte[] password = null; + if (userPass.length > 1) { + password = access.decrypt(userPass[1], true).getBytes(); + } + usr = getUser(userName, password); + if (usr == null) { + usr = new User<>(new ConfigPrincipal(userName, password)); + addUser(usr); + } + else { + usr.principal = new ConfigPrincipal(userName, password); + } + usr.add(p); + access.log(Level.INIT, "Local User:", usr.principal); + } + } + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalPermission.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalPermission.java index 8d6f9698..ee7bab9c 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalPermission.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalPermission.java @@ -24,27 +24,27 @@ package org.onap.aaf.cadi.lur; import org.onap.aaf.cadi.Permission; public class LocalPermission implements Permission { - private String key; - - public LocalPermission(String role) { - this.key = role; - } - - public String getKey() { - return key; - } + private String key; + + public LocalPermission(String role) { + this.key = role; + } + + public String getKey() { + return key; + } - public String toString() { - return key; - } + public String toString() { + return key; + } - public boolean match(Permission p) { - return key.equals(p.getKey()); - } + public boolean match(Permission p) { + return key.equals(p.getKey()); + } - public String permType() { - return "LOCAL"; - } - - + public String permType() { + return "LOCAL"; + } + + } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/NullLur.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/NullLur.java index b314f20e..fe9bbd30 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/NullLur.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/NullLur.java @@ -28,60 +28,60 @@ import org.onap.aaf.cadi.Lur; import org.onap.aaf.cadi.Permission; public class NullLur implements Lur { - private static final Permission NULL = new Permission() { - @Override - public String permType() { - return ""; - } + private static final Permission NULL = new Permission() { + @Override + public String permType() { + return ""; + } - @Override - public String getKey() { - return ""; - } + @Override + public String getKey() { + return ""; + } - @Override - public boolean match(Permission p) { - return false; - }}; + @Override + public boolean match(Permission p) { + return false; + }}; - public boolean fish(Principal bait, Permission ... pond) { - // Well, for Jenkins, this is ok... It finds out it can't do J2EE Security, and then looks at it's own -// System.err.println("CADI's LUR has not been configured, but is still being called. Access is being denied"); - return false; - } + public boolean fish(Principal bait, Permission ... pond) { + // Well, for Jenkins, this is ok... It finds out it can't do J2EE Security, and then looks at it's own +// System.err.println("CADI's LUR has not been configured, but is still being called. Access is being denied"); + return false; + } - public void fishAll(Principal bait, List permissions) { - } + public void fishAll(Principal bait, List permissions) { + } - public void destroy() { - } + public void destroy() { + } - public boolean handlesExclusively(Permission ... pond) { - return false; - } + public boolean handlesExclusively(Permission ... pond) { + return false; + } - public boolean handles(Principal p) { - return false; - } + public boolean handles(Principal p) { + return false; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) - */ - @Override - public Permission createPerm(String p) { - return NULL; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#createPerm(java.lang.String) + */ + @Override + public Permission createPerm(String p) { + return NULL; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.Lur#clear(java.security.Principal, java.lang.StringBuilder) - */ - @Override - public void clear(Principal p, StringBuilder report) { - report.append(NullLur.class.getSimpleName()); - report.append('\n'); - } - - public String toString() { - return NullLur.class.getSimpleName() + '\n'; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.Lur#clear(java.security.Principal, java.lang.StringBuilder) + */ + @Override + public void clear(Principal p, StringBuilder report) { + report.append(NullLur.class.getSimpleName()); + report.append('\n'); + } + + public String toString() { + return NullLur.class.getSimpleName() + '\n'; + } } \ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java index a235f1d4..d3c1e236 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java @@ -32,102 +32,102 @@ import org.onap.aaf.cadi.GetCred; import org.onap.aaf.cadi.Symm; public class BasicPrincipal extends BearerPrincipal implements GetCred { - private static byte[] basic = "Basic ".getBytes(); + private static byte[] basic = "Basic ".getBytes(); - private String name = null; - private String shortName = null; - private String domain; - private byte[] cred = null; - private long created; + private String name = null; + private String shortName = null; + private String domain; + private byte[] cred = null; + private long created; - public BasicPrincipal(String content,String defaultDomain) throws IOException { - created = System.currentTimeMillis(); - ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes()); - // Read past "Basic ", ensuring it starts with it. - for(int i=0;i0) { - domain=name.substring(at+1); - shortName=name.substring(0, at); - } else { - shortName = name; - domain=defaultDomain; - name = name + '@' + defaultDomain; - } - } - - public BasicPrincipal(BasicCred bc, String domain) { - name = bc.getUser(); - cred = bc.getCred(); - this.domain = domain; - } + public BasicPrincipal(String content,String defaultDomain) throws IOException { + created = System.currentTimeMillis(); + ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes()); + // Read past "Basic ", ensuring it starts with it. + for(int i=0;i0) { + domain=name.substring(at+1); + shortName=name.substring(0, at); + } else { + shortName = name; + domain=defaultDomain; + name = name + '@' + defaultDomain; + } + } + + public BasicPrincipal(BasicCred bc, String domain) { + name = bc.getUser(); + cred = bc.getCred(); + this.domain = domain; + } - private class BasicOS extends OutputStream { - private boolean first = true; - private ByteArrayOutputStream baos; - - public BasicOS(int size) { - baos = new ByteArrayOutputStream(size); - } + private class BasicOS extends OutputStream { + private boolean first = true; + private ByteArrayOutputStream baos; + + public BasicOS(int size) { + baos = new ByteArrayOutputStream(size); + } - @Override - public void write(int b) throws IOException { - if(b==':' && first) { - first = false; - name = new String(baos.toByteArray()); - baos.reset(); // - } else { - baos.write(b); - } - } - - private byte[] toCred() { - return baos.toByteArray(); - } - } - - public String getName() { - return name; - } - - public String getShortName() { - return shortName; - } - - public String getDomain() { - return domain; - } - - public byte[] getCred() { - return cred; - } - - public long created() { - return created; - } + @Override + public void write(int b) throws IOException { + if(b==':' && first) { + first = false; + name = new String(baos.toByteArray()); + baos.reset(); // + } else { + baos.write(b); + } + } + + private byte[] toCred() { + return baos.toByteArray(); + } + } + + public String getName() { + return name; + } + + public String getShortName() { + return shortName; + } + + public String getDomain() { + return domain; + } + + public byte[] getCred() { + return cred; + } + + public long created() { + return created; + } - public String toString() { - return "Basic Authorization for " + name + " evaluated on " + new Date(created).toString(); - } + public String toString() { + return "Basic Authorization for " + name + " evaluated on " + new Date(created).toString(); + } - @Override - public String tag() { - return "BAth"; - } + @Override + public String tag() { + return "BAth"; + } - @Override - public String personalName() { - return name; // personalName not available with Basic Auth - } + @Override + public String personalName() { + return name; // personalName not available with Basic Auth + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BearerPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BearerPrincipal.java index ea0ff2fe..6fdcdc0d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BearerPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BearerPrincipal.java @@ -22,12 +22,12 @@ package org.onap.aaf.cadi.principal; public abstract class BearerPrincipal extends TaggedPrincipal { - private String bearer = null; - public BearerPrincipal setBearer(String bearer) { - this.bearer = bearer; - return this; - } - public String getBearer() { - return bearer; - } + private String bearer = null; + public BearerPrincipal setBearer(String bearer) { + this.bearer = bearer; + return this; + } + public String getBearer() { + return bearer; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java index 68229d3d..f81e160d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java @@ -34,32 +34,32 @@ import org.onap.aaf.cadi.taf.HttpTaf; * */ public class CachedBasicPrincipal extends BasicPrincipal implements CachedPrincipal { - private final HttpTaf creator; - private long timeToLive; - private long expires; + private final HttpTaf creator; + private long timeToLive; + private long expires; - public CachedBasicPrincipal(HttpTaf creator, BasicCred bc, String domain, long timeToLive) { - super(bc, domain); - this.creator = creator; - this.timeToLive = timeToLive; - expires = System.currentTimeMillis()+timeToLive; - } - - public CachedBasicPrincipal(HttpTaf creator, String content, String domain, long timeToLive) throws IOException { - super(content, domain); - this.creator = creator; - this.timeToLive = timeToLive; - expires = System.currentTimeMillis()+timeToLive; - } + public CachedBasicPrincipal(HttpTaf creator, BasicCred bc, String domain, long timeToLive) { + super(bc, domain); + this.creator = creator; + this.timeToLive = timeToLive; + expires = System.currentTimeMillis()+timeToLive; + } + + public CachedBasicPrincipal(HttpTaf creator, String content, String domain, long timeToLive) throws IOException { + super(content, domain); + this.creator = creator; + this.timeToLive = timeToLive; + expires = System.currentTimeMillis()+timeToLive; + } - public CachedPrincipal.Resp revalidate(Object state) { - Resp resp = creator.revalidate(this, state); - if(resp.equals(Resp.REVALIDATED))expires = System.currentTimeMillis()+timeToLive; - return resp; - } + public CachedPrincipal.Resp revalidate(Object state) { + Resp resp = creator.revalidate(this, state); + if(resp.equals(Resp.REVALIDATED))expires = System.currentTimeMillis()+timeToLive; + return resp; + } - public long expires() { - return expires; - } + public long expires() { + return expires; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java index bb6dc673..8c75701f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java @@ -24,30 +24,30 @@ package org.onap.aaf.cadi.principal; import java.security.Principal; public class Kind { - public static final char X509 = 'X'; - public static final char OAUTH = 'O'; - public static final char AAF_OAUTH='A'; - public static final char BASIC_AUTH = 'B'; - public static final char UNKNOWN = 'U'; - - - public static char getKind(final Principal principal) { - Principal check; - if(principal instanceof TrustPrincipal) { - check = ((TrustPrincipal)principal).original(); - } else { - check = principal; - } - if(check instanceof X509Principal) { - return X509; - } - if(check instanceof OAuth2FormPrincipal) { - // Note: if AAF, will turn into 'A' - return OAUTH; - } - if(check instanceof BasicPrincipal) { - return BASIC_AUTH; - } - return UNKNOWN; - } + public static final char X509 = 'X'; + public static final char OAUTH = 'O'; + public static final char AAF_OAUTH='A'; + public static final char BASIC_AUTH = 'B'; + public static final char UNKNOWN = 'U'; + + + public static char getKind(final Principal principal) { + Principal check; + if(principal instanceof TrustPrincipal) { + check = ((TrustPrincipal)principal).original(); + } else { + check = principal; + } + if(check instanceof X509Principal) { + return X509; + } + if(check instanceof OAuth2FormPrincipal) { + // Note: if AAF, will turn into 'A' + return OAUTH; + } + if(check instanceof BasicPrincipal) { + return BASIC_AUTH; + } + return UNKNOWN; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java index 1df2bd3e..4d13de87 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java @@ -22,40 +22,40 @@ package org.onap.aaf.cadi.principal; public class OAuth2FormPrincipal extends TaggedPrincipal { - private final String username; - private final String client_id; - - /* - * Note: client_id and username might be the same, if only authenticating the Client_ID - */ - public OAuth2FormPrincipal(final String client_id, final String username) { - this.username = username; - this.client_id = client_id; - } - - @Override - public String getName() { - return username; - } - - public String client_id() { - return client_id; - } + private final String username; + private final String client_id; + + /* + * Note: client_id and username might be the same, if only authenticating the Client_ID + */ + public OAuth2FormPrincipal(final String client_id, final String username) { + this.username = username; + this.client_id = client_id; + } + + @Override + public String getName() { + return username; + } + + public String client_id() { + return client_id; + } - @Override - public String tag() { - return "OAuth"; - } + @Override + public String tag() { + return "OAuth"; + } - @Override - public String personalName() { - if(username!=null && username!=client_id) { - StringBuilder sb = new StringBuilder(); - sb.append(username); - sb.append('|'); - sb.append(client_id); - return sb.toString(); - } - return client_id; - } + @Override + public String personalName() { + if(username!=null && username!=client_id) { + StringBuilder sb = new StringBuilder(); + sb.append(username); + sb.append('|'); + sb.append(client_id); + return sb.toString(); + } + return client_id; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/StringTagLookup.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/StringTagLookup.java index a3927168..04bcf59a 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/StringTagLookup.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/StringTagLookup.java @@ -24,12 +24,12 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.principal.TaggedPrincipal.TagLookup; public class StringTagLookup implements TagLookup { - private String tag; - public StringTagLookup(final String tag) { - this.tag = tag; - } - @Override - public String lookup() throws CadiException { - return tag; - } + private String tag; + public StringTagLookup(final String tag) { + this.tag = tag; + } + @Override + public String lookup() throws CadiException { + return tag; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java index a3b07c6c..9dddcd63 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java @@ -26,35 +26,35 @@ import org.onap.aaf.cadi.CadiException; public abstract class TaggedPrincipal implements Principal { - public TaggedPrincipal() { - tagLookup = null; - } - - public TaggedPrincipal(final TagLookup tl) { - tagLookup = tl; - } - - public abstract String tag(); // String representing what kind of Authentication occurred. - - public interface TagLookup { - public String lookup() throws CadiException; - } - - private TagLookup tagLookup; - - public void setTagLookup(TagLookup tl) { - tagLookup = tl; - } - - public String personalName() { - if(tagLookup == null) { - return getName(); - } - try { - return tagLookup.lookup(); - } catch (CadiException e) { - return getName(); - } - } + public TaggedPrincipal() { + tagLookup = null; + } + + public TaggedPrincipal(final TagLookup tl) { + tagLookup = tl; + } + + public abstract String tag(); // String representing what kind of Authentication occurred. + + public interface TagLookup { + public String lookup() throws CadiException; + } + + private TagLookup tagLookup; + + public void setTagLookup(TagLookup tl) { + tagLookup = tl; + } + + public String personalName() { + if(tagLookup == null) { + return getName(); + } + try { + return tagLookup.lookup(); + } catch (CadiException e) { + return getName(); + } + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java index 09083316..5d4a0586 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java @@ -26,45 +26,45 @@ import java.security.Principal; import org.onap.aaf.cadi.UserChain; public class TrustPrincipal extends BearerPrincipal implements UserChain { - private final String name; - private final Principal original; - private String userChain; - - public TrustPrincipal(final Principal actual, final String asName) { - this.original = actual; - name = asName.trim(); - if(actual instanceof UserChain) { - UserChain uc = (UserChain)actual; - userChain = uc.userChain(); - } else if(actual instanceof TaggedPrincipal) { - userChain=((TaggedPrincipal)actual).tag(); - } else { - userChain = actual.getClass().getSimpleName(); - } - } - - @Override - public String getName() { - return name; - } - - @Override - public String userChain() { - return userChain; - } - - public Principal original() { - return original; - } + private final String name; + private final Principal original; + private String userChain; + + public TrustPrincipal(final Principal actual, final String asName) { + this.original = actual; + name = asName.trim(); + if(actual instanceof UserChain) { + UserChain uc = (UserChain)actual; + userChain = uc.userChain(); + } else if(actual instanceof TaggedPrincipal) { + userChain=((TaggedPrincipal)actual).tag(); + } else { + userChain = actual.getClass().getSimpleName(); + } + } + + @Override + public String getName() { + return name; + } + + @Override + public String userChain() { + return userChain; + } + + public Principal original() { + return original; + } - @Override - public String tag() { - return userChain; - } + @Override + public String tag() { + return userChain; + } - @Override - public String personalName() { - return original.getName() + '[' + userChain + ']'; - } - + @Override + public String personalName() { + return original.getName() + '[' + userChain + ']'; + } + } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/UnAuthPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/UnAuthPrincipal.java index 52f78e80..f0cacd8d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/UnAuthPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/UnAuthPrincipal.java @@ -24,14 +24,14 @@ package org.onap.aaf.cadi.principal; import java.security.Principal; public class UnAuthPrincipal implements Principal { - private String name; - - public UnAuthPrincipal(final String name) { - this.name = name; - } - @Override - public String getName() { - return name; - } + private String name; + + public UnAuthPrincipal(final String name) { + this.name = name; + } + @Override + public String getName() { + return name; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java index 200b8174..1cd114a0 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java @@ -30,83 +30,83 @@ import org.onap.aaf.cadi.GetCred; import org.onap.aaf.cadi.taf.basic.BasicHttpTaf; public class X509Principal extends BearerPrincipal implements GetCred { - private static final Pattern pattern = Pattern.compile("[a-zA-Z0-9]*\\@[a-zA-Z0-9.]*"); - private final X509Certificate cert; - private final String name; - private byte[] content; - private BasicHttpTaf bht; + private static final Pattern pattern = Pattern.compile("[a-zA-Z0-9]*\\@[a-zA-Z0-9.]*"); + private final X509Certificate cert; + private final String name; + private byte[] content; + private BasicHttpTaf bht; - public X509Principal(String identity, X509Certificate cert) { - name = identity; - content = null; - this.cert = cert; - } + public X509Principal(String identity, X509Certificate cert) { + name = identity; + content = null; + this.cert = cert; + } - public X509Principal(String identity, X509Certificate cert, byte[] content, BasicHttpTaf bht) { - name = identity; - this.content = content; - this.cert = cert; - this.bht = bht; - } + public X509Principal(String identity, X509Certificate cert, byte[] content, BasicHttpTaf bht) { + name = identity; + this.content = content; + this.cert = cert; + this.bht = bht; + } - public X509Principal(X509Certificate cert, byte[] content, BasicHttpTaf bht) throws IOException { - this.content=content; - this.cert = cert; - String _name = null; - String subj = cert.getSubjectDN().getName(); - int cn = subj.indexOf("OU="); - if(cn>=0) { - cn+=3; - int space = subj.indexOf(',',cn); - if(space>=0) { - String id = subj.substring(cn, space); - if(pattern.matcher(id).matches()) { - _name = id; - } - } - } - if(_name==null) { - throw new IOException("X509 does not have Identity as CN"); - } - name = _name; - this.bht = bht; - } - - public String getAsHeader() throws IOException { - try { - if(content==null) { - content=cert.getEncoded(); - } - } catch (CertificateEncodingException e) { - throw new IOException(e); - } - return "X509 " + content; - } - - public String toString() { - return "X509 Authentication for " + name; - } + public X509Principal(X509Certificate cert, byte[] content, BasicHttpTaf bht) throws IOException { + this.content=content; + this.cert = cert; + String _name = null; + String subj = cert.getSubjectDN().getName(); + int cn = subj.indexOf("OU="); + if(cn>=0) { + cn+=3; + int space = subj.indexOf(',',cn); + if(space>=0) { + String id = subj.substring(cn, space); + if(pattern.matcher(id).matches()) { + _name = id; + } + } + } + if(_name==null) { + throw new IOException("X509 does not have Identity as CN"); + } + name = _name; + this.bht = bht; + } + + public String getAsHeader() throws IOException { + try { + if(content==null) { + content=cert.getEncoded(); + } + } catch (CertificateEncodingException e) { + throw new IOException(e); + } + return "X509 " + content; + } + + public String toString() { + return "X509 Authentication for " + name; + } - public byte[] getCred() { - try { - return content==null?(content=cert.getEncoded()):content; - } catch (CertificateEncodingException e) { - return null; - } - } + public byte[] getCred() { + try { + return content==null?(content=cert.getEncoded()):content; + } catch (CertificateEncodingException e) { + return null; + } + } - public String getName() { - return name; - } + public String getName() { + return name; + } - @Override - public String tag() { - return "x509"; - } + @Override + public String tag() { + return "x509"; + } - public BasicHttpTaf getBasicHttpTaf() { - return bht; - } + public BasicHttpTaf getBasicHttpTaf() { + return bht; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java index fb54abdb..b3ac0945 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java @@ -35,102 +35,102 @@ import org.onap.aaf.cadi.util.Timing; */ public abstract class AbsTafResp implements TafResp { - protected final Access access; - protected final String tafName; - protected final TaggedPrincipal principal; - protected final String desc; - private float timing; + protected final Access access; + protected final String tafName; + protected final TaggedPrincipal principal; + protected final String desc; + private float timing; - /** - * AbsTafResp - * - * Set and hold - * Description (for logging) - * Principal (as created by derived class) - * Access (for access to underlying container, i.e. for Logging, auditing, ClassLoaders, etc) - * - * @param access - * @param tafname - * @param principal - * @param description - */ - public AbsTafResp(Access access, String tafname, TaggedPrincipal principal, String description) { - this.access = access; - this.tafName = tafname; - this.principal = principal; - this.desc = description; - } + /** + * AbsTafResp + * + * Set and hold + * Description (for logging) + * Principal (as created by derived class) + * Access (for access to underlying container, i.e. for Logging, auditing, ClassLoaders, etc) + * + * @param access + * @param tafname + * @param principal + * @param description + */ + public AbsTafResp(Access access, String tafname, TaggedPrincipal principal, String description) { + this.access = access; + this.tafName = tafname; + this.principal = principal; + this.desc = description; + } - /** - * isValid() - * - * Respond in the affirmative if the TAF was able to Authenticate - */ - public boolean isValid() { - return principal != null; - } + /** + * isValid() + * + * Respond in the affirmative if the TAF was able to Authenticate + */ + public boolean isValid() { + return principal != null; + } - /** - * desc() - * - * Respond with description of response as given by the TAF - */ - public String desc() { - return desc; - } + /** + * desc() + * + * Respond with description of response as given by the TAF + */ + public String desc() { + return desc; + } - /** - * isAuthenticated() - * - * Respond with the TAF's code of whether Authenticated, or suggested next steps - * default is either IS_AUTHENTICATED, or TRY_ANOTHER_TAF. The TAF can overload - * and suggest others, such as "NO_FURTHER_PROCESSING", if it can detect that this - * is some sort of security breach (i.e. Denial of Service) - */ - public RESP isAuthenticated() { - return principal==null?RESP.TRY_ANOTHER_TAF:RESP.IS_AUTHENTICATED; - } + /** + * isAuthenticated() + * + * Respond with the TAF's code of whether Authenticated, or suggested next steps + * default is either IS_AUTHENTICATED, or TRY_ANOTHER_TAF. The TAF can overload + * and suggest others, such as "NO_FURTHER_PROCESSING", if it can detect that this + * is some sort of security breach (i.e. Denial of Service) + */ + public RESP isAuthenticated() { + return principal==null?RESP.TRY_ANOTHER_TAF:RESP.IS_AUTHENTICATED; + } - /** - * getPrincipal() - * - * Return the principal created by the TAF based on Authentication. - * - * Returns "null" if Authentication failed (no principal) - */ - public TaggedPrincipal getPrincipal() { - return principal; - } + /** + * getPrincipal() + * + * Return the principal created by the TAF based on Authentication. + * + * Returns "null" if Authentication failed (no principal) + */ + public TaggedPrincipal getPrincipal() { + return principal; + } - /** - * getAccess() - * - * Get the Access object from the TAF, so that appropriate Logging, etc can be coordinated. - */ - public Access getAccess() { - return access; - } + /** + * getAccess() + * + * Get the Access object from the TAF, so that appropriate Logging, etc can be coordinated. + */ + public Access getAccess() { + return access; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.taf.TafResp#isFailedAttempt() - */ - public boolean isFailedAttempt() { - return false; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.taf.TafResp#isFailedAttempt() + */ + public boolean isFailedAttempt() { + return false; + } - @Override - public float timing() { - return timing; - } - - @Override - public void timing(final long start) { - timing = Timing.millis(start); - } + @Override + public float timing() { + return timing; + } + + @Override + public void timing(final long start) { + timing = Timing.millis(start); + } - @Override - public String taf() { - return tafName; - } + @Override + public String taf() { + return tafName; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java index d772d493..b248e553 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java @@ -36,49 +36,49 @@ import org.onap.aaf.cadi.Taf; * */ public class EpiTaf implements Taf { - private Taf[] tafs; - - /** - * EpiTaf constructor - * - * Construct the EpiTaf from variable TAF parameters - * @param tafs - * @throws CadiException - */ - public EpiTaf(Taf ... tafs) throws CadiException{ - this.tafs = tafs; - if(tafs.length==0) throw new CadiException("Need at least one Taf implementation in constructor"); - } + private Taf[] tafs; + + /** + * EpiTaf constructor + * + * Construct the EpiTaf from variable TAF parameters + * @param tafs + * @throws CadiException + */ + public EpiTaf(Taf ... tafs) throws CadiException{ + this.tafs = tafs; + if(tafs.length==0) throw new CadiException("Need at least one Taf implementation in constructor"); + } - /** - * validate - * - * Respond with the first TAF to authenticate user based on variable info and "LifeForm" (is it - * a human behind an interface, or a server behind a protocol). - * - * If there is no TAF that can authenticate, respond with the first TAF that suggests it can - * establish an Authentication conversation (TRY_AUTHENTICATING). - * - * If no TAF declares either, respond with NullTafResp (which denies all questions) - */ - public TafResp validate(LifeForm reading, String... info) { - TafResp tresp,firstTryAuth=null; - for(Taf taf : tafs) { - tresp = taf.validate(reading, info); - switch(tresp.isAuthenticated()) { - case TRY_ANOTHER_TAF: - break; - case TRY_AUTHENTICATING: - if(firstTryAuth==null)firstTryAuth=tresp; - break; - default: - return tresp; - } - } + /** + * validate + * + * Respond with the first TAF to authenticate user based on variable info and "LifeForm" (is it + * a human behind an interface, or a server behind a protocol). + * + * If there is no TAF that can authenticate, respond with the first TAF that suggests it can + * establish an Authentication conversation (TRY_AUTHENTICATING). + * + * If no TAF declares either, respond with NullTafResp (which denies all questions) + */ + public TafResp validate(LifeForm reading, String... info) { + TafResp tresp,firstTryAuth=null; + for(Taf taf : tafs) { + tresp = taf.validate(reading, info); + switch(tresp.isAuthenticated()) { + case TRY_ANOTHER_TAF: + break; + case TRY_AUTHENTICATING: + if(firstTryAuth==null)firstTryAuth=tresp; + break; + default: + return tresp; + } + } - // No TAFs configured, at this point. It is safer at this point to be "not validated", - // rather than "let it go" - return firstTryAuth == null?NullTafResp.singleton():firstTryAuth; - } + // No TAFs configured, at this point. It is safer at this point to be "not validated", + // rather than "let it go" + return firstTryAuth == null?NullTafResp.singleton():firstTryAuth; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java index 1d7967e3..b0f56603 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java @@ -47,168 +47,168 @@ import org.onap.aaf.cadi.TrustChecker; * */ public class HttpEpiTaf implements HttpTaf { - private HttpTaf[] tafs; - private Access access; - private Locator locator; - private TrustChecker trustChecker; - - /** - * HttpEpiTaf constructor - * - * Construct the HttpEpiTaf from variable Http specific TAF parameters - - * @param tafs - * @throws CadiException - */ - public HttpEpiTaf(Access access, Locator locator, TrustChecker tc, HttpTaf ... tafs) throws CadiException{ - this.tafs = tafs; - this.access = access; - this.locator = locator; - this.trustChecker = tc; - // Establish what Header Property to look for UserChain/Trust Props - - if (tafs.length == 0) { - throw new CadiException("Need at least one HttpTaf implementation in constructor"); - } - } - - /** - * validate - * - * Respond with the first Http specific TAF to authenticate user based on variable info - * and "LifeForm" (is it a human behind a browser, or a server utilizing HTTP Protocol). - * - * If there is no HttpTAF that can authenticate, respond with the first TAF that suggests it can - * establish an Authentication conversation (TRY_AUTHENTICATING) (Examples include a redirect to CSP - * Servers for CSP Cookie, or BasicAuth 401 response, suggesting User/Password for given Realm - * submission - * - * If no TAF declares either, respond with NullTafResp (which denies all questions) - */ - public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { - // Given a LifeForm Neutral, for HTTP, we need to discover true Life-Form Readings - if (reading == LifeForm.LFN) { - reading = tricorderScan(req); - } - TafResp tresp = null; - TafResp firstTry = null; - List redirectables = null; - List log; - if(access.willLog(Level.DEBUG)) { - log = new ArrayList<>(); - } else { - log = null; - } - try { - for (HttpTaf taf : tafs) { - final long start = System.nanoTime(); - tresp = taf.validate(reading, req, resp); - addToLog(log, tresp, start); - switch(tresp.isAuthenticated()) { - case TRY_ANOTHER_TAF: - break; // and loop - case TRY_AUTHENTICATING: - if (tresp instanceof Redirectable) { - if (redirectables == null) { - redirectables = new ArrayList<>(); - } - redirectables.add((Redirectable)tresp); - } else if (firstTry == null) { - firstTry = tresp; - } - break; - case IS_AUTHENTICATED: - tresp = trustChecker.mayTrust(tresp, req); - return tresp; - default: - return tresp; - } - } - } finally { - printLog(log); - } - - // If No TAFs configured, at this point. It is safer at this point to be "not validated", - // rather than "let it go" - // Note: if exists, there will always be more than 0 entries, according to above code - if (redirectables == null) { - return (firstTry != null) ? firstTry : NullTafResp.singleton(); - } - - // If there is one Tryable entry then return it - if (redirectables.size() > 1) { - return LoginPageTafResp.create(access, locator, resp, redirectables); - } else { - return redirectables.get(0); - } - } - - public boolean revalidate(Principal prin) throws Exception { - return false; - } - - /* - * Since this is internal, we use a little Star Trek humor to indicate looking in the HTTP Request to see if we can determine what kind - * of "LifeForm" reading we can determine, i.e. is there a Human (CarbonBasedLifeForm) behind a browser, or is it mechanical - * id (SiliconBasedLifeForm)? This makes a difference in some Authentication, i.e CSP, which doesn't work well for SBLFs - */ - private LifeForm tricorderScan(HttpServletRequest req) { - // For simplicity's sake, we'll say Humans use FQDNs, not IPs. - - // Current guess that only Browsers bother to set "Agent" codes that identify the kind of browser they are. - // If mechanical frameworks are found that populate this, then more advanced analysis may be required - // Jonathan 1/22/2013 - String agent = req.getHeader("User-Agent"); - if (agent != null && agent.startsWith("Mozilla")) { // covers I.E./Firefox/Safari/probably any other "advanced" Browser see http://en.wikipedia.org/wiki/User_agent - return LifeForm.CBLF; - } - return LifeForm.SBLF; // notably skips "curl","wget", (which is desired behavior. We don't want to try CSP, etc on these) - } - - public Resp revalidate(CachedPrincipal prin, Object state) { - Resp resp; - for (HttpTaf taf : tafs) { - resp = taf.revalidate(prin, state); - if (resp != Resp.NOT_MINE) { - return resp; - } -// switch(resp) { -// case NOT_MINE: -// break; -// default: -// return resp; -// } - } - return Resp.NOT_MINE; - } - - private void addToLog(List log, final TafResp tresp, final long start) { - if (log == null) { - return; - } - tresp.timing(start); - log.add(tresp); - } - - private void printLog(List log) { - if (log == null) { - return; - } - for (TafResp tresp : log) { - access.printf(Level.DEBUG, "%s: %s, ms=%f", tresp.taf(), tresp.desc(), tresp.timing()); - } - } - - /** - * List HttpTafs with their "toString" representations... primarily useful for Debugging in an IDE - * like Eclipse. - */ - public String toString() { - StringBuilder sb = new StringBuilder(); - for (HttpTaf ht : tafs) { - sb.append(ht.toString()); - sb.append(". "); - } - return sb.toString(); - } + private HttpTaf[] tafs; + private Access access; + private Locator locator; + private TrustChecker trustChecker; + + /** + * HttpEpiTaf constructor + * + * Construct the HttpEpiTaf from variable Http specific TAF parameters + + * @param tafs + * @throws CadiException + */ + public HttpEpiTaf(Access access, Locator locator, TrustChecker tc, HttpTaf ... tafs) throws CadiException{ + this.tafs = tafs; + this.access = access; + this.locator = locator; + this.trustChecker = tc; + // Establish what Header Property to look for UserChain/Trust Props + + if (tafs.length == 0) { + throw new CadiException("Need at least one HttpTaf implementation in constructor"); + } + } + + /** + * validate + * + * Respond with the first Http specific TAF to authenticate user based on variable info + * and "LifeForm" (is it a human behind a browser, or a server utilizing HTTP Protocol). + * + * If there is no HttpTAF that can authenticate, respond with the first TAF that suggests it can + * establish an Authentication conversation (TRY_AUTHENTICATING) (Examples include a redirect to CSP + * Servers for CSP Cookie, or BasicAuth 401 response, suggesting User/Password for given Realm + * submission + * + * If no TAF declares either, respond with NullTafResp (which denies all questions) + */ + public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { + // Given a LifeForm Neutral, for HTTP, we need to discover true Life-Form Readings + if (reading == LifeForm.LFN) { + reading = tricorderScan(req); + } + TafResp tresp = null; + TafResp firstTry = null; + List redirectables = null; + List log; + if(access.willLog(Level.DEBUG)) { + log = new ArrayList<>(); + } else { + log = null; + } + try { + for (HttpTaf taf : tafs) { + final long start = System.nanoTime(); + tresp = taf.validate(reading, req, resp); + addToLog(log, tresp, start); + switch(tresp.isAuthenticated()) { + case TRY_ANOTHER_TAF: + break; // and loop + case TRY_AUTHENTICATING: + if (tresp instanceof Redirectable) { + if (redirectables == null) { + redirectables = new ArrayList<>(); + } + redirectables.add((Redirectable)tresp); + } else if (firstTry == null) { + firstTry = tresp; + } + break; + case IS_AUTHENTICATED: + tresp = trustChecker.mayTrust(tresp, req); + return tresp; + default: + return tresp; + } + } + } finally { + printLog(log); + } + + // If No TAFs configured, at this point. It is safer at this point to be "not validated", + // rather than "let it go" + // Note: if exists, there will always be more than 0 entries, according to above code + if (redirectables == null) { + return (firstTry != null) ? firstTry : NullTafResp.singleton(); + } + + // If there is one Tryable entry then return it + if (redirectables.size() > 1) { + return LoginPageTafResp.create(access, locator, resp, redirectables); + } else { + return redirectables.get(0); + } + } + + public boolean revalidate(Principal prin) throws Exception { + return false; + } + + /* + * Since this is internal, we use a little Star Trek humor to indicate looking in the HTTP Request to see if we can determine what kind + * of "LifeForm" reading we can determine, i.e. is there a Human (CarbonBasedLifeForm) behind a browser, or is it mechanical + * id (SiliconBasedLifeForm)? This makes a difference in some Authentication, i.e CSP, which doesn't work well for SBLFs + */ + private LifeForm tricorderScan(HttpServletRequest req) { + // For simplicity's sake, we'll say Humans use FQDNs, not IPs. + + // Current guess that only Browsers bother to set "Agent" codes that identify the kind of browser they are. + // If mechanical frameworks are found that populate this, then more advanced analysis may be required + // Jonathan 1/22/2013 + String agent = req.getHeader("User-Agent"); + if (agent != null && agent.startsWith("Mozilla")) { // covers I.E./Firefox/Safari/probably any other "advanced" Browser see http://en.wikipedia.org/wiki/User_agent + return LifeForm.CBLF; + } + return LifeForm.SBLF; // notably skips "curl","wget", (which is desired behavior. We don't want to try CSP, etc on these) + } + + public Resp revalidate(CachedPrincipal prin, Object state) { + Resp resp; + for (HttpTaf taf : tafs) { + resp = taf.revalidate(prin, state); + if (resp != Resp.NOT_MINE) { + return resp; + } +// switch(resp) { +// case NOT_MINE: +// break; +// default: +// return resp; +// } + } + return Resp.NOT_MINE; + } + + private void addToLog(List log, final TafResp tresp, final long start) { + if (log == null) { + return; + } + tresp.timing(start); + log.add(tresp); + } + + private void printLog(List log) { + if (log == null) { + return; + } + for (TafResp tresp : log) { + access.printf(Level.DEBUG, "%s: %s, ms=%f", tresp.taf(), tresp.desc(), tresp.timing()); + } + } + + /** + * List HttpTafs with their "toString" representations... primarily useful for Debugging in an IDE + * like Eclipse. + */ + public String toString() { + StringBuilder sb = new StringBuilder(); + for (HttpTaf ht : tafs) { + sb.append(ht.toString()); + sb.append(". "); + } + return sb.toString(); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpTaf.java index 9484458c..77976ce2 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpTaf.java @@ -38,23 +38,23 @@ import org.onap.aaf.cadi.Taf.LifeForm; * */ public interface HttpTaf { - /** - * validate - * - * Validate the Request, and respond with created TafResp object. - * - * @param reading - * @param req - * @param resp - * @return - */ - public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp); - - /** - * Re-Validate Credential - * - * @param prin - * @return - */ - public CachedPrincipal.Resp revalidate(CachedPrincipal prin,Object state); + /** + * validate + * + * Validate the Request, and respond with created TafResp object. + * + * @param reading + * @param req + * @param resp + * @return + */ + public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp); + + /** + * Re-Validate Credential + * + * @param prin + * @return + */ + public CachedPrincipal.Resp revalidate(CachedPrincipal prin,Object state); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java index c8abec0a..a5ce45b7 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java @@ -33,68 +33,68 @@ import org.onap.aaf.cadi.Access.Level; import org.onap.aaf.cadi.Locator.Item; public class LoginPageTafResp extends AbsTafResp { - private final HttpServletResponse httpResp; - private final String loginPageURL; + private final HttpServletResponse httpResp; + private final String loginPageURL; - private LoginPageTafResp(Access access, final HttpServletResponse resp, String loginPageURL) { - super(access, "LoginPage", null, "Multiple Possible HTTP Logins available. Redirecting to Login Choice Page"); - httpResp = resp; - this.loginPageURL = loginPageURL; - } + private LoginPageTafResp(Access access, final HttpServletResponse resp, String loginPageURL) { + super(access, "LoginPage", null, "Multiple Possible HTTP Logins available. Redirecting to Login Choice Page"); + httpResp = resp; + this.loginPageURL = loginPageURL; + } - @Override - public RESP authenticate() throws IOException { - httpResp.sendRedirect(loginPageURL); - return RESP.HTTP_REDIRECT_INVOKED; - } - - @Override - public RESP isAuthenticated() { - return RESP.TRY_AUTHENTICATING; - } - - public static TafResp create(Access access, Locator locator, final HttpServletResponse resp, List redirectables) { - if (locator == null) { - if (!redirectables.isEmpty()) { - access.log(Level.DEBUG,"LoginPage Locator is not configured. Taking first Redirectable Taf"); - return redirectables.get(0); - } - return NullTafResp.singleton(); - } + @Override + public RESP authenticate() throws IOException { + httpResp.sendRedirect(loginPageURL); + return RESP.HTTP_REDIRECT_INVOKED; + } + + @Override + public RESP isAuthenticated() { + return RESP.TRY_AUTHENTICATING; + } + + public static TafResp create(Access access, Locator locator, final HttpServletResponse resp, List redirectables) { + if (locator == null) { + if (!redirectables.isEmpty()) { + access.log(Level.DEBUG,"LoginPage Locator is not configured. Taking first Redirectable Taf"); + return redirectables.get(0); + } + return NullTafResp.singleton(); + } - try { - Item item = locator.best(); - URI uri = locator.get(item); - if (uri == null) { - return NullTafResp.singleton(); - } + try { + Item item = locator.best(); + URI uri = locator.get(item); + if (uri == null) { + return NullTafResp.singleton(); + } - StringBuilder sb = new StringBuilder(uri.toString()); - String query = uri.getQuery(); - boolean first = ((query == null) || (query.length() == 0)); - for (Redirectable redir : redirectables) { - if (first) { - sb.append('?'); - first = false; - } - else { - sb.append('&'); - } - sb.append(redir.get()); - } - if (!redirectables.isEmpty()) { - return new LoginPageTafResp(access, resp, sb.toString()); - } - } catch (Exception e) { - access.log(e, "Error deriving Login Page location"); - } + StringBuilder sb = new StringBuilder(uri.toString()); + String query = uri.getQuery(); + boolean first = ((query == null) || (query.length() == 0)); + for (Redirectable redir : redirectables) { + if (first) { + sb.append('?'); + first = false; + } + else { + sb.append('&'); + } + sb.append(redir.get()); + } + if (!redirectables.isEmpty()) { + return new LoginPageTafResp(access, resp, sb.toString()); + } + } catch (Exception e) { + access.log(e, "Error deriving Login Page location"); + } - return NullTafResp.singleton(); - } - - @Override - public String taf() { - return "LoginPage"; - } + return NullTafResp.singleton(); + } + + @Override + public String taf() { + return "LoginPage"; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTaf.java index e8293faa..7e834794 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTaf.java @@ -37,28 +37,28 @@ import org.onap.aaf.cadi.CachedPrincipal.Resp; * */ public class NullTaf implements Taf, HttpTaf { - // Singleton Pattern - public NullTaf() {} + // Singleton Pattern + public NullTaf() {} - /** - * validate - * - * Always Respond with a NullTafResp, which declares it is unauthenticated, and unauthorized - */ - public TafResp validate(LifeForm reading, String... info) { - return NullTafResp.singleton(); - } + /** + * validate + * + * Always Respond with a NullTafResp, which declares it is unauthenticated, and unauthorized + */ + public TafResp validate(LifeForm reading, String... info) { + return NullTafResp.singleton(); + } - /** - * validate - * - * Always Respond with a NullTafResp, which declares it is unauthenticated, and unauthorized - */ - public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { - return NullTafResp.singleton(); - } + /** + * validate + * + * Always Respond with a NullTafResp, which declares it is unauthenticated, and unauthorized + */ + public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { + return NullTafResp.singleton(); + } - public Resp revalidate(CachedPrincipal prin, Object state) { - return Resp.NOT_MINE; - } + public Resp revalidate(CachedPrincipal prin, Object state) { + return Resp.NOT_MINE; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java index af6ef9cc..a3c8f5bb 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java @@ -32,57 +32,57 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; * */ class NullTafResp implements TafResp { - private NullTafResp(){} - - private static TafResp singleton = new NullTafResp(); - - public static TafResp singleton() { - return singleton; - } - - public boolean isValid() { - return false; - } - - public RESP isAuthenticated() { - return RESP.NO_FURTHER_PROCESSING; - } - - public String desc() { - return "All Authentication denied"; - } - - public RESP authenticate() throws IOException { - return RESP.NO_FURTHER_PROCESSING; - } + private NullTafResp(){} + + private static TafResp singleton = new NullTafResp(); + + public static TafResp singleton() { + return singleton; + } + + public boolean isValid() { + return false; + } + + public RESP isAuthenticated() { + return RESP.NO_FURTHER_PROCESSING; + } + + public String desc() { + return "All Authentication denied"; + } + + public RESP authenticate() throws IOException { + return RESP.NO_FURTHER_PROCESSING; + } - public TaggedPrincipal getPrincipal() { - return null; - } + public TaggedPrincipal getPrincipal() { + return null; + } - public Access getAccess() { - return Access.NULL; - } + public Access getAccess() { + return Access.NULL; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.taf.TafResp#isFailedAttempt() - */ - public boolean isFailedAttempt() { - return true; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.taf.TafResp#isFailedAttempt() + */ + public boolean isFailedAttempt() { + return true; + } - @Override - public float timing() { - return 0; - } + @Override + public float timing() { + return 0; + } - @Override - public void timing(long start) { - } - - @Override - public String taf() { - return "NULL"; - } + @Override + public void timing(long start) { + } + + @Override + public String taf() { + return "NULL"; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java index a38c8532..e6555051 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java @@ -34,56 +34,56 @@ import org.onap.aaf.cadi.util.Timing; * */ public class PuntTafResp implements TafResp { - private final String name; - private final String desc; - private float timing; + private final String name; + private final String desc; + private float timing; - public PuntTafResp(String name, String explanation) { - this.name = name; - desc = "Not processing this transaction: " + explanation; - } - - public boolean isValid() { - return false; - } - - public RESP isAuthenticated() { - return RESP.TRY_ANOTHER_TAF; - } - - public String desc() { - return desc; - } - - public RESP authenticate() throws IOException { - return RESP.TRY_ANOTHER_TAF; - } + public PuntTafResp(String name, String explanation) { + this.name = name; + desc = "Not processing this transaction: " + explanation; + } + + public boolean isValid() { + return false; + } + + public RESP isAuthenticated() { + return RESP.TRY_ANOTHER_TAF; + } + + public String desc() { + return desc; + } + + public RESP authenticate() throws IOException { + return RESP.TRY_ANOTHER_TAF; + } - public TaggedPrincipal getPrincipal() { - return null; - } + public TaggedPrincipal getPrincipal() { + return null; + } - public Access getAccess() { - return NullTafResp.singleton().getAccess(); - } + public Access getAccess() { + return NullTafResp.singleton().getAccess(); + } - public boolean isFailedAttempt() { - return false; - } + public boolean isFailedAttempt() { + return false; + } - @Override - public float timing() { - return timing; - } + @Override + public float timing() { + return timing; + } - @Override - public void timing(long start) { - timing = Timing.millis(start); - } - - @Override - public String taf() { - return name; - } + @Override + public void timing(long start) { + timing = Timing.millis(start); + } + + @Override + public String taf() { + return name; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/Redirectable.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/Redirectable.java index 8dc5c118..47c262b0 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/Redirectable.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/Redirectable.java @@ -22,10 +22,10 @@ package org.onap.aaf.cadi.taf; public interface Redirectable extends TafResp { - /** - * Create a Redirectable URL entry prefaced by a URLEncoder.String for a Menu - * example: - * "Global Login=https://xxxx....." - */ - public String get(); + /** + * Create a Redirectable URL entry prefaced by a URLEncoder.String for a Menu + * example: + * "Global Login=https://xxxx....." + */ + public String get(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TafResp.java index acade37a..f3afde72 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TafResp.java @@ -34,78 +34,78 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; * */ public interface TafResp { - public static enum RESP { - IS_AUTHENTICATED, - NO_FURTHER_PROCESSING, - TRY_AUTHENTICATING, - TRY_ANOTHER_TAF, - FAIL, - // A note was made to avoid the response REDIRECT. However, I have deemed that it is - // unavoidable when the underlying TAF did do a REDIRECT, because it requires a HTTP - // Service code to exit without modifying the Response any further. - // Therefore, I have changed this to indicate what HAS happened, with should accommodate - // both positions. Jonathan 10/18/2012 -// public static final int HTTP_REDIRECT_INVOKED = 11; - HTTP_REDIRECT_INVOKED, - HAS_PROCESSED}; - - /** - * Basic success check - * @return - */ - public boolean isValid(); - - /** - * String description of what has occurred (for logging/exceptions) - * @return - */ - public String desc(); - - /** - * Check Response - * @return - */ - public RESP isAuthenticated(); + public static enum RESP { + IS_AUTHENTICATED, + NO_FURTHER_PROCESSING, + TRY_AUTHENTICATING, + TRY_ANOTHER_TAF, + FAIL, + // A note was made to avoid the response REDIRECT. However, I have deemed that it is + // unavoidable when the underlying TAF did do a REDIRECT, because it requires a HTTP + // Service code to exit without modifying the Response any further. + // Therefore, I have changed this to indicate what HAS happened, with should accommodate + // both positions. Jonathan 10/18/2012 +// public static final int HTTP_REDIRECT_INVOKED = 11; + HTTP_REDIRECT_INVOKED, + HAS_PROCESSED}; + + /** + * Basic success check + * @return + */ + public boolean isValid(); + + /** + * String description of what has occurred (for logging/exceptions) + * @return + */ + public String desc(); + + /** + * Check Response + * @return + */ + public RESP isAuthenticated(); - /** - * Authenticate, returning FAIL or Other Valid indication - * - * HTTP implementations should watch for "HTTP_REDIRECT_INVOKED", and end the HTTP call appropriately. - * @return - * @throws CadiException - */ - public RESP authenticate() throws IOException; + /** + * Authenticate, returning FAIL or Other Valid indication + * + * HTTP implementations should watch for "HTTP_REDIRECT_INVOKED", and end the HTTP call appropriately. + * @return + * @throws CadiException + */ + public RESP authenticate() throws IOException; - /** - * Once authenticated, this object should hold a Principal created from the authorization - * @return - */ - public TaggedPrincipal getPrincipal(); + /** + * Once authenticated, this object should hold a Principal created from the authorization + * @return + */ + public TaggedPrincipal getPrincipal(); - /** - * get the Access object which created this object, allowing the responder to appropriate Log, etc - */ - public Access getAccess(); - - /** - * Be able to check if part of a Failed attempt - */ - public boolean isFailedAttempt(); - - /** - * report how long this took - * @return - */ - public float timing(); + /** + * get the Access object which created this object, allowing the responder to appropriate Log, etc + */ + public Access getAccess(); + + /** + * Be able to check if part of a Failed attempt + */ + public boolean isFailedAttempt(); + + /** + * report how long this took + * @return + */ + public float timing(); - /** - * Set end of timing in Millis, given Nanos - * @param start - */ - void timing(long start); - - /** - * Support Taf Name - */ - String taf(); + /** + * Set end of timing in Millis, given Nanos + * @param start + */ + void timing(long start); + + /** + * Support Taf Name + */ + String taf(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java index 98ead3ca..6b8adeb8 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java @@ -28,67 +28,67 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; import org.onap.aaf.cadi.util.Timing; public class TrustNotTafResp implements TafResp { - private final TafResp delegate; - private final String desc; - private float timing; - - public TrustNotTafResp(final TafResp delegate, final String desc) { - this.delegate = delegate; - this.desc = desc; - } - - @Override - public boolean isValid() { - return false; - } + private final TafResp delegate; + private final String desc; + private float timing; + + public TrustNotTafResp(final TafResp delegate, final String desc) { + this.delegate = delegate; + this.desc = desc; + } + + @Override + public boolean isValid() { + return false; + } - @Override - public String desc() { - return desc; - } + @Override + public String desc() { + return desc; + } - @Override - public RESP isAuthenticated() { - return RESP.NO_FURTHER_PROCESSING; - } + @Override + public RESP isAuthenticated() { + return RESP.NO_FURTHER_PROCESSING; + } - @Override - public RESP authenticate() throws IOException { - return RESP.NO_FURTHER_PROCESSING; - } + @Override + public RESP authenticate() throws IOException { + return RESP.NO_FURTHER_PROCESSING; + } - @Override - public TaggedPrincipal getPrincipal() { - return delegate.getPrincipal(); - } + @Override + public TaggedPrincipal getPrincipal() { + return delegate.getPrincipal(); + } - @Override - public Access getAccess() { - return delegate.getAccess(); - } + @Override + public Access getAccess() { + return delegate.getAccess(); + } - @Override - public boolean isFailedAttempt() { - return true; - } - @Override - public float timing() { - return timing; - } + @Override + public boolean isFailedAttempt() { + return true; + } + @Override + public float timing() { + return timing; + } - @Override - public void timing(long start) { - timing = Timing.millis(start); - } - - @Override - public String toString() { - return desc(); - } - - @Override - public String taf() { - return "TrustNot"; - } + @Override + public void timing(long start) { + timing = Timing.millis(start); + } + + @Override + public String toString() { + return desc(); + } + + @Override + public String taf() { + return "TrustNot"; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java index 9d3b28ca..91f9f8c4 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java @@ -28,68 +28,68 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; import org.onap.aaf.cadi.util.Timing; public class TrustTafResp implements TafResp { - private final TafResp delegate; - private final TaggedPrincipal principal; - private final String desc; - private float timing; - - public TrustTafResp(final TafResp delegate, final TaggedPrincipal principal, final String desc) { - this.delegate = delegate; - this.principal = principal; - this.desc = desc + ' ' + delegate.desc(); - } - - @Override - public boolean isValid() { - return delegate.isValid(); - } + private final TafResp delegate; + private final TaggedPrincipal principal; + private final String desc; + private float timing; + + public TrustTafResp(final TafResp delegate, final TaggedPrincipal principal, final String desc) { + this.delegate = delegate; + this.principal = principal; + this.desc = desc + ' ' + delegate.desc(); + } + + @Override + public boolean isValid() { + return delegate.isValid(); + } - @Override - public String desc() { - return desc; - } + @Override + public String desc() { + return desc; + } - @Override - public RESP isAuthenticated() { - return delegate.isAuthenticated(); - } + @Override + public RESP isAuthenticated() { + return delegate.isAuthenticated(); + } - @Override - public RESP authenticate() throws IOException { - return delegate.authenticate(); - } + @Override + public RESP authenticate() throws IOException { + return delegate.authenticate(); + } - @Override - public TaggedPrincipal getPrincipal() { - return principal; - } + @Override + public TaggedPrincipal getPrincipal() { + return principal; + } - @Override - public Access getAccess() { - return delegate.getAccess(); - } + @Override + public Access getAccess() { + return delegate.getAccess(); + } - @Override - public boolean isFailedAttempt() { - return delegate.isFailedAttempt(); - } - @Override - public float timing() { - return timing; - } + @Override + public boolean isFailedAttempt() { + return delegate.isFailedAttempt(); + } + @Override + public float timing() { + return timing; + } - @Override - public void timing(long start) { - timing = Timing.millis(start); - } - - public String toString() { - return principal.getName() + " by trust of " + desc(); - } - - @Override - public String taf() { - return "Trust"; - } + @Override + public void timing(long start) { + timing = Timing.millis(start); + } + + public String toString() { + return principal.getName() + " by trust of " + desc(); + } + + @Override + public String taf() { + return "Trust"; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java index 8fc985cf..21830b01 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java @@ -60,139 +60,139 @@ import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf; * */ public class BasicHttpTaf implements HttpTaf { - private Access access; - private String realm; - private CredVal rbac; - private Map rbacs = new TreeMap<>(); - private boolean warn; - private long timeToLive; - - public BasicHttpTaf(Access access, CredVal rbac, String realm, long timeToLive, boolean turnOnWarning) { - this.access = access; - this.realm = realm; - this.rbac = rbac; - this.warn = turnOnWarning; - this.timeToLive = timeToLive; - } + private Access access; + private String realm; + private CredVal rbac; + private Map rbacs = new TreeMap<>(); + private boolean warn; + private long timeToLive; + + public BasicHttpTaf(Access access, CredVal rbac, String realm, long timeToLive, boolean turnOnWarning) { + this.access = access; + this.realm = realm; + this.rbac = rbac; + this.warn = turnOnWarning; + this.timeToLive = timeToLive; + } - public void add(final CredValDomain cvd) { - rbacs.put(cvd.domain(), cvd); - } - - /** - * Note: BasicHttp works for either Carbon Based (Humans) or Silicon Based (machine) Lifeforms. - * @see Taf - */ - public TafResp validate(Taf.LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { - // See if Request implements BasicCred (aka CadiWrap or other), and if User/Pass has already been set separately - if(req instanceof BasicCred) { - BasicCred bc = (BasicCred)req; - if(bc.getUser()!=null) { // CadiWrap, if set, makes sure User & Password are both valid, or both null - if(DenialOfServiceTaf.isDeniedID(bc.getUser())!=null) { - return DenialOfServiceTaf.respDenyID(access,bc.getUser()); - } - CachedBasicPrincipal bp = new CachedBasicPrincipal(this,bc,realm,timeToLive); - - // Be able to do Organizational specific lookups by Domain - CredVal cv = rbacs.get(bp.getDomain()); - if(cv==null) { - cv = rbac; - } - - // ONLY FOR Last Ditch DEBUGGING... - // access.log(Level.WARN,bp.getName() + ":" + new String(bp.getCred())); - if(cv.validate(bp.getName(),Type.PASSWORD,bp.getCred(),req)) { - return new BasicHttpTafResp(access,bp,bp.getName()+" authenticated by password",RESP.IS_AUTHENTICATED,resp,realm,false); - } else { - //TODO may need timed retries in a given time period - return new BasicHttpTafResp(access,null,buildMsg(bp,req,"user/pass combo invalid for ",bc.getUser(),"from",req.getRemoteAddr()), - RESP.TRY_AUTHENTICATING,resp,realm,true); - } - } - } - // Get User/Password from Authorization Header value - String authz = req.getHeader("Authorization"); - if(authz != null && authz.startsWith("Basic ")) { - if(warn&&!req.isSecure()) { - access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); - } - try { - CachedBasicPrincipal ba = new CachedBasicPrincipal(this,authz,realm,timeToLive); - if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { - return DenialOfServiceTaf.respDenyID(access,ba.getName()); - } - - final int at = ba.getName().indexOf('@'); - CredVal cv = rbacs.get(ba.getName().substring(at+1)); - if(cv==null) { - cv = rbac; // default - } + public void add(final CredValDomain cvd) { + rbacs.put(cvd.domain(), cvd); + } + + /** + * Note: BasicHttp works for either Carbon Based (Humans) or Silicon Based (machine) Lifeforms. + * @see Taf + */ + public TafResp validate(Taf.LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { + // See if Request implements BasicCred (aka CadiWrap or other), and if User/Pass has already been set separately + if(req instanceof BasicCred) { + BasicCred bc = (BasicCred)req; + if(bc.getUser()!=null) { // CadiWrap, if set, makes sure User & Password are both valid, or both null + if(DenialOfServiceTaf.isDeniedID(bc.getUser())!=null) { + return DenialOfServiceTaf.respDenyID(access,bc.getUser()); + } + CachedBasicPrincipal bp = new CachedBasicPrincipal(this,bc,realm,timeToLive); + + // Be able to do Organizational specific lookups by Domain + CredVal cv = rbacs.get(bp.getDomain()); + if(cv==null) { + cv = rbac; + } + + // ONLY FOR Last Ditch DEBUGGING... + // access.log(Level.WARN,bp.getName() + ":" + new String(bp.getCred())); + if(cv.validate(bp.getName(),Type.PASSWORD,bp.getCred(),req)) { + return new BasicHttpTafResp(access,bp,bp.getName()+" authenticated by password",RESP.IS_AUTHENTICATED,resp,realm,false); + } else { + //TODO may need timed retries in a given time period + return new BasicHttpTafResp(access,null,buildMsg(bp,req,"user/pass combo invalid for ",bc.getUser(),"from",req.getRemoteAddr()), + RESP.TRY_AUTHENTICATING,resp,realm,true); + } + } + } + // Get User/Password from Authorization Header value + String authz = req.getHeader("Authorization"); + if(authz != null && authz.startsWith("Basic ")) { + if(warn&&!req.isSecure()) { + access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); + } + try { + CachedBasicPrincipal ba = new CachedBasicPrincipal(this,authz,realm,timeToLive); + if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { + return DenialOfServiceTaf.respDenyID(access,ba.getName()); + } + + final int at = ba.getName().indexOf('@'); + CredVal cv = rbacs.get(ba.getName().substring(at+1)); + if(cv==null) { + cv = rbac; // default + } - // ONLY FOR Last Ditch DEBUGGING... - // access.log(Level.WARN,ba.getName() + ":" + new String(ba.getCred())); - if(cv.validate(ba.getName(), Type.PASSWORD, ba.getCred(), req)) { - return new BasicHttpTafResp(access,ba, ba.getName()+" authenticated by BasicAuth password",RESP.IS_AUTHENTICATED,resp,realm,false); - } else { - //TODO may need timed retries in a given time period - return new BasicHttpTafResp(access,null,buildMsg(ba,req,"user/pass combo invalid"), - RESP.TRY_AUTHENTICATING,resp,realm,true); - } - } catch (IOException e) { - String msg = buildMsg(null,req,"Failed HTTP Basic Authorization (", e.getMessage(), ')'); - access.log(Level.INFO,msg); - return new BasicHttpTafResp(access,null,msg, RESP.TRY_AUTHENTICATING, resp, realm,true); - } - } - return new BasicHttpTafResp(access,null,"Requesting HTTP Basic Authorization",RESP.TRY_AUTHENTICATING,resp,realm,false); - } - - protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { - StringBuilder sb = new StringBuilder(); - if(pr!=null) { - sb.append("user="); - sb.append(pr.getName()); - sb.append(','); - } - sb.append("ip="); - sb.append(req.getRemoteAddr()); - sb.append(",port="); - sb.append(req.getRemotePort()); - if(msg.length>0) { - sb.append(",msg=\""); - for(Object s : msg) { - sb.append(s.toString()); - } - sb.append('"'); - } - return sb.toString(); - } - - public void addCredVal(final String realm, final CredVal cv) { - rbacs.put(realm, cv); - } + // ONLY FOR Last Ditch DEBUGGING... + // access.log(Level.WARN,ba.getName() + ":" + new String(ba.getCred())); + if(cv.validate(ba.getName(), Type.PASSWORD, ba.getCred(), req)) { + return new BasicHttpTafResp(access,ba, ba.getName()+" authenticated by BasicAuth password",RESP.IS_AUTHENTICATED,resp,realm,false); + } else { + //TODO may need timed retries in a given time period + return new BasicHttpTafResp(access,null,buildMsg(ba,req,"user/pass combo invalid"), + RESP.TRY_AUTHENTICATING,resp,realm,true); + } + } catch (IOException e) { + String msg = buildMsg(null,req,"Failed HTTP Basic Authorization (", e.getMessage(), ')'); + access.log(Level.INFO,msg); + return new BasicHttpTafResp(access,null,msg, RESP.TRY_AUTHENTICATING, resp, realm,true); + } + } + return new BasicHttpTafResp(access,null,"Requesting HTTP Basic Authorization",RESP.TRY_AUTHENTICATING,resp,realm,false); + } + + protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { + StringBuilder sb = new StringBuilder(); + if(pr!=null) { + sb.append("user="); + sb.append(pr.getName()); + sb.append(','); + } + sb.append("ip="); + sb.append(req.getRemoteAddr()); + sb.append(",port="); + sb.append(req.getRemotePort()); + if(msg.length>0) { + sb.append(",msg=\""); + for(Object s : msg) { + sb.append(s.toString()); + } + sb.append('"'); + } + return sb.toString(); + } + + public void addCredVal(final String realm, final CredVal cv) { + rbacs.put(realm, cv); + } - public CredVal getCredVal(String key) { - CredVal cv = rbacs.get(key); - if(cv==null) { - cv = rbac; - } - return cv; - } - - @Override - public Resp revalidate(CachedPrincipal prin, Object state) { - if(prin instanceof BasicPrincipal) { - BasicPrincipal ba = (BasicPrincipal)prin; - if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { - return Resp.UNVALIDATED; - } - return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; - } - return Resp.NOT_MINE; - } - - public String toString() { - return "Basic Auth enabled on realm: " + realm; - } + public CredVal getCredVal(String key) { + CredVal cv = rbacs.get(key); + if(cv==null) { + cv = rbac; + } + return cv; + } + + @Override + public Resp revalidate(CachedPrincipal prin, Object state) { + if(prin instanceof BasicPrincipal) { + BasicPrincipal ba = (BasicPrincipal)prin; + if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { + return Resp.UNVALIDATED; + } + return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; + } + return Resp.NOT_MINE; + } + + public String toString() { + return "Basic Auth enabled on realm: " + realm; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTafResp.java index 643cf29e..d1acf5fe 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTafResp.java @@ -31,31 +31,31 @@ import org.onap.aaf.cadi.taf.AbsTafResp; import org.onap.aaf.cadi.taf.TafResp; public class BasicHttpTafResp extends AbsTafResp implements TafResp { - private static final String tafName = BasicHttpTaf.class.getSimpleName(); - private HttpServletResponse httpResp; - private String realm; - private RESP status; - private final boolean wasFailed; - - public BasicHttpTafResp(Access access, TaggedPrincipal principal, String description, RESP status, HttpServletResponse resp, String realm, boolean wasFailed) { - super(access, tafName, principal, description); - httpResp = resp; - this.realm = realm; - this.status = status; - this.wasFailed = wasFailed; - } - - public RESP authenticate() throws IOException { - httpResp.setStatus(401); // Unauthorized - httpResp.setHeader("WWW-Authenticate", "Basic realm=\""+realm+'"'); - return RESP.HTTP_REDIRECT_INVOKED; - } - - public RESP isAuthenticated() { - return status; - } - - public boolean isFailedAttempt() { - return wasFailed; - } + private static final String tafName = BasicHttpTaf.class.getSimpleName(); + private HttpServletResponse httpResp; + private String realm; + private RESP status; + private final boolean wasFailed; + + public BasicHttpTafResp(Access access, TaggedPrincipal principal, String description, RESP status, HttpServletResponse resp, String realm, boolean wasFailed) { + super(access, tafName, principal, description); + httpResp = resp; + this.realm = realm; + this.status = status; + this.wasFailed = wasFailed; + } + + public RESP authenticate() throws IOException { + httpResp.setStatus(401); // Unauthorized + httpResp.setHeader("WWW-Authenticate", "Basic realm=\""+realm+'"'); + return RESP.HTTP_REDIRECT_INVOKED; + } + + public RESP isAuthenticated() { + return status; + } + + public boolean isFailedAttempt() { + return wasFailed; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/CertIdentity.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/CertIdentity.java index 0da41b81..f597159e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/CertIdentity.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/CertIdentity.java @@ -29,18 +29,18 @@ import javax.servlet.http.HttpServletRequest; import org.onap.aaf.cadi.principal.TaggedPrincipal; public interface CertIdentity { - /** - * identity from X509Certificate Object and/or certBytes - * - * If you have both, include them. If you only have one, leave the other null, and it will be generated if needed - * - * The Request is there to obtain Header or Attribute info of ultimate user - * - * @param req - * @param cert - * @param certBytes - * @return - * @throws CertificateException - */ - public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] certBytes) throws CertificateException; + /** + * identity from X509Certificate Object and/or certBytes + * + * If you have both, include them. If you only have one, leave the other null, and it will be generated if needed + * + * The Request is there to obtain Header or Attribute info of ultimate user + * + * @param req + * @param cert + * @param certBytes + * @return + * @throws CertificateException + */ + public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] certBytes) throws CertificateException; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509HttpTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509HttpTafResp.java index c18f9036..d51cc86a 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509HttpTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509HttpTafResp.java @@ -29,25 +29,25 @@ import org.onap.aaf.cadi.taf.AbsTafResp; import org.onap.aaf.cadi.taf.TafResp; public class X509HttpTafResp extends AbsTafResp implements TafResp { - private static final String tafName = X509Taf.class.getSimpleName(); - - private RESP status; - - public X509HttpTafResp(Access access, TaggedPrincipal principal, String description, RESP status) { - super(access, tafName, principal, description); - this.status = status; - } - - public RESP authenticate() throws IOException { - return RESP.TRY_ANOTHER_TAF; - } - - public RESP isAuthenticated() { - return status; - } - - public String toString() { - return status.name(); - } + private static final String tafName = X509Taf.class.getSimpleName(); + + private RESP status; + + public X509HttpTafResp(Access access, TaggedPrincipal principal, String description, RESP status) { + super(access, tafName, principal, description); + this.status = status; + } + + public RESP authenticate() throws IOException { + return RESP.TRY_ANOTHER_TAF; + } + + public RESP isAuthenticated() { + return status; + } + + public String toString() { + return status.name(); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java index 77efa956..d0034c76 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java @@ -56,221 +56,221 @@ import org.onap.aaf.cadi.taf.basic.BasicHttpTaf; import org.onap.aaf.cadi.util.Split; public class X509Taf implements HttpTaf { - private static final String CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION = "Certificate NOT valid for Authentication"; - public static final CertificateFactory certFactory; - public static final MessageDigest messageDigest; - public static final TrustManagerFactory tmf; - private Access access; - private CertIdentity[] certIdents; -// private Lur lur; - private ArrayList cadiIssuers; - private String env; - private SecurityInfo si; - private BasicHttpTaf bht; + private static final String CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION = "Certificate NOT valid for Authentication"; + public static final CertificateFactory certFactory; + public static final MessageDigest messageDigest; + public static final TrustManagerFactory tmf; + private Access access; + private CertIdentity[] certIdents; +// private Lur lur; + private ArrayList cadiIssuers; + private String env; + private SecurityInfo si; + private BasicHttpTaf bht; - static { - try { - certFactory = CertificateFactory.getInstance("X.509"); - messageDigest = MessageDigest.getInstance("SHA-256"); // use this to clone - tmf = TrustManagerFactory.getInstance(SecurityInfoC.SSL_KEY_MANAGER_FACTORY_ALGORITHM); - } catch (Exception e) { - throw new RuntimeException("X.509 and SHA-256 are required for X509Taf",e); - } - } - - public X509Taf(Access access, Lur lur, CertIdentity ... cis) throws CertificateException, NoSuchAlgorithmException, CadiException { - this.access = access; - env = access.getProperty(Config.AAF_ENV,null); - if(env==null) { - throw new CadiException("X509Taf requires Environment ("+Config.AAF_ENV+") to be set."); - } -// this.lur = lur; - this.cadiIssuers = new ArrayList<>(); - for(String ci : access.getProperty(Config.CADI_X509_ISSUERS, "").split(":")) { - access.printf(Level.INIT, "Trusting Identity for Certificates signed by \"%s\"",ci); - cadiIssuers.add(ci); - } - try { - Class dci = access.classLoader().loadClass("org.onap.aaf.auth.direct.DirectCertIdentity"); - if(dci==null) { - certIdents = cis; - } else { - CertIdentity temp[] = new CertIdentity[cis.length+1]; - System.arraycopy(cis, 0, temp, 1, cis.length); - temp[0] = (CertIdentity) dci.newInstance(); - certIdents=temp; - } - } catch (Exception e) { - certIdents = cis; - } - - si = new SecurityInfo(access); - } + static { + try { + certFactory = CertificateFactory.getInstance("X.509"); + messageDigest = MessageDigest.getInstance("SHA-256"); // use this to clone + tmf = TrustManagerFactory.getInstance(SecurityInfoC.SSL_KEY_MANAGER_FACTORY_ALGORITHM); + } catch (Exception e) { + throw new RuntimeException("X.509 and SHA-256 are required for X509Taf",e); + } + } + + public X509Taf(Access access, Lur lur, CertIdentity ... cis) throws CertificateException, NoSuchAlgorithmException, CadiException { + this.access = access; + env = access.getProperty(Config.AAF_ENV,null); + if(env==null) { + throw new CadiException("X509Taf requires Environment ("+Config.AAF_ENV+") to be set."); + } +// this.lur = lur; + this.cadiIssuers = new ArrayList<>(); + for(String ci : access.getProperty(Config.CADI_X509_ISSUERS, "").split(":")) { + access.printf(Level.INIT, "Trusting Identity for Certificates signed by \"%s\"",ci); + cadiIssuers.add(ci); + } + try { + Class dci = access.classLoader().loadClass("org.onap.aaf.auth.direct.DirectCertIdentity"); + if(dci==null) { + certIdents = cis; + } else { + CertIdentity temp[] = new CertIdentity[cis.length+1]; + System.arraycopy(cis, 0, temp, 1, cis.length); + temp[0] = (CertIdentity) dci.newInstance(); + certIdents=temp; + } + } catch (Exception e) { + certIdents = cis; + } + + si = new SecurityInfo(access); + } - public static final X509Certificate getCert(byte[] certBytes) throws CertificateException { - ByteArrayInputStream bais = new ByteArrayInputStream(certBytes); - return (X509Certificate)certFactory.generateCertificate(bais); - } + public static final X509Certificate getCert(byte[] certBytes) throws CertificateException { + ByteArrayInputStream bais = new ByteArrayInputStream(certBytes); + return (X509Certificate)certFactory.generateCertificate(bais); + } - public static final byte[] getFingerPrint(byte[] ba) { - MessageDigest md; - try { - md = (MessageDigest)messageDigest.clone(); - } catch (CloneNotSupportedException e) { - // should never get here - return new byte[0]; - } - md.update(ba); - return md.digest(); - } + public static final byte[] getFingerPrint(byte[] ba) { + MessageDigest md; + try { + md = (MessageDigest)messageDigest.clone(); + } catch (CloneNotSupportedException e) { + // should never get here + return new byte[0]; + } + md.update(ba); + return md.digest(); + } - @Override - public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { - // Check for Mutual SSL - try { - X509Certificate[] certarr = (X509Certificate[])req.getAttribute("javax.servlet.request.X509Certificate"); - if(certarr!=null && certarr.length>0) { - si.checkClientTrusted(certarr); - // Note: If the Issuer is not in the TrustStore, it's not added to the Cert list - String issuer = certarr[0].getIssuerDN().toString(); - if(cadiIssuers.contains(issuer)) { - String subject = certarr[0].getSubjectDN().getName(); - // avoiding extra object creation, since this is validated EVERY transaction with a Cert - int at = subject.indexOf('@'); - if(at>=0) { - int start = subject.lastIndexOf(',', at); - if(start<0) { - start = 0; - } - int end = subject.indexOf(',', at); - if(end<0) { - end=subject.length(); - } - int temp; - if(((temp=subject.indexOf("OU=",start))>=0 && temp=0 && temp1 && env!=null && env.equals(sa[1]))) { // Check Environment - return new X509HttpTafResp(access, - new X509Principal(sa[0], certarr[0],(byte[])null,bht), - "X509Taf validated " + sa[0] + (sa.length<2?"":" for aaf_env " + env ), RESP.IS_AUTHENTICATED); - } - } - - } - } - } - + @Override + public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { + // Check for Mutual SSL + try { + X509Certificate[] certarr = (X509Certificate[])req.getAttribute("javax.servlet.request.X509Certificate"); + if(certarr!=null && certarr.length>0) { + si.checkClientTrusted(certarr); + // Note: If the Issuer is not in the TrustStore, it's not added to the Cert list + String issuer = certarr[0].getIssuerDN().toString(); + if(cadiIssuers.contains(issuer)) { + String subject = certarr[0].getSubjectDN().getName(); + // avoiding extra object creation, since this is validated EVERY transaction with a Cert + int at = subject.indexOf('@'); + if(at>=0) { + int start = subject.lastIndexOf(',', at); + if(start<0) { + start = 0; + } + int end = subject.indexOf(',', at); + if(end<0) { + end=subject.length(); + } + int temp; + if(((temp=subject.indexOf("OU=",start))>=0 && temp=0 && temp1 && env!=null && env.equals(sa[1]))) { // Check Environment + return new X509HttpTafResp(access, + new X509Principal(sa[0], certarr[0],(byte[])null,bht), + "X509Taf validated " + sa[0] + (sa.length<2?"":" for aaf_env " + env ), RESP.IS_AUTHENTICATED); + } + } + + } + } + } + - byte[] array = null; - byte[] certBytes = null; - X509Certificate cert=null; - String responseText=null; - String authHeader = req.getHeader("Authorization"); + byte[] array = null; + byte[] certBytes = null; + X509Certificate cert=null; + String responseText=null; + String authHeader = req.getHeader("Authorization"); - if(certarr!=null) { // If cert !=null, Cert is Tested by Mutual Protocol. - if(authHeader!=null) { // This is only intended to be a Secure Connection, not an Identity - for(String auth : Split.split(',',authHeader)) { - if(auth.startsWith("Bearer ")) { // Bearer = OAuth... Don't use as Authenication - return new X509HttpTafResp(access, null, "Certificate verified, but Bearer Token is presented", RESP.TRY_ANOTHER_TAF); - } - } - } - cert = certarr[0]; - responseText = ", validated by Mutual SSL Protocol"; - } else { // If cert == null, Get Declared Cert (in header), but validate by having them sign something - if(authHeader != null) { - for(String auth : Split.splitTrim(',',authHeader)) { - if(auth.startsWith("x509 ")) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(auth.length()); - try { - array = auth.getBytes(); - ByteArrayInputStream bais = new ByteArrayInputStream(array); - Symm.base64noSplit.decode(bais, baos, 5); - certBytes = baos.toByteArray(); - cert = getCert(certBytes); - - /** - * Identity from CERT if well know CA and specific encoded information - */ - // If found Identity doesn't work, try SignedStuff Protocol - // cert.checkValidity(); - // cert.--- GET FINGERPRINT? - String stuff = req.getHeader("Signature"); - if(stuff==null) - return new X509HttpTafResp(access, null, "Header entry 'Signature' required to validate One way X509 Certificate", RESP.TRY_ANOTHER_TAF); - String data = req.getHeader("Data"); - // if(data==null) - // return new X509HttpTafResp(access, null, "No signed Data to validate with X509 Certificate", RESP.TRY_ANOTHER_TAF); - - // Note: Data Pos shows is " " - // int dataPos = (stuff.indexOf(' ')); // determine what is Algorithm - // Get Signature - bais = new ByteArrayInputStream(stuff.getBytes()); - baos = new ByteArrayOutputStream(stuff.length()); - Symm.base64noSplit.decode(bais, baos); - array = baos.toByteArray(); - // Signature sig = Signature.getInstance(stuff.substring(0, dataPos)); // get Algorithm from first part of Signature - - Signature sig = Signature.getInstance(cert.getSigAlgName()); - sig.initVerify(cert.getPublicKey()); - sig.update(data.getBytes()); - if(!sig.verify(array)) { - access.log(Level.ERROR, "Signature doesn't Match"); - return new X509HttpTafResp(access, null, CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION, RESP.TRY_ANOTHER_TAF); - } - responseText = ", validated by Signed Data"; - } catch (Exception e) { - access.log(e, "Exception while validating Cert"); - return new X509HttpTafResp(access, null, CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION, RESP.TRY_ANOTHER_TAF); - } - } - } - } - if(cert==null) { - return new X509HttpTafResp(access, null, "No Certificate Info on Transaction", RESP.TRY_ANOTHER_TAF); - } - - // A cert has been found, match Identify - TaggedPrincipal prin=null; - - for(int i=0;prin==null && i " + // int dataPos = (stuff.indexOf(' ')); // determine what is Algorithm + // Get Signature + bais = new ByteArrayInputStream(stuff.getBytes()); + baos = new ByteArrayOutputStream(stuff.length()); + Symm.base64noSplit.decode(bais, baos); + array = baos.toByteArray(); + // Signature sig = Signature.getInstance(stuff.substring(0, dataPos)); // get Algorithm from first part of Signature + + Signature sig = Signature.getInstance(cert.getSigAlgName()); + sig.initVerify(cert.getPublicKey()); + sig.update(data.getBytes()); + if(!sig.verify(array)) { + access.log(Level.ERROR, "Signature doesn't Match"); + return new X509HttpTafResp(access, null, CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION, RESP.TRY_ANOTHER_TAF); + } + responseText = ", validated by Signed Data"; + } catch (Exception e) { + access.log(e, "Exception while validating Cert"); + return new X509HttpTafResp(access, null, CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION, RESP.TRY_ANOTHER_TAF); + } + } + } + } + if(cert==null) { + return new X509HttpTafResp(access, null, "No Certificate Info on Transaction", RESP.TRY_ANOTHER_TAF); + } + + // A cert has been found, match Identify + TaggedPrincipal prin=null; + + for(int i=0;prin==null && i deniedIP=null, deniedID=null; - private Access access; - private final TafResp puntNotDenied; - private static File dosIP, dosID; - - /** - * - * @param hostname - * @param prod - * @throws CadiException - */ - public DenialOfServiceTaf(Access access) throws CadiException { - puntNotDenied = new PuntTafResp("DenialOfServiceTaf", "This Transaction is not denied"); - this.access = access; - if(dosIP==null || dosID == null) { - String dirStr; - if((dirStr = access.getProperty(Config.AAF_DATA_DIR, null))!=null) { - dosIP = new File(dirStr+"/dosIP"); - readIP(); - dosID = new File(dirStr+"/dosID"); - readID(); - } - } - } + private static Map deniedIP=null, deniedID=null; + private Access access; + private final TafResp puntNotDenied; + private static File dosIP, dosID; + + /** + * + * @param hostname + * @param prod + * @throws CadiException + */ + public DenialOfServiceTaf(Access access) throws CadiException { + puntNotDenied = new PuntTafResp("DenialOfServiceTaf", "This Transaction is not denied"); + this.access = access; + if(dosIP==null || dosID == null) { + String dirStr; + if((dirStr = access.getProperty(Config.AAF_DATA_DIR, null))!=null) { + dosIP = new File(dirStr+"/dosIP"); + readIP(); + dosID = new File(dirStr+"/dosID"); + readID(); + } + } + } - @Override - public TafResp validate(LifeForm reading, HttpServletRequest req, final HttpServletResponse resp) { - // Performance, when not needed - if(deniedIP != null) { - String ip; - Counter c = deniedIP.get(ip=req.getRemoteAddr()); - if(c!=null) { - c.inc(); - return respDenyIP(access,ip); - } - } - - // Note: Can't process Principal, because this is the first TAF, and no Principal is created. - // Other TAFs use "isDenied()" on this Object to validate. - return puntNotDenied; - } + @Override + public TafResp validate(LifeForm reading, HttpServletRequest req, final HttpServletResponse resp) { + // Performance, when not needed + if(deniedIP != null) { + String ip; + Counter c = deniedIP.get(ip=req.getRemoteAddr()); + if(c!=null) { + c.inc(); + return respDenyIP(access,ip); + } + } + + // Note: Can't process Principal, because this is the first TAF, and no Principal is created. + // Other TAFs use "isDenied()" on this Object to validate. + return puntNotDenied; + } - @Override - public Resp revalidate(CachedPrincipal prin, Object state) { - // We always return NOT MINE, because DOS Taf does not ever validate - return Resp.NOT_MINE; - } + @Override + public Resp revalidate(CachedPrincipal prin, Object state) { + // We always return NOT MINE, because DOS Taf does not ever validate + return Resp.NOT_MINE; + } - /* - * for use in Other TAFs, before they attempt backend validation of - */ - public static Counter isDeniedID(String identity) { - if(deniedID!=null) { - return deniedID.get(identity); - } - return null; - } - - /** - * - */ - public static Counter isDeniedIP(String ipvX) { - if(deniedIP!=null) { - return deniedIP.get(ipvX); - } - return null; - } + /* + * for use in Other TAFs, before they attempt backend validation of + */ + public static Counter isDeniedID(String identity) { + if(deniedID!=null) { + return deniedID.get(identity); + } + return null; + } + + /** + * + */ + public static Counter isDeniedIP(String ipvX) { + if(deniedIP!=null) { + return deniedIP.get(ipvX); + } + return null; + } - /** - * Return of "True" means IP has been added. - * Return of "False" means IP already added. - * - * @param ip - * @return - */ - public static synchronized boolean denyIP(String ip) { - boolean rv = false; - if(deniedIP==null) { - deniedIP = new HashMap<>(); - deniedIP.put(ip, new Counter(ip)); // Noted duplicated for minimum time spent - rv= true; - } else if(deniedIP.get(ip)==null) { - deniedIP.put(ip, new Counter(ip)); - rv = true; - } - if(rv) { - writeIP(); - } - return rv; - } - - private static void writeIP() { - if(dosIP!=null && deniedIP!=null) { - if(deniedIP.isEmpty()) { - if(dosIP.exists()) { - dosIP.delete(); - } - } else { - PrintStream fos; - try { - fos = new PrintStream(new FileOutputStream(dosIP,false)); - try { - for(String ip: deniedIP.keySet()) { - fos.println(ip); - } - } finally { - fos.close(); - } - } catch (IOException e) { - e.printStackTrace(System.err); - } - } - } - } - - private static void readIP() { - if(dosIP!=null && dosIP.exists()) { - BufferedReader br; - try { - br = new BufferedReader(new FileReader(dosIP)); - try { - if(deniedIP==null) { - deniedIP=new HashMap<>(); - } + /** + * Return of "True" means IP has been added. + * Return of "False" means IP already added. + * + * @param ip + * @return + */ + public static synchronized boolean denyIP(String ip) { + boolean rv = false; + if(deniedIP==null) { + deniedIP = new HashMap<>(); + deniedIP.put(ip, new Counter(ip)); // Noted duplicated for minimum time spent + rv= true; + } else if(deniedIP.get(ip)==null) { + deniedIP.put(ip, new Counter(ip)); + rv = true; + } + if(rv) { + writeIP(); + } + return rv; + } + + private static void writeIP() { + if(dosIP!=null && deniedIP!=null) { + if(deniedIP.isEmpty()) { + if(dosIP.exists()) { + dosIP.delete(); + } + } else { + PrintStream fos; + try { + fos = new PrintStream(new FileOutputStream(dosIP,false)); + try { + for(String ip: deniedIP.keySet()) { + fos.println(ip); + } + } finally { + fos.close(); + } + } catch (IOException e) { + e.printStackTrace(System.err); + } + } + } + } + + private static void readIP() { + if(dosIP!=null && dosIP.exists()) { + BufferedReader br; + try { + br = new BufferedReader(new FileReader(dosIP)); + try { + if(deniedIP==null) { + deniedIP=new HashMap<>(); + } - String line; - while((line=br.readLine())!=null) { - deniedIP.put(line, new Counter(line)); - } - } finally { - br.close(); - } - } catch (IOException e) { - e.printStackTrace(System.err); - } - } - } + String line; + while((line=br.readLine())!=null) { + deniedIP.put(line, new Counter(line)); + } + } finally { + br.close(); + } + } catch (IOException e) { + e.printStackTrace(System.err); + } + } + } - /** - * Return of "True" means IP has was removed. - * Return of "False" means IP wasn't being denied. - * - * @param ip - * @return - */ - public static synchronized boolean removeDenyIP(String ip) { - if(deniedIP!=null && deniedIP.remove(ip)!=null) { - writeIP(); - if(deniedIP.isEmpty()) { - deniedIP=null; - } - return true; - } - return false; - } + /** + * Return of "True" means IP has was removed. + * Return of "False" means IP wasn't being denied. + * + * @param ip + * @return + */ + public static synchronized boolean removeDenyIP(String ip) { + if(deniedIP!=null && deniedIP.remove(ip)!=null) { + writeIP(); + if(deniedIP.isEmpty()) { + deniedIP=null; + } + return true; + } + return false; + } - /** - * Return of "True" means ID has been added. - * Return of "False" means ID already added. - * - * @param ip - * @return - */ - public static synchronized boolean denyID(String id) { - boolean rv = false; - if(deniedID==null) { - deniedID = new HashMap<>(); - deniedID.put(id, new Counter(id)); // Noted duplicated for minimum time spent - rv = true; - } else if(deniedID.get(id)==null) { - deniedID.put(id, new Counter(id)); - rv = true; - } - if(rv) { - writeID(); - } - return rv; + /** + * Return of "True" means ID has been added. + * Return of "False" means ID already added. + * + * @param ip + * @return + */ + public static synchronized boolean denyID(String id) { + boolean rv = false; + if(deniedID==null) { + deniedID = new HashMap<>(); + deniedID.put(id, new Counter(id)); // Noted duplicated for minimum time spent + rv = true; + } else if(deniedID.get(id)==null) { + deniedID.put(id, new Counter(id)); + rv = true; + } + if(rv) { + writeID(); + } + return rv; - } + } - private static void writeID() { - if(dosID!=null && deniedID!=null) { - if(deniedID.isEmpty()) { - if(dosID.exists()) { - dosID.delete(); - } - } else { - PrintStream fos; - try { - fos = new PrintStream(new FileOutputStream(dosID,false)); - try { - for(String ip: deniedID.keySet()) { - fos.println(ip); - } - } finally { - fos.close(); - } - } catch (IOException e) { - e.printStackTrace(System.err); - } - } - } - } + private static void writeID() { + if(dosID!=null && deniedID!=null) { + if(deniedID.isEmpty()) { + if(dosID.exists()) { + dosID.delete(); + } + } else { + PrintStream fos; + try { + fos = new PrintStream(new FileOutputStream(dosID,false)); + try { + for(String ip: deniedID.keySet()) { + fos.println(ip); + } + } finally { + fos.close(); + } + } catch (IOException e) { + e.printStackTrace(System.err); + } + } + } + } - private static void readID() { - if(dosID!=null && dosID.exists()) { - BufferedReader br; - try { - br = new BufferedReader(new FileReader(dosID)); - try { - if(deniedID==null) { - deniedID=new HashMap<>(); - } - - String line; - while((line=br.readLine())!=null) { - deniedID.put(line, new Counter(line)); - } - } finally { - br.close(); - } - } catch (IOException e) { - e.printStackTrace(System.err); - } - } - } + private static void readID() { + if(dosID!=null && dosID.exists()) { + BufferedReader br; + try { + br = new BufferedReader(new FileReader(dosID)); + try { + if(deniedID==null) { + deniedID=new HashMap<>(); + } + + String line; + while((line=br.readLine())!=null) { + deniedID.put(line, new Counter(line)); + } + } finally { + br.close(); + } + } catch (IOException e) { + e.printStackTrace(System.err); + } + } + } - /** - * Return of "True" means ID has was removed. - * Return of "False" means ID wasn't being denied. - * - * @param ip - * @return - */ - public static synchronized boolean removeDenyID(String id) { - if(deniedID!=null && deniedID.remove(id)!=null) { - writeID(); - if(deniedID.isEmpty()) { - deniedID=null; - } + /** + * Return of "True" means ID has was removed. + * Return of "False" means ID wasn't being denied. + * + * @param ip + * @return + */ + public static synchronized boolean removeDenyID(String id) { + if(deniedID!=null && deniedID.remove(id)!=null) { + writeID(); + if(deniedID.isEmpty()) { + deniedID=null; + } - return true; - } - return false; - } - - public List report() { - int initSize = 0; - if(deniedIP!=null)initSize+=deniedIP.size(); - if(deniedID!=null)initSize+=deniedID.size(); - ArrayList al = new ArrayList<>(initSize); - if(deniedID!=null) { - for(Counter c : deniedID.values()) { - al.add(c.toString()); - } - } - if(deniedIP!=null) { - for(Counter c : deniedIP.values()) { - al.add(c.toString()); - } - } - return al; - } - - public static class Counter { - private final String name; - private int count = 0; - private Date first; - private long last; // note, we use "last" as long, to avoid popping useless dates on Heap. - - public Counter(String name) { - this.name = name; - first = null; - last = 0L; - count = 0; - } - - public String getName() { - return name; - } - - public int getCount() { - return count; - } + return true; + } + return false; + } + + public List report() { + int initSize = 0; + if(deniedIP!=null)initSize+=deniedIP.size(); + if(deniedID!=null)initSize+=deniedID.size(); + ArrayList al = new ArrayList<>(initSize); + if(deniedID!=null) { + for(Counter c : deniedID.values()) { + al.add(c.toString()); + } + } + if(deniedIP!=null) { + for(Counter c : deniedIP.values()) { + al.add(c.toString()); + } + } + return al; + } + + public static class Counter { + private final String name; + private int count = 0; + private Date first; + private long last; // note, we use "last" as long, to avoid popping useless dates on Heap. + + public Counter(String name) { + this.name = name; + first = null; + last = 0L; + count = 0; + } + + public String getName() { + return name; + } + + public int getCount() { + return count; + } - public long getLast() { - return last; - } - - /* - * Only allow Denial of ServiceTaf to increment - */ - private synchronized void inc() { - ++count; - last = System.currentTimeMillis(); - if(first==null) { - first = new Date(last); - } - } - - public String toString() { - if(count==0) - return name + " is on the denied list, but has not attempted Access"; - else - return - name + - " has been denied " + - count + - " times since " + - first + - ". Last denial was " + - new Date(last); - } - } + public long getLast() { + return last; + } + + /* + * Only allow Denial of ServiceTaf to increment + */ + private synchronized void inc() { + ++count; + last = System.currentTimeMillis(); + if(first==null) { + first = new Date(last); + } + } + + public String toString() { + if(count==0) + return name + " is on the denied list, but has not attempted Access"; + else + return + name + + " has been denied " + + count + + " times since " + + first + + ". Last denial was " + + new Date(last); + } + } - public static TafResp respDenyID(Access access, String identity) { - return new DenialOfServiceTafResp(access, RESP.NO_FURTHER_PROCESSING, identity + " is on the Identity Denial list"); - } - - public static TafResp respDenyIP(Access access, String ip) { - return new DenialOfServiceTafResp(access, RESP.NO_FURTHER_PROCESSING, ip + " is on the IP Denial list"); - } + public static TafResp respDenyID(Access access, String identity) { + return new DenialOfServiceTafResp(access, RESP.NO_FURTHER_PROCESSING, identity + " is on the Identity Denial list"); + } + + public static TafResp respDenyIP(Access access, String ip) { + return new DenialOfServiceTafResp(access, RESP.NO_FURTHER_PROCESSING, ip + " is on the IP Denial list"); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTafResp.java index e5a336f7..2fcd1553 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTafResp.java @@ -27,29 +27,29 @@ import org.onap.aaf.cadi.Access; import org.onap.aaf.cadi.taf.AbsTafResp; public class DenialOfServiceTafResp extends AbsTafResp { - private static final String tafName = DenialOfServiceTaf.class.getSimpleName(); - - private RESP ect; // Homage to Arethra Franklin - - public DenialOfServiceTafResp(Access access, RESP resp, String description ) { - super(access, tafName, null, description); - ect = resp; - } - - // Override base behavior of checking Principal and trying another TAF - @Override - public RESP isAuthenticated() { - return ect; - } - - - public RESP authenticate() throws IOException { - return ect; - } - - @Override - public String taf() { - return "DOS"; - } + private static final String tafName = DenialOfServiceTaf.class.getSimpleName(); + + private RESP ect; // Homage to Arethra Franklin + + public DenialOfServiceTafResp(Access access, RESP resp, String description ) { + super(access, tafName, null, description); + ect = resp; + } + + // Override base behavior of checking Principal and trying another TAF + @Override + public RESP isAuthenticated() { + return ect; + } + + + public RESP authenticate() throws IOException { + return ect; + } + + @Override + public String taf() { + return "DOS"; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Chmod.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Chmod.java index 74bf805d..70fabd82 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Chmod.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Chmod.java @@ -25,38 +25,38 @@ import java.io.File; import java.io.IOException; public interface Chmod { - public void chmod(File f) throws IOException; - - public static final Chmod to755 = new Chmod() { - public void chmod(File f) throws IOException { - f.setExecutable(true, false); - f.setExecutable(true, true); - f.setReadable(true, false); - f.setReadable(true, true); - f.setWritable(false, false); - f.setWritable(true, true); - } - }; + public void chmod(File f) throws IOException; + + public static final Chmod to755 = new Chmod() { + public void chmod(File f) throws IOException { + f.setExecutable(true, false); + f.setExecutable(true, true); + f.setReadable(true, false); + f.setReadable(true, true); + f.setWritable(false, false); + f.setWritable(true, true); + } + }; - public static final Chmod to644 = new Chmod() { - public void chmod(File f) throws IOException { - f.setExecutable(false, false); - f.setExecutable(false, true); - f.setReadable(true, false); - f.setReadable(true, true); - f.setWritable(false, false); - f.setWritable(true, true); - } - }; + public static final Chmod to644 = new Chmod() { + public void chmod(File f) throws IOException { + f.setExecutable(false, false); + f.setExecutable(false, true); + f.setReadable(true, false); + f.setReadable(true, true); + f.setWritable(false, false); + f.setWritable(true, true); + } + }; - public static final Chmod to400 = new Chmod() { - public void chmod(File f) throws IOException { - f.setExecutable(false, false); - f.setExecutable(false, true); - f.setReadable(false, false); - f.setReadable(true, true); - f.setWritable(false, false); - f.setWritable(false, true); - } - }; + public static final Chmod to400 = new Chmod() { + public void chmod(File f) throws IOException { + f.setExecutable(false, false); + f.setExecutable(false, true); + f.setReadable(false, false); + f.setReadable(true, true); + f.setWritable(false, false); + f.setWritable(false, true); + } + }; } \ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java index 4ea50a10..f0b8d38d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java @@ -22,30 +22,30 @@ package org.onap.aaf.cadi.util; public class FQI { - /** - * Take a Fully Qualified User, and get a Namespace from it. - * @param fqi - * @return - */ - public final static String reverseDomain(final String fqi) { - StringBuilder sb = null; - String[] split = Split.split('.',fqi); - int at; - for(int i=split.length-1;i>=0;--i) { - if(sb == null) { - sb = new StringBuilder(); - } else { - sb.append('.'); - } + /** + * Take a Fully Qualified User, and get a Namespace from it. + * @param fqi + * @return + */ + public final static String reverseDomain(final String fqi) { + StringBuilder sb = null; + String[] split = Split.split('.',fqi); + int at; + for(int i=split.length-1;i>=0;--i) { + if(sb == null) { + sb = new StringBuilder(); + } else { + sb.append('.'); + } - if((at = split[i].indexOf('@'))>0) { - sb.append(split[i].subSequence(at+1, split[i].length())); - } else { - sb.append(split[i]); - } - } - - return sb==null?"":sb.toString(); - } + if((at = split[i].indexOf('@'))>0) { + sb.append(split[i].subSequence(at+1, split[i].length())); + } else { + sb.append(split[i]); + } + } + + return sb==null?"":sb.toString(); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java index 7b04942f..7c3ac30d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java @@ -25,65 +25,65 @@ import java.io.IOException; import java.io.OutputStream; public class JsonOutputStream extends OutputStream { - private static final byte[] TWO_SPACE = " ".getBytes(); - private OutputStream os; - private boolean closeable; - private int indent = 0; - private int prev,ret=0; + private static final byte[] TWO_SPACE = " ".getBytes(); + private OutputStream os; + private boolean closeable; + private int indent = 0; + private int prev,ret=0; - public JsonOutputStream(OutputStream os) { - // Don't close these, or dire consequences. - closeable = !os.equals(System.out) && !os.equals(System.err); - this.os = os; - } + public JsonOutputStream(OutputStream os) { + // Don't close these, or dire consequences. + closeable = !os.equals(System.out) && !os.equals(System.err); + this.os = os; + } - @Override - public void write(int b) throws IOException { - if(ret=='\n') { - ret = 0; - if(prev!=',' || (b!='{' && b!='[')) { - os.write('\n'); - for(int i=0;i=0?slash:str.length(); - int bits = slash>=0?Integer.parseInt(str.substring(slash+1)):32; - if(check && bits>32) { - throw new MaskFormatException("Invalid Mask Offset in IPV4 Address"); - } - int prev = 0; - long lbyte; - while(prev255 || lbyte<0)) { - throw new MaskFormatException("Invalid Byte in IPV4 Address"); - } - rv|=lbyte<>bits; - } - return rv; - } + if(idx<0) { // Not IPV6, so it's IPV4... Is there a mask of 123/254? + idx=str.indexOf('.'); + int offset = 24; + int end = slash>=0?slash:str.length(); + int bits = slash>=0?Integer.parseInt(str.substring(slash+1)):32; + if(check && bits>32) { + throw new MaskFormatException("Invalid Mask Offset in IPV4 Address"); + } + int prev = 0; + long lbyte; + while(prev255 || lbyte<0)) { + throw new MaskFormatException("Invalid Byte in IPV4 Address"); + } + rv|=lbyte<>bits; + } + return rv; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Pool.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Pool.java index 7cd7a633..156397b6 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Pool.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Pool.java @@ -61,322 +61,322 @@ import org.onap.aaf.cadi.CadiException; * @param */ public class Pool { - /** - * This is a constant which specified the default maximum number of unused - * objects to be held at any given time. - */ - private static final int MAX_RANGE = 6; // safety + /** + * This is a constant which specified the default maximum number of unused + * objects to be held at any given time. + */ + private static final int MAX_RANGE = 6; // safety - /** - * only Simple List needed. - * - * NOTE TO MAINTAINERS: THIS OBJECT DOES IT'S OWN SYNCHRONIZATION. All - * changes that touch list must account for correctly synchronizing list. - */ - private LinkedList> list; + /** + * only Simple List needed. + * + * NOTE TO MAINTAINERS: THIS OBJECT DOES IT'S OWN SYNCHRONIZATION. All + * changes that touch list must account for correctly synchronizing list. + */ + private LinkedList> list; - /** - * keep track of how many elements exist, to avoid asking list. - */ - private int count; + /** + * keep track of how many elements exist, to avoid asking list. + */ + private int count; - /** - * Spares are those Object that are primed and ready to go. - */ - private int spares; + /** + * Spares are those Object that are primed and ready to go. + */ + private int spares; - /** - * Actual MAX number of spares allowed to hang around. Can be set to - * something besides the default MAX_RANGE. - */ - private int max_range = MAX_RANGE; + /** + * Actual MAX number of spares allowed to hang around. Can be set to + * something besides the default MAX_RANGE. + */ + private int max_range = MAX_RANGE; - /** - * The Creator for this particular pool. It must work for type T. - */ - private Creator creator; + /** + * The Creator for this particular pool. It must work for type T. + */ + private Creator creator; - private Log logger; + private Log logger; - /** - * Create a new Pool, given the implementation of Creator, which must be - * able to create/destroy T objects at will. - * - * @param creator - */ - public Pool(Creator creator) { - count = spares = 0; - this.creator = creator; - list = new LinkedList<>(); - logger = Log.NULL; - } - - /** - * Attach Pool Logging activities to any other Logging Mechanism. - * @param logger - */ - public void setLogger(Log logger) { - this.logger = logger; - } - - public void log(Object ...objects) { - logger.log(objects); - } + /** + * Create a new Pool, given the implementation of Creator, which must be + * able to create/destroy T objects at will. + * + * @param creator + */ + public Pool(Creator creator) { + count = spares = 0; + this.creator = creator; + list = new LinkedList<>(); + logger = Log.NULL; + } + + /** + * Attach Pool Logging activities to any other Logging Mechanism. + * @param logger + */ + public void setLogger(Log logger) { + this.logger = logger; + } + + public void log(Object ...objects) { + logger.log(objects); + } - /** - * Preallocate a certain number of T Objects. Useful for services so that - * the first transactions don't get hit with all the Object creation costs - * - * @param lt - * @param prime - * @throws CadiException - */ - public void prime(int prime) throws CadiException { - for (int i = 0; i < prime; ++i) { - Pooled pt = new Pooled(creator.create(), this); - synchronized (list) { - list.addFirst(pt); - ++count; - } - } + /** + * Preallocate a certain number of T Objects. Useful for services so that + * the first transactions don't get hit with all the Object creation costs + * + * @param lt + * @param prime + * @throws CadiException + */ + public void prime(int prime) throws CadiException { + for (int i = 0; i < prime; ++i) { + Pooled pt = new Pooled(creator.create(), this); + synchronized (list) { + list.addFirst(pt); + ++count; + } + } - } + } - /** - * Destroy and remove all remaining objects. This is valuable for closing - * down all Allocated objects cleanly for exiting. It is also a good method - * for removing objects when, for instance, all Objects are invalid because - * of broken connections, etc. - */ - public void drain() { - synchronized (list) { - for (int i = 0; i < list.size(); ++i) { - Pooled pt = list.remove(); - creator.destroy(pt.content); - logger.log("Pool drained ", creator.toString()); - } - count = spares = 0; - } + /** + * Destroy and remove all remaining objects. This is valuable for closing + * down all Allocated objects cleanly for exiting. It is also a good method + * for removing objects when, for instance, all Objects are invalid because + * of broken connections, etc. + */ + public void drain() { + synchronized (list) { + for (int i = 0; i < list.size(); ++i) { + Pooled pt = list.remove(); + creator.destroy(pt.content); + logger.log("Pool drained ", creator.toString()); + } + count = spares = 0; + } - } + } - /** - * This is the essential function for Pool. Get an Object "T" inside a - * "Pooled" object. If there is a spare Object, then use it. If not, then - * create and pass back. - * - * This one uses a Null LogTarget - * - * IMPORTANT: When the use of this object is done (and the object is still - * in a valid state), then "done()" should be called immediately to allow - * the object to be reused. That is the point of the Pool... - * - * If the Object is in an invalid state, then "toss()" should be used so the - * Pool doesn't pass on invalid objects to others. - * - * @param lt - * @return - * @throws CadiException - */ - public Pooled get() throws CadiException { - Pooled pt; - synchronized (list) { - if (list.isEmpty()) { - pt = null; - } else { - pt = list.removeLast(); - --count; - creator.reuse(pt.content); - } - } - if (pt == null) { - if (spares < max_range) - ++spares; - pt = new Pooled(creator.create(), this); - } else { - if (spares > 1) - --spares; - } - return pt; - } + /** + * This is the essential function for Pool. Get an Object "T" inside a + * "Pooled" object. If there is a spare Object, then use it. If not, then + * create and pass back. + * + * This one uses a Null LogTarget + * + * IMPORTANT: When the use of this object is done (and the object is still + * in a valid state), then "done()" should be called immediately to allow + * the object to be reused. That is the point of the Pool... + * + * If the Object is in an invalid state, then "toss()" should be used so the + * Pool doesn't pass on invalid objects to others. + * + * @param lt + * @return + * @throws CadiException + */ + public Pooled get() throws CadiException { + Pooled pt; + synchronized (list) { + if (list.isEmpty()) { + pt = null; + } else { + pt = list.removeLast(); + --count; + creator.reuse(pt.content); + } + } + if (pt == null) { + if (spares < max_range) + ++spares; + pt = new Pooled(creator.create(), this); + } else { + if (spares > 1) + --spares; + } + return pt; + } - /** - * This function will validate whether the Objects are still in a usable - * state. If not, they are tossed from the Pool. This is valuable to have - * when Remote Connections go down, and there is a question on whether the - * Pooled Objects are still functional. - * - * @return - */ - public boolean validate() { - boolean rv = true; - synchronized (list) { - for (Iterator> iter = list.iterator(); iter.hasNext();) { - Pooled t = iter.next(); - if (!creator.isValid(t.content)) { - rv = false; - t.toss(); - iter.remove(); - } - } - } - return rv; - } + /** + * This function will validate whether the Objects are still in a usable + * state. If not, they are tossed from the Pool. This is valuable to have + * when Remote Connections go down, and there is a question on whether the + * Pooled Objects are still functional. + * + * @return + */ + public boolean validate() { + boolean rv = true; + synchronized (list) { + for (Iterator> iter = list.iterator(); iter.hasNext();) { + Pooled t = iter.next(); + if (!creator.isValid(t.content)) { + rv = false; + t.toss(); + iter.remove(); + } + } + } + return rv; + } - /** - * This is an internal method, used only by the Internal Pooled class. - * - * The Pooled class "offers" it's Object back after use. It is an - * "offer", because Pool will simply destroy and remove the object if it has - * more than enough spares. - * - * @param lt - * @param used - * @return - */ - // Used only by Pooled - private boolean offer(Pooled used) { - if (count < spares) { - synchronized (list) { - list.addFirst(used); - ++count; - } - logger.log("Pool recovered ", creator); - } else { - logger.log("Pool destroyed ", creator); - creator.destroy(used.content); - } - return false; - } + /** + * This is an internal method, used only by the Internal Pooled class. + * + * The Pooled class "offers" it's Object back after use. It is an + * "offer", because Pool will simply destroy and remove the object if it has + * more than enough spares. + * + * @param lt + * @param used + * @return + */ + // Used only by Pooled + private boolean offer(Pooled used) { + if (count < spares) { + synchronized (list) { + list.addFirst(used); + ++count; + } + logger.log("Pool recovered ", creator); + } else { + logger.log("Pool destroyed ", creator); + creator.destroy(used.content); + } + return false; + } - /** - * The Creator Interface give the Pool the ability to Create, Destroy and - * Validate the Objects it is maintaining. Thus, it is a specially written - * Implementation for each type. - * - * @author Jonathan - * - * @param - */ - public interface Creator { - public T create() throws CadiException; + /** + * The Creator Interface give the Pool the ability to Create, Destroy and + * Validate the Objects it is maintaining. Thus, it is a specially written + * Implementation for each type. + * + * @author Jonathan + * + * @param + */ + public interface Creator { + public T create() throws CadiException; - public void destroy(T t); + public void destroy(T t); - public boolean isValid(T t); + public boolean isValid(T t); - public void reuse(T t); - } + public void reuse(T t); + } - public interface Log { - public void log(Object ... o); - - public final static Log NULL = new Log() { - @Override - public void log(Object ... o) { - } - }; - } - /** - * The "Pooled" class is the transient class that wraps the actual Object - * T for API use/ It gives the ability to return ("done()", or "toss()") the - * Object to the Pool when processing is finished. - * - * For Safety, i.e. to avoid memory leaks and invalid Object States, there - * is a "finalize" method. It is strictly for when coder forgets to return - * the object, or perhaps hasn't covered the case during Exceptions or - * Runtime Exceptions with finally (preferred). This should not be - * considered normal procedure, as finalize() is called at an undetermined - * time during garbage collection, and is thus rather useless for a Pool. - * However, we don't want Coding Mistakes to put the whole program in an - * invalid state, so if something happened such that "done()" or "toss()" - * were not called, the resource is still cleaned up as well as possible. - * - * @author Jonathan - * - * @param - */ - public static class Pooled { - public final T content; - private Pool pool; + public interface Log { + public void log(Object ... o); + + public final static Log NULL = new Log() { + @Override + public void log(Object ... o) { + } + }; + } + /** + * The "Pooled" class is the transient class that wraps the actual Object + * T for API use/ It gives the ability to return ("done()", or "toss()") the + * Object to the Pool when processing is finished. + * + * For Safety, i.e. to avoid memory leaks and invalid Object States, there + * is a "finalize" method. It is strictly for when coder forgets to return + * the object, or perhaps hasn't covered the case during Exceptions or + * Runtime Exceptions with finally (preferred). This should not be + * considered normal procedure, as finalize() is called at an undetermined + * time during garbage collection, and is thus rather useless for a Pool. + * However, we don't want Coding Mistakes to put the whole program in an + * invalid state, so if something happened such that "done()" or "toss()" + * were not called, the resource is still cleaned up as well as possible. + * + * @author Jonathan + * + * @param + */ + public static class Pooled { + public final T content; + private Pool pool; - /** - * Create the Wrapping Object Pooled. - * - * @param t - * @param pool - * @param logTarget - */ - public Pooled(T t, Pool pool) { - content = t; - this.pool = pool; + /** + * Create the Wrapping Object Pooled. + * + * @param t + * @param pool + * @param logTarget + */ + public Pooled(T t, Pool pool) { + content = t; + this.pool = pool; - } + } - /** - * This is the key API for the Pool, as calling "done()" offers this - * object back to the Pool for reuse. - * - * Do not use the Pooled object again after calling "done()". - */ - public void done() { - if (pool != null) { - pool.offer(this); - } - } + /** + * This is the key API for the Pool, as calling "done()" offers this + * object back to the Pool for reuse. + * + * Do not use the Pooled object again after calling "done()". + */ + public void done() { + if (pool != null) { + pool.offer(this); + } + } - /** - * The user of the Object may discover that the Object t is no longer in - * a valid state. Don't put Garbage back in the Refrigerator... Toss it, - * if it's no longer valid. - * - * toss() is also used for draining the Pool, etc. - * - * toss() will attempt to destroy the Object by using the Creator - * Interface. - * - */ - public void toss() { - if (pool != null) { - pool.creator.destroy(content); - } - // Don't allow finalize to put it back in. - pool = null; - } + /** + * The user of the Object may discover that the Object t is no longer in + * a valid state. Don't put Garbage back in the Refrigerator... Toss it, + * if it's no longer valid. + * + * toss() is also used for draining the Pool, etc. + * + * toss() will attempt to destroy the Object by using the Creator + * Interface. + * + */ + public void toss() { + if (pool != null) { + pool.creator.destroy(content); + } + // Don't allow finalize to put it back in. + pool = null; + } - /** - * Just in case someone neglected to offer back object... Do not rely on - * this, as there is no specific time when finalize is called, which - * rather defeats the purpose of a Pool. - */ - @Override - protected void finalize() throws Throwable { - if (pool != null) { - done(); - pool = null; - } - } - } + /** + * Just in case someone neglected to offer back object... Do not rely on + * this, as there is no specific time when finalize is called, which + * rather defeats the purpose of a Pool. + */ + @Override + protected void finalize() throws Throwable { + if (pool != null) { + done(); + pool = null; + } + } + } - /** - * Get the maximum number of spare objects allowed at any moment - * - * @return - */ - public int getMaxRange() { - return max_range; - } + /** + * Get the maximum number of spare objects allowed at any moment + * + * @return + */ + public int getMaxRange() { + return max_range; + } - /** - * Set a Max Range for numbers of spare objects waiting to be used. - * - * No negative numbers are allowed - * - * @return - */ - public void setMaxRange(int max_range) { - // Do not allow negative numbers - this.max_range = Math.max(0, max_range); - } + /** + * Set a Max Range for numbers of spare objects waiting to be used. + * + * No negative numbers are allowed + * + * @return + */ + public void setMaxRange(int max_range) { + // Do not allow negative numbers + this.max_range = Math.max(0, max_range); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java index 3fa9a3f1..a2c76967 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java @@ -31,84 +31,84 @@ package org.onap.aaf.cadi.util; */ public class Split { - public static String[] split(char c, String value) { - return split(c,value,0,value.length()); - } + public static String[] split(char c, String value) { + return split(c,value,0,value.length()); + } - public static String[] split(char c, String value, int start, int end) { - if(value==null) { - return new String[0]; - } + public static String[] split(char c, String value, int start, int end) { + if(value==null) { + return new String[0]; + } - // Count items to preallocate Array (memory alloc is more expensive than counting twice) - int count,idx; - for(count=1,idx=value.indexOf(c,start);idx>=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && count0) { - rv[++count]=value.substring(last,idx).trim(); - } else { - rv[++count]=value.substring(last).trim(); - } - } - return rv; - } + int idx; + String[] rv = new String[size]; + if(size==1) { + rv[0]=value.trim(); + } else { + int last=0; + int count=-1; + size-=2; + for(idx=value.indexOf(c);idx>=0 && count0) { + rv[++count]=value.substring(last,idx).trim(); + } else { + rv[++count]=value.substring(last).trim(); + } + } + return rv; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java index b7dd0148..5cab15f6 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java @@ -27,44 +27,44 @@ import java.io.InputStreamReader; // Substandard, because System.in doesn't do Passwords.. public class SubStandardConsole implements MyConsole { - private final static char[] BLANK = new char[0]; - private final BufferedReader br; + private final static char[] BLANK = new char[0]; + private final BufferedReader br; - public SubStandardConsole() { - br = new BufferedReader(new InputStreamReader(System.in)); - } - - @Override - public String readLine(String fmt, Object... args) { - String rv; - try { - System.out.printf(fmt,args); - rv = br.readLine(); - if(args.length==1 && rv.length()==0) { - rv = args[0].toString(); - } - } catch (IOException e) { - System.err.println("uh oh..."); - rv = ""; - } - return rv; - } + public SubStandardConsole() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + @Override + public String readLine(String fmt, Object... args) { + String rv; + try { + System.out.printf(fmt,args); + rv = br.readLine(); + if(args.length==1 && rv.length()==0) { + rv = args[0].toString(); + } + } catch (IOException e) { + System.err.println("uh oh..."); + rv = ""; + } + return rv; + } - @Override - public char[] readPassword(String fmt, Object... args) { - try { - System.out.printf(fmt,args); - String response = br.readLine(); - return response==null?BLANK:response.toCharArray(); + @Override + public char[] readPassword(String fmt, Object... args) { + try { + System.out.printf(fmt,args); + String response = br.readLine(); + return response==null?BLANK:response.toCharArray(); - } catch (IOException e) { - System.err.println("uh oh..."); - return BLANK; - } - } + } catch (IOException e) { + System.err.println("uh oh..."); + return BLANK; + } + } - @Override - public void printf(String fmt, Object... args) { - System.out.printf(fmt, args); - } + @Override + public void printf(String fmt, Object... args) { + System.out.printf(fmt, args); + } } \ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java index 4c5d35b7..9ddd0626 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java @@ -22,26 +22,26 @@ package org.onap.aaf.cadi.util; public class TheConsole implements MyConsole { - @Override - public String readLine(String fmt, Object... args) { - String rv = System.console().readLine(fmt, args); - if(args.length>0 && args[0]!=null && rv.length()==0) { - rv = args[0].toString(); - } - return rv; - } + @Override + public String readLine(String fmt, Object... args) { + String rv = System.console().readLine(fmt, args); + if(args.length>0 && args[0]!=null && rv.length()==0) { + rv = args[0].toString(); + } + return rv; + } - @Override - public char[] readPassword(String fmt, Object... args) { - return System.console().readPassword(fmt, args); - } - - public static boolean implemented() { - return System.console()!=null; - } + @Override + public char[] readPassword(String fmt, Object... args) { + return System.console().readPassword(fmt, args); + } + + public static boolean implemented() { + return System.console()!=null; + } - @Override - public void printf(String fmt, Object... args) { - System.console().printf(fmt, args); - } + @Override + public void printf(String fmt, Object... args) { + System.console().printf(fmt, args); + } } \ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Timing.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Timing.java index 82bd389a..529849de 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Timing.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Timing.java @@ -21,7 +21,7 @@ package org.onap.aaf.cadi.util; public class Timing { - public static float millis(final long start) { - return (System.nanoTime() - start) / 1000000f; - } + public static float millis(final long start) { + return (System.nanoTime() - start) / 1000000f; + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java index a8c0690f..ff74f39c 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java @@ -24,54 +24,54 @@ package org.onap.aaf.cadi.util; import org.onap.aaf.cadi.UserChain; public class UserChainManip { - /** - Build an element in the correct format for UserChain. - Format:::[:AS][,::]* - @see UserChain - */ - public static StringBuilder build(StringBuilder sb, String app, String id, UserChain.Protocol proto, boolean as) { - boolean mayAs; - if(!(mayAs=sb.length()==0)) { - sb.append(','); - } - sb.append(app); - sb.append(':'); - sb.append(id); - sb.append(':'); - sb.append(proto.name()); - if(as && mayAs) { - sb.append(":AS"); - } - return sb; - } - - public static String idToNS(String id) { - if(id==null) { - return ""; - } else { - StringBuilder sb = new StringBuilder(); - char c; - int end; - boolean first = true; - for(int idx = end = id.length()-1;idx>=0;--idx) { - if((c = id.charAt(idx))=='@' || c=='.') { - if(idx::[:AS][,::]* + @see UserChain + */ + public static StringBuilder build(StringBuilder sb, String app, String id, UserChain.Protocol proto, boolean as) { + boolean mayAs; + if(!(mayAs=sb.length()==0)) { + sb.append(','); + } + sb.append(app); + sb.append(':'); + sb.append(id); + sb.append(':'); + sb.append(proto.name()); + if(as && mayAs) { + sb.append(":AS"); + } + return sb; + } + + public static String idToNS(String id) { + if(id==null) { + return ""; + } else { + StringBuilder sb = new StringBuilder(); + char c; + int end; + boolean first = true; + for(int idx = end = id.length()-1;idx>=0;--idx) { + if((c = id.charAt(idx))=='@' || c=='.') { + if(idx vars) { - String[] array = new String[vars.size()]; - StringBuilder sb = new StringBuilder(); - convert(sb,text,vars.toArray(array)); - return sb.toString(); - } - /** - * Convert a format string with "%s" into AT&T RESTful Error %1 %2 (number) format - * If "holder" is passed in, it is built with full Message extracted (typically for Logging) - * @param holder - * @param text - * @param vars - * @return - */ - public static String convert(final StringBuilder holder, final String text, final String ... vars) { - StringBuilder sb = null; - int idx,index=0,prev = 0; - - if(text.contains("%s")) { - sb = new StringBuilder(); - } - - StringBuilder[] sbs = new StringBuilder[] {sb,holder}; - boolean replace, clearIndex = false; - int c; - while((idx=text.indexOf('%',prev))>=0) { - replace = false; - if(clearIndex) { - index=0; - } - if(sb!=null) { - sb.append(text,prev,idx); - } - if(holder!=null) { - holder.append(text,prev,idx); - } - - boolean go = true; - while(go) { - if(text.length()>++idx) { - switch(c=text.charAt(idx)) { - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - index *=10; - index +=(c-'0'); - clearIndex=replace=true; - continue; - case 's': - ++index; - replace = true; - continue; - default: - break; - } - } - prev = idx; - go=false; - if(replace) { - if(sb!=null) { - sb.append('%'); - sb.append(index); - } - if(index<=vars.length) { - if(holder!=null) { - holder.append(vars[index-1]); - } - } - } else { - for(StringBuilder s : sbs) { - if(s!=null) { - s.append("%"); - } - } - } - } - } - - if(sb!=null) { - sb.append(text,prev,text.length()); - } - if(holder!=null) { - holder.append(text,prev,text.length()); - } + /** + * Simplified Conversion based on typical use of getting AT&T style RESTful Error Messages + * @param text + * @param vars + * @return + */ + public static String convert(final String text, final List vars) { + String[] array = new String[vars.size()]; + StringBuilder sb = new StringBuilder(); + convert(sb,text,vars.toArray(array)); + return sb.toString(); + } + /** + * Convert a format string with "%s" into AT&T RESTful Error %1 %2 (number) format + * If "holder" is passed in, it is built with full Message extracted (typically for Logging) + * @param holder + * @param text + * @param vars + * @return + */ + public static String convert(final StringBuilder holder, final String text, final String ... vars) { + StringBuilder sb = null; + int idx,index=0,prev = 0; + + if(text.contains("%s")) { + sb = new StringBuilder(); + } + + StringBuilder[] sbs = new StringBuilder[] {sb,holder}; + boolean replace, clearIndex = false; + int c; + while((idx=text.indexOf('%',prev))>=0) { + replace = false; + if(clearIndex) { + index=0; + } + if(sb!=null) { + sb.append(text,prev,idx); + } + if(holder!=null) { + holder.append(text,prev,idx); + } + + boolean go = true; + while(go) { + if(text.length()>++idx) { + switch(c=text.charAt(idx)) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + index *=10; + index +=(c-'0'); + clearIndex=replace=true; + continue; + case 's': + ++index; + replace = true; + continue; + default: + break; + } + } + prev = idx; + go=false; + if(replace) { + if(sb!=null) { + sb.append('%'); + sb.append(index); + } + if(index<=vars.length) { + if(holder!=null) { + holder.append(vars[index-1]); + } + } + } else { + for(StringBuilder s : sbs) { + if(s!=null) { + s.append("%"); + } + } + } + } + } + + if(sb!=null) { + sb.append(text,prev,text.length()); + } + if(holder!=null) { + holder.append(text,prev,text.length()); + } - return sb==null?text:sb.toString(); - } + return sb==null?text:sb.toString(); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Action.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Action.java index dff18acd..ebcfa9f7 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Action.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Action.java @@ -33,5 +33,5 @@ package org.onap.aaf.cadi.wsse; * @param */ interface Action { - public boolean content(OUTPUT output, String text); + public boolean content(OUTPUT output, String text); } \ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java index 2582bc17..38322307 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java @@ -44,87 +44,87 @@ import javax.xml.stream.events.XMLEvent; */ //@SuppressWarnings("restriction") public class Match { - private QName qname; - private Match[] next; - private Match prev; - private Action action = null; - private boolean stopAfter; - private boolean exclusive; - + private QName qname; + private Match[] next; + private Match prev; + private Action action = null; + private boolean stopAfter; + private boolean exclusive; + - @SafeVarargs - public Match(String ns, String name, Match ... next) { - this.qname = new QName(ns,name); - this.next = next; - stopAfter = exclusive = false; - for(Match m : next) { // add the possible tags to look for - if(!m.stopAfter)m.prev = this; - } - } - - public Match onMatch(OUTPUT output, XReader reader) throws XMLStreamException { - while(reader.hasNext()) { - XEvent event = reader.nextEvent(); - switch(event.getEventType()) { - case XMLEvent.START_ELEMENT: - QName e_qname = event.asStartElement().getName(); - //System.out.println("Start - " + e_qname); - boolean match = false; - for(Match m : next) { - if(e_qname.equals(m.qname)) { - match=true; - if(m.onMatch(output, reader)==null) { - return null; // short circuit Parsing - } - break; - } - } - if(exclusive && !match) // When Tag MUST be present, i.e. the Root Tag, versus info we're not interested in - return null; - break; - case XMLEvent.CHARACTERS: - //System.out.println("Data - " +event.asCharacters().getData()); - if(action!=null) { - if(!action.content(output,event.asCharacters().getData())) { - return null; - } - } - break; - case XMLEvent.END_ELEMENT: - //System.out.println("End - " + event.asEndElement().getName()); - if(event.asEndElement().getName().equals(qname)) { - return prev; - } - break; - case XMLEvent.END_DOCUMENT: - return null; // Exit Chain - } - } - return this; - } + @SafeVarargs + public Match(String ns, String name, Match ... next) { + this.qname = new QName(ns,name); + this.next = next; + stopAfter = exclusive = false; + for(Match m : next) { // add the possible tags to look for + if(!m.stopAfter)m.prev = this; + } + } + + public Match onMatch(OUTPUT output, XReader reader) throws XMLStreamException { + while(reader.hasNext()) { + XEvent event = reader.nextEvent(); + switch(event.getEventType()) { + case XMLEvent.START_ELEMENT: + QName e_qname = event.asStartElement().getName(); + //System.out.println("Start - " + e_qname); + boolean match = false; + for(Match m : next) { + if(e_qname.equals(m.qname)) { + match=true; + if(m.onMatch(output, reader)==null) { + return null; // short circuit Parsing + } + break; + } + } + if(exclusive && !match) // When Tag MUST be present, i.e. the Root Tag, versus info we're not interested in + return null; + break; + case XMLEvent.CHARACTERS: + //System.out.println("Data - " +event.asCharacters().getData()); + if(action!=null) { + if(!action.content(output,event.asCharacters().getData())) { + return null; + } + } + break; + case XMLEvent.END_ELEMENT: + //System.out.println("End - " + event.asEndElement().getName()); + if(event.asEndElement().getName().equals(qname)) { + return prev; + } + break; + case XMLEvent.END_DOCUMENT: + return null; // Exit Chain + } + } + return this; + } - /** - * When this Matched Tag has completed, Stop parsing and end - * @return - */ - public Match stopAfter() { - stopAfter = true; - return this; - } - - /** - * Mark that this Object MUST be matched at this level or stop parsing and end - * - * @param action - * @return - */ - public Match exclusive() { - exclusive = true; - return this; - } + /** + * When this Matched Tag has completed, Stop parsing and end + * @return + */ + public Match stopAfter() { + stopAfter = true; + return this; + } + + /** + * Mark that this Object MUST be matched at this level or stop parsing and end + * + * @param action + * @return + */ + public Match exclusive() { + exclusive = true; + return this; + } - public Match set(Action action) { - this.action = action; - return this; - } + public Match set(Action action) { + this.action = action; + return this; + } } \ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java index 017337b1..787f1b4b 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java @@ -42,42 +42,42 @@ import org.onap.aaf.cadi.BasicCred; * @author Jonathan */ public class WSSEParser { - private static final String SOAP_NS = "http://schemas.xmlsoap.org/soap/envelope/"; - private static final String WSSE_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; - private Match parseTree; + private static final String SOAP_NS = "http://schemas.xmlsoap.org/soap/envelope/"; + private static final String WSSE_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; + private Match parseTree; - public WSSEParser() { - // soap:Envelope/soap:Header/wsse:Security/wsse:UsernameToken/[wsse:Password&wsse:Username] - parseTree = new Match(SOAP_NS,"root", // need a root level to start from... Doesn't matter what the tag is - new Match(SOAP_NS,"Envelope", - new Match(SOAP_NS,"Header", - new Match(WSSE_NS,"Security", - new Match(WSSE_NS,"UsernameToken", - new Match(WSSE_NS,"Password").set(new Action() { - public boolean content(BasicCred bc,String text) { - bc.setCred(text.getBytes()); - return true; - } - }), - new Match(WSSE_NS,"Username").set(new Action() { - public boolean content(BasicCred bc,String text) { - bc.setUser(text); - return true; - } - }) - ).stopAfter() // if found, end when UsernameToken ends (no further processing needed) - ) - ).stopAfter() // Stop Processing when Header Ends - ).exclusive()// Envelope must match Header, and no other. FYI, Body comes after Header short circuits (see above), so it's ok - ).exclusive(); // root must be Envelope - } - - public XMLStreamException parse(BasicCred bc, InputStream is) { - try { - parseTree.onMatch(bc, new XReader(is)); - return null; - } catch (XMLStreamException e) { - return e; - } - } + public WSSEParser() { + // soap:Envelope/soap:Header/wsse:Security/wsse:UsernameToken/[wsse:Password&wsse:Username] + parseTree = new Match(SOAP_NS,"root", // need a root level to start from... Doesn't matter what the tag is + new Match(SOAP_NS,"Envelope", + new Match(SOAP_NS,"Header", + new Match(WSSE_NS,"Security", + new Match(WSSE_NS,"UsernameToken", + new Match(WSSE_NS,"Password").set(new Action() { + public boolean content(BasicCred bc,String text) { + bc.setCred(text.getBytes()); + return true; + } + }), + new Match(WSSE_NS,"Username").set(new Action() { + public boolean content(BasicCred bc,String text) { + bc.setUser(text); + return true; + } + }) + ).stopAfter() // if found, end when UsernameToken ends (no further processing needed) + ) + ).stopAfter() // Stop Processing when Header Ends + ).exclusive()// Envelope must match Header, and no other. FYI, Body comes after Header short circuits (see above), so it's ok + ).exclusive(); // root must be Envelope + } + + public XMLStreamException parse(BasicCred bc, InputStream is) { + try { + parseTree.onMatch(bc, new XReader(is)); + return null; + } catch (XMLStreamException e) { + return e; + } + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XEvent.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XEvent.java index 12de366e..187d5b1e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XEvent.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XEvent.java @@ -38,98 +38,98 @@ import javax.xml.stream.events.XMLEvent; // @SuppressWarnings("restriction") public abstract class XEvent { - public abstract int getEventType(); + public abstract int getEventType(); - public StartElement asStartElement() { - return (StartElement)this; - } + public StartElement asStartElement() { + return (StartElement)this; + } - public Characters asCharacters() { - return (Characters)this; - } + public Characters asCharacters() { + return (Characters)this; + } - public EndElement asEndElement() { - return (EndElement)this; - } + public EndElement asEndElement() { + return (EndElement)this; + } public static abstract class NamedXEvent extends XEvent { - private QName qname; - - public NamedXEvent(QName qname) { - this.qname = qname; - } - - public QName getName() { - return qname; - } + private QName qname; + + public NamedXEvent(QName qname) { + this.qname = qname; + } + + public QName getName() { + return qname; + } + } + public static class StartElement extends NamedXEvent { + + public StartElement(String ns, String tag) { + super(new QName(ns,tag)); + } + + @Override + public int getEventType() { + return XMLEvent.START_ELEMENT; + } + } + + public static class EndElement extends NamedXEvent { + public EndElement(String ns, String tag) { + super(new QName(ns,tag)); + } + + @Override + public int getEventType() { + return XMLEvent.END_ELEMENT; + } + } + + public static class Characters extends XEvent { + private String data; + + public Characters(String data) { + this.data = data; + } + @Override + public int getEventType() { + return XMLEvent.CHARACTERS; + } + + public String getData() { + return data; + } + } + + public static class StartDocument extends XEvent { + + @Override + public int getEventType() { + return XMLEvent.START_DOCUMENT; + } + + } + + public static class EndDocument extends XEvent { + + @Override + public int getEventType() { + return XMLEvent.END_DOCUMENT; + } + + } + public static class Comment extends XEvent { + public final String value; + public Comment(String value) { + this.value = value; + } + + @Override + public int getEventType() { + return XMLEvent.COMMENT; + } + } - public static class StartElement extends NamedXEvent { - - public StartElement(String ns, String tag) { - super(new QName(ns,tag)); - } - - @Override - public int getEventType() { - return XMLEvent.START_ELEMENT; - } - } - - public static class EndElement extends NamedXEvent { - public EndElement(String ns, String tag) { - super(new QName(ns,tag)); - } - - @Override - public int getEventType() { - return XMLEvent.END_ELEMENT; - } - } - - public static class Characters extends XEvent { - private String data; - - public Characters(String data) { - this.data = data; - } - @Override - public int getEventType() { - return XMLEvent.CHARACTERS; - } - - public String getData() { - return data; - } - } - - public static class StartDocument extends XEvent { - - @Override - public int getEventType() { - return XMLEvent.START_DOCUMENT; - } - - } - - public static class EndDocument extends XEvent { - - @Override - public int getEventType() { - return XMLEvent.END_DOCUMENT; - } - - } - public static class Comment extends XEvent { - public final String value; - public Comment(String value) { - this.value = value; - } - - @Override - public int getEventType() { - return XMLEvent.COMMENT; - } - - } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java index 78265e4b..b7cc40ad 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java @@ -49,379 +49,379 @@ import javax.xml.stream.XMLStreamException; */ // @SuppressWarnings("restriction") public class XReader { - private XEvent curr,another; - private InputStream is; - private ByteArrayOutputStream baos; - private int state, count, last; - - private Stack> nsses; - - public XReader(InputStream is) { - this.is = is; - curr = another = null; - baos = new ByteArrayOutputStream(); - state = BEGIN_DOC; - count = 0; - nsses = new Stack>(); - } - - public boolean hasNext() throws XMLStreamException { - if(curr==null) { - curr = parse(); - } - return curr!=null; - } + private XEvent curr,another; + private InputStream is; + private ByteArrayOutputStream baos; + private int state, count, last; + + private Stack> nsses; + + public XReader(InputStream is) { + this.is = is; + curr = another = null; + baos = new ByteArrayOutputStream(); + state = BEGIN_DOC; + count = 0; + nsses = new Stack>(); + } + + public boolean hasNext() throws XMLStreamException { + if(curr==null) { + curr = parse(); + } + return curr!=null; + } - public XEvent nextEvent() { - XEvent xe = curr; - curr = null; - return xe; - } + public XEvent nextEvent() { + XEvent xe = curr; + curr = null; + return xe; + } - // - // State Flags - // - // Note: The State of parsing XML can be complicated. There are too many to cleanly keep in "booleans". Additionally, - // there are certain checks that can be better made with Bitwise operations within switches - // Keeping track of state this way also helps us to accomplish logic without storing any back characters except one - private final static int BEGIN_DOC= 0x000001; - private final static int DOC_TYPE= 0x000002; - private final static int QUESTION_F= 0x000004; - private final static int QUESTION = 0x000008; - private final static int START_TAG = 0x000010; - private final static int END_TAG = 0x000020; - private final static int VALUE= 0x000040; - private final static int COMMENT = 0x001000; - private final static int COMMENT_E = 0x002000; - private final static int COMMENT_D1 =0x010000; - private final static int COMMENT_D2 =0x020000; - private final static int COMMENT_D3 =0x040000; - private final static int COMMENT_D4 =0x080000; - // useful combined Comment states - private final static int IN_COMMENT=COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2; - private final static int COMPLETE_COMMENT = COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2|COMMENT_D3|COMMENT_D4; - - - private XEvent parse() throws XMLStreamException { - Map nss = nsses.isEmpty()?null:nsses.peek(); + // + // State Flags + // + // Note: The State of parsing XML can be complicated. There are too many to cleanly keep in "booleans". Additionally, + // there are certain checks that can be better made with Bitwise operations within switches + // Keeping track of state this way also helps us to accomplish logic without storing any back characters except one + private final static int BEGIN_DOC= 0x000001; + private final static int DOC_TYPE= 0x000002; + private final static int QUESTION_F= 0x000004; + private final static int QUESTION = 0x000008; + private final static int START_TAG = 0x000010; + private final static int END_TAG = 0x000020; + private final static int VALUE= 0x000040; + private final static int COMMENT = 0x001000; + private final static int COMMENT_E = 0x002000; + private final static int COMMENT_D1 =0x010000; + private final static int COMMENT_D2 =0x020000; + private final static int COMMENT_D3 =0x040000; + private final static int COMMENT_D4 =0x080000; + // useful combined Comment states + private final static int IN_COMMENT=COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2; + private final static int COMPLETE_COMMENT = COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2|COMMENT_D3|COMMENT_D4; + + + private XEvent parse() throws XMLStreamException { + Map nss = nsses.isEmpty()?null:nsses.peek(); - XEvent rv; - if((rv=another)!=null) { // "another" is a tag that may have needed to be created, but not - // immediately returned. Save for next parse. If necessary, this could be turned into - // a FIFO storage, but a single reference is enough for now. - another = null; // "rv" is now set for the Event, and will be returned. Set to Null. - } else { - boolean go = true; - int c=0; - - try { - while(go && (c=is.read())>=0) { - ++count; - switch(c) { - case '<': // Tag is opening - state|=~BEGIN_DOC; // remove BEGIN_DOC flag, this is possibly an XML Doc - XEvent cxe = null; - if(baos.size()>0) { // If there are any characters between tags, we send as Character Event - String chars = baos.toString().trim(); // Trim out WhiteSpace before and after - if(chars.length()>0) { // don't send if Characters were only whitespace - cxe = new XEvent.Characters(chars); - baos.reset(); - go = false; - } - } - last = c; // make sure "last" character is set for use in "ParseTag" - Tag t = parseTag(); // call subroutine to process the tag as a unit - String ns; - switch(t.state&(START_TAG|END_TAG)) { - case START_TAG: - nss = getNss(nss,t); // Only Start Tags might have NS Attributes - // Get any NameSpace elements from tag. If there are, nss will become - // a new Map with all the previous NSs plus the new. This provides - // scoping behavior when used with the Stack - // drop through on purpose - case END_TAG: - ns = t.prefix==null||nss==null?"":nss.get(t.prefix); // Get the namespace from prefix (if exists) - break; - default: - ns = ""; - } - if(ns==null) - throw new XMLStreamException("Invalid Namespace Prefix at " + count); - go = false; - switch(t.state) { // based on - case DOC_TYPE: - rv = new XEvent.StartDocument(); - break; - case COMMENT: - rv = new XEvent.Comment(t.value); - break; - case START_TAG: - rv = new XEvent.StartElement(ns,t.name); - nsses.push(nss); // Change potential scope for Namespace - break; - case END_TAG: - rv = new XEvent.EndElement(ns,t.name); - nss = nsses.pop(); // End potential scope for Namespace - break; - case START_TAG|END_TAG: // This tag is both start/end aka - rv = new XEvent.StartElement(ns,t.name); - if(last=='/')another = new XEvent.EndElement(ns,t.name); - } - if(cxe!=null) { // if there is a Character Event, it actually should go first. ow. - another = rv; // Make current Event the "another" or next event, and - rv = cxe; // send Character Event now - } - break; - case ' ': - case '\t': - case '\n': - if((state&BEGIN_DOC)==BEGIN_DOC) { // if Whitespace before doc, just ignore - break; - } - // fallthrough on purpose - default: - if((state&BEGIN_DOC)==BEGIN_DOC) { // if there is any data at the start other than XML Tag, it's not XML - throw new XMLStreamException("Parse Error: This is not an XML Doc"); - } - baos.write(c); // save off Characters - } - last = c; // Some processing needs to know what the last character was, aka Escaped characters... ex \" - } - } catch (IOException e) { - throw new XMLStreamException(e); // all errors parsing will be treated as XMLStreamErrors (like StAX) - } - if(c==-1 && (state&BEGIN_DOC)==BEGIN_DOC) { // Normally, end of stream is ok, however, we need to know if the - throw new XMLStreamException("Premature End of File"); // document isn't an XML document, so we throw exception if it - } // hasn't yet been determined to be an XML Doc - } - return rv; - } - - /** - * parseTag - * - * Parsing a Tag is somewhat complicated, so it's helpful to separate this process from the - * higher level Parsing effort - * @return - * @throws IOException - * @throws XMLStreamException - */ - private Tag parseTag() throws IOException, XMLStreamException { - Tag tag = null; - boolean go = true; - state = 0; - int c, quote=0; // If "quote" is 0, then we're not in a quote. We set ' (in pretag) or " in attribs accordingly to denote quoted - String prefix=null,name=null,value=null; - baos.reset(); - - while(go && (c=is.read())>=0) { - ++count; - if(quote!=0) { // If we're in a quote, we only end if we hit another quote of the same time, not preceded by \ - if(c==quote && last!='\\') { - quote=0; - } else { - baos.write(c); - } - } else if((state&COMMENT)==COMMENT) { // similar to Quote is being in a comment - switch(c) { - case '-': - switch(state) { // XML has a complicated Quote set... ... we keep track if each has been met with flags. - case COMMENT|COMMENT_E: - state|=COMMENT_D1; - break; - case COMMENT|COMMENT_E|COMMENT_D1: - state|=COMMENT_D2; - baos.reset(); // clear out "!--", it's a Comment - break; - case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2: - state|=COMMENT_D3; - baos.write(c); - break; - case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2|COMMENT_D3: - state|=COMMENT_D4; - baos.write(c); - break; - } - break; - case '>': // Tag indicator has been found, do we have all the comment characters in line? - if((state&COMPLETE_COMMENT)==COMPLETE_COMMENT) { - byte ba[] = baos.toByteArray(); - tag = new Tag(null,null, new String(ba,0,ba.length-2)); - baos.reset(); - go = false; - break; - } - // fall through on purpose - default: - state&=~(COMMENT_D3|COMMENT_D4); - if((state&IN_COMMENT)!=IN_COMMENT) state&=~IN_COMMENT; // false alarm, it's not actually a comment - baos.write(c); - } - } else { // Normal Tag Processing loop - switch(c) { - case '?': - switch(state & (QUESTION_F|QUESTION)) { // Validate the state of Doc tag... - case QUESTION_F: - state |= DOC_TYPE; - state &= ~QUESTION_F; - break; - case 0: - state |=QUESTION_F; - break; - default: - throw new IOException("Bad character [?] at " + count); - } - break; - case '!': - if(last=='<') { - state|=COMMENT|COMMENT_E; // likely a comment, continue processing in Comment Loop - } - baos.write(c); - break; - case '/': - state|=(last=='<'?END_TAG:(END_TAG|START_TAG)); // end tag indicator , ,or both - break; - case ':': - prefix=baos.toString(); // prefix indicator - baos.reset(); - break; - case '=': // used in Attributes - name=baos.toString(); - baos.reset(); - state|=VALUE; - break; - case '>': // end the tag, which causes end of this subprocess as well as formulation of the found data - go = false; - // passthrough on purpose - case ' ': - case '\t': - case '\n': // white space indicates change in internal tag state, ex between name and between attributes - if((state&VALUE)==VALUE) { - value = baos.toString(); // we're in VALUE state, add characters to Value - } else if(name==null) { - name = baos.toString(); // we're in Name state (default) add characters to Name - } - baos.reset(); // we've assigned chars, reset buffer - if(name!=null) { // Name is not null, there's a tag in the offing here... - Tag t = new Tag(prefix,name,value); - if(tag==null) { // Set as the tag to return, if not exists - tag = t; - } else { // if we already have a Tag, then we'll treat this one as an attribute - tag.add(t); - } - } - prefix=name=value=null; // reset these values in case we loop for attributes. - break; - case '\'': // is the character one of two kinds of quote? - case '"': - if(last!='\\') { - quote=c; - break; - } - // Fallthrough ok - default: - baos.write(c); // write any unprocessed bytes into buffer - - } - } - last = c; - } - int type = state&(DOC_TYPE|COMMENT|END_TAG|START_TAG); // get just the Tag states and turn into Type for Tag - if(type==0) { - type=START_TAG; - } - if(tag!=null) { - tag.state|=type; // add the appropriate Tag States - } - return tag; - } + XEvent rv; + if((rv=another)!=null) { // "another" is a tag that may have needed to be created, but not + // immediately returned. Save for next parse. If necessary, this could be turned into + // a FIFO storage, but a single reference is enough for now. + another = null; // "rv" is now set for the Event, and will be returned. Set to Null. + } else { + boolean go = true; + int c=0; + + try { + while(go && (c=is.read())>=0) { + ++count; + switch(c) { + case '<': // Tag is opening + state|=~BEGIN_DOC; // remove BEGIN_DOC flag, this is possibly an XML Doc + XEvent cxe = null; + if(baos.size()>0) { // If there are any characters between tags, we send as Character Event + String chars = baos.toString().trim(); // Trim out WhiteSpace before and after + if(chars.length()>0) { // don't send if Characters were only whitespace + cxe = new XEvent.Characters(chars); + baos.reset(); + go = false; + } + } + last = c; // make sure "last" character is set for use in "ParseTag" + Tag t = parseTag(); // call subroutine to process the tag as a unit + String ns; + switch(t.state&(START_TAG|END_TAG)) { + case START_TAG: + nss = getNss(nss,t); // Only Start Tags might have NS Attributes + // Get any NameSpace elements from tag. If there are, nss will become + // a new Map with all the previous NSs plus the new. This provides + // scoping behavior when used with the Stack + // drop through on purpose + case END_TAG: + ns = t.prefix==null||nss==null?"":nss.get(t.prefix); // Get the namespace from prefix (if exists) + break; + default: + ns = ""; + } + if(ns==null) + throw new XMLStreamException("Invalid Namespace Prefix at " + count); + go = false; + switch(t.state) { // based on + case DOC_TYPE: + rv = new XEvent.StartDocument(); + break; + case COMMENT: + rv = new XEvent.Comment(t.value); + break; + case START_TAG: + rv = new XEvent.StartElement(ns,t.name); + nsses.push(nss); // Change potential scope for Namespace + break; + case END_TAG: + rv = new XEvent.EndElement(ns,t.name); + nss = nsses.pop(); // End potential scope for Namespace + break; + case START_TAG|END_TAG: // This tag is both start/end aka + rv = new XEvent.StartElement(ns,t.name); + if(last=='/')another = new XEvent.EndElement(ns,t.name); + } + if(cxe!=null) { // if there is a Character Event, it actually should go first. ow. + another = rv; // Make current Event the "another" or next event, and + rv = cxe; // send Character Event now + } + break; + case ' ': + case '\t': + case '\n': + if((state&BEGIN_DOC)==BEGIN_DOC) { // if Whitespace before doc, just ignore + break; + } + // fallthrough on purpose + default: + if((state&BEGIN_DOC)==BEGIN_DOC) { // if there is any data at the start other than XML Tag, it's not XML + throw new XMLStreamException("Parse Error: This is not an XML Doc"); + } + baos.write(c); // save off Characters + } + last = c; // Some processing needs to know what the last character was, aka Escaped characters... ex \" + } + } catch (IOException e) { + throw new XMLStreamException(e); // all errors parsing will be treated as XMLStreamErrors (like StAX) + } + if(c==-1 && (state&BEGIN_DOC)==BEGIN_DOC) { // Normally, end of stream is ok, however, we need to know if the + throw new XMLStreamException("Premature End of File"); // document isn't an XML document, so we throw exception if it + } // hasn't yet been determined to be an XML Doc + } + return rv; + } + + /** + * parseTag + * + * Parsing a Tag is somewhat complicated, so it's helpful to separate this process from the + * higher level Parsing effort + * @return + * @throws IOException + * @throws XMLStreamException + */ + private Tag parseTag() throws IOException, XMLStreamException { + Tag tag = null; + boolean go = true; + state = 0; + int c, quote=0; // If "quote" is 0, then we're not in a quote. We set ' (in pretag) or " in attribs accordingly to denote quoted + String prefix=null,name=null,value=null; + baos.reset(); + + while(go && (c=is.read())>=0) { + ++count; + if(quote!=0) { // If we're in a quote, we only end if we hit another quote of the same time, not preceded by \ + if(c==quote && last!='\\') { + quote=0; + } else { + baos.write(c); + } + } else if((state&COMMENT)==COMMENT) { // similar to Quote is being in a comment + switch(c) { + case '-': + switch(state) { // XML has a complicated Quote set... ... we keep track if each has been met with flags. + case COMMENT|COMMENT_E: + state|=COMMENT_D1; + break; + case COMMENT|COMMENT_E|COMMENT_D1: + state|=COMMENT_D2; + baos.reset(); // clear out "!--", it's a Comment + break; + case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2: + state|=COMMENT_D3; + baos.write(c); + break; + case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2|COMMENT_D3: + state|=COMMENT_D4; + baos.write(c); + break; + } + break; + case '>': // Tag indicator has been found, do we have all the comment characters in line? + if((state&COMPLETE_COMMENT)==COMPLETE_COMMENT) { + byte ba[] = baos.toByteArray(); + tag = new Tag(null,null, new String(ba,0,ba.length-2)); + baos.reset(); + go = false; + break; + } + // fall through on purpose + default: + state&=~(COMMENT_D3|COMMENT_D4); + if((state&IN_COMMENT)!=IN_COMMENT) state&=~IN_COMMENT; // false alarm, it's not actually a comment + baos.write(c); + } + } else { // Normal Tag Processing loop + switch(c) { + case '?': + switch(state & (QUESTION_F|QUESTION)) { // Validate the state of Doc tag... + case QUESTION_F: + state |= DOC_TYPE; + state &= ~QUESTION_F; + break; + case 0: + state |=QUESTION_F; + break; + default: + throw new IOException("Bad character [?] at " + count); + } + break; + case '!': + if(last=='<') { + state|=COMMENT|COMMENT_E; // likely a comment, continue processing in Comment Loop + } + baos.write(c); + break; + case '/': + state|=(last=='<'?END_TAG:(END_TAG|START_TAG)); // end tag indicator , ,or both + break; + case ':': + prefix=baos.toString(); // prefix indicator + baos.reset(); + break; + case '=': // used in Attributes + name=baos.toString(); + baos.reset(); + state|=VALUE; + break; + case '>': // end the tag, which causes end of this subprocess as well as formulation of the found data + go = false; + // passthrough on purpose + case ' ': + case '\t': + case '\n': // white space indicates change in internal tag state, ex between name and between attributes + if((state&VALUE)==VALUE) { + value = baos.toString(); // we're in VALUE state, add characters to Value + } else if(name==null) { + name = baos.toString(); // we're in Name state (default) add characters to Name + } + baos.reset(); // we've assigned chars, reset buffer + if(name!=null) { // Name is not null, there's a tag in the offing here... + Tag t = new Tag(prefix,name,value); + if(tag==null) { // Set as the tag to return, if not exists + tag = t; + } else { // if we already have a Tag, then we'll treat this one as an attribute + tag.add(t); + } + } + prefix=name=value=null; // reset these values in case we loop for attributes. + break; + case '\'': // is the character one of two kinds of quote? + case '"': + if(last!='\\') { + quote=c; + break; + } + // Fallthrough ok + default: + baos.write(c); // write any unprocessed bytes into buffer + + } + } + last = c; + } + int type = state&(DOC_TYPE|COMMENT|END_TAG|START_TAG); // get just the Tag states and turn into Type for Tag + if(type==0) { + type=START_TAG; + } + if(tag!=null) { + tag.state|=type; // add the appropriate Tag States + } + return tag; + } - /** - * getNSS - * - * If the tag contains some Namespace attributes, create a new nss from the passed in one, copy all into it, then add - * This provides Scoping behavior - * - * if Nss is null in the first place, create an new nss, so we don't have to deal with null Maps. - * - * @param nss - * @param t - * @return - */ - private Map getNss(Map nss, Tag t) { - Map newnss = null; - if(t.attribs!=null) { - for(Tag tag : t.attribs) { - if("xmlns".equals(tag.prefix)) { - if(newnss==null) { - newnss = new HashMap<>(); - if(nss!=null)newnss.putAll(nss); - } - newnss.put(tag.name, tag.value); - } - } - } - //return newnss==null?(nss==null?new HashMap():nss):newnss; - if(newnss==null) { - if(nss==null) { - newnss = new HashMap<>(); - } else { - newnss = nss; - } - } - return newnss; - } + /** + * getNSS + * + * If the tag contains some Namespace attributes, create a new nss from the passed in one, copy all into it, then add + * This provides Scoping behavior + * + * if Nss is null in the first place, create an new nss, so we don't have to deal with null Maps. + * + * @param nss + * @param t + * @return + */ + private Map getNss(Map nss, Tag t) { + Map newnss = null; + if(t.attribs!=null) { + for(Tag tag : t.attribs) { + if("xmlns".equals(tag.prefix)) { + if(newnss==null) { + newnss = new HashMap<>(); + if(nss!=null)newnss.putAll(nss); + } + newnss.put(tag.name, tag.value); + } + } + } + //return newnss==null?(nss==null?new HashMap():nss):newnss; + if(newnss==null) { + if(nss==null) { + newnss = new HashMap<>(); + } else { + newnss = nss; + } + } + return newnss; + } - /** - * The result of the parseTag method - * - * Data is split up into prefix, name and value portions. "Tags" with Values that are inside a Tag are known in XLM - * as Attributes. - * - * @author Jonathan - * - */ - public class Tag { - public int state; - public String prefix,name,value; - public List attribs; + /** + * The result of the parseTag method + * + * Data is split up into prefix, name and value portions. "Tags" with Values that are inside a Tag are known in XLM + * as Attributes. + * + * @author Jonathan + * + */ + public class Tag { + public int state; + public String prefix,name,value; + public List attribs; - public Tag(String prefix, String name, String value) { - this.prefix = prefix; - this.name = name; - this.value = value; - attribs = null; - } + public Tag(String prefix, String name, String value) { + this.prefix = prefix; + this.name = name; + this.value = value; + attribs = null; + } - /** - * add an attribute - * Not all tags need attributes... lazy instantiate to save time and memory - * @param tag - */ - public void add(Tag attrib) { - if(attribs == null) { - attribs = new ArrayList<>(); - } - attribs.add(attrib); - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - if(prefix!=null) { - sb.append(prefix); - sb.append(':'); - } - sb.append(name==null?"!!ERROR!!":name); + /** + * add an attribute + * Not all tags need attributes... lazy instantiate to save time and memory + * @param tag + */ + public void add(Tag attrib) { + if(attribs == null) { + attribs = new ArrayList<>(); + } + attribs.add(attrib); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + if(prefix!=null) { + sb.append(prefix); + sb.append(':'); + } + sb.append(name==null?"!!ERROR!!":name); - char quote = ((state&DOC_TYPE)==DOC_TYPE)?'\'':'"'; - if(value!=null) { - sb.append('='); - sb.append(quote); - sb.append(value); - sb.append(quote); - } - return sb.toString(); - } - } + char quote = ((state&DOC_TYPE)==DOC_TYPE)?'\'':'"'; + if(value!=null) { + sb.append('='); + sb.append(quote); + sb.append(value); + sb.append(quote); + } + return sb.toString(); + } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java index eaa3376d..982a29e5 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java @@ -33,84 +33,84 @@ import org.onap.aaf.cadi.config.Get; public class JU_Get { - private String defaultVal = "some default value"; + private String defaultVal = "some default value"; - private ByteArrayOutputStream outStream; + private ByteArrayOutputStream outStream; - private TestBean tb; + private TestBean tb; - @Before - public void setup() { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - } + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } - @After - public void tearDown() { - System.setOut(System.out); - } + @After + public void tearDown() { + System.setOut(System.out); + } - @Test - public void beanTest() { - tb = new TestBean(); - tb.setProperty1("prop1"); + @Test + public void beanTest() { + tb = new TestBean(); + tb.setProperty1("prop1"); - Get.Bean testBean = new Get.Bean(tb); - assertThat(testBean.get("property1", defaultVal, true), is("prop1")); - assertThat(testBean.get("property2", defaultVal, true), is(defaultVal)); - assertThat(testBean.get("thrower", defaultVal, true), is(defaultVal)); - } + Get.Bean testBean = new Get.Bean(tb); + assertThat(testBean.get("property1", defaultVal, true), is("prop1")); + assertThat(testBean.get("property2", defaultVal, true), is(defaultVal)); + assertThat(testBean.get("thrower", defaultVal, true), is(defaultVal)); + } - @Test - public void nullTest() { - assertThat(Get.NULL.get("name", defaultVal, true), is(defaultVal)); - } + @Test + public void nullTest() { + assertThat(Get.NULL.get("name", defaultVal, true), is(defaultVal)); + } - @Test - public void accessTest() { - String output; + @Test + public void accessTest() { + String output; - PropAccess access = new PropAccess(); - access.setProperty("tag", "value"); - Get.AccessGet accessGet = new Get.AccessGet(access); + PropAccess access = new PropAccess(); + access.setProperty("tag", "value"); + Get.AccessGet accessGet = new Get.AccessGet(access); - assertThat(accessGet.get("tag", defaultVal, true), is("value")); - output = outStream.toString().split(" ", 2)[1]; - assertThat(output, is("INIT [cadi] tag is set to value" + System.lineSeparator())); + assertThat(accessGet.get("tag", defaultVal, true), is("value")); + output = outStream.toString().split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] tag is set to value" + System.lineSeparator())); - outStream.reset(); + outStream.reset(); - assertThat(accessGet.get("not a real tag", defaultVal, true), is(defaultVal)); - output = outStream.toString().split(" ", 2)[1]; - assertThat(output, is("INIT [cadi] not a real tag is set to " + defaultVal + System.lineSeparator())); + assertThat(accessGet.get("not a real tag", defaultVal, true), is(defaultVal)); + output = outStream.toString().split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] not a real tag is set to " + defaultVal + System.lineSeparator())); - outStream.reset(); + outStream.reset(); - assertThat(accessGet.get("not a real tag", null, true), is(nullValue())); - output = outStream.toString().split(" ", 2)[1]; - assertThat(output, is("INIT [cadi] not a real tag is not set" + System.lineSeparator())); + assertThat(accessGet.get("not a real tag", null, true), is(nullValue())); + output = outStream.toString().split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] not a real tag is not set" + System.lineSeparator())); - outStream.reset(); + outStream.reset(); - assertThat(accessGet.get("tag", defaultVal, false), is("value")); - assertThat(outStream.toString(), is("")); - } + assertThat(accessGet.get("tag", defaultVal, false), is("value")); + assertThat(outStream.toString(), is("")); + } - public class TestBean implements java.io.Serializable { + public class TestBean implements java.io.Serializable { - private static final long serialVersionUID = 1L; - private String property1 = null; - private String property2 = null; - @SuppressWarnings("unused") - private String thrower = null; + private static final long serialVersionUID = 1L; + private String property1 = null; + private String property2 = null; + @SuppressWarnings("unused") + private String thrower = null; - public TestBean() { } - public String getProperty1() { return property1; } - public void setProperty1(final String value) { this.property1 = value; } - public String getProperty2() { return property2; } - public void setProperty2(final String value) { this.property2 = value; } - public String getThrower() throws Exception { throw new Exception(); } - public void setThrower(final String value) { this.thrower = value; } + public TestBean() { } + public String getProperty1() { return property1; } + public void setProperty1(final String value) { this.property1 = value; } + public String getProperty2() { return property2; } + public void setProperty2(final String value) { this.property2 = value; } + public String getThrower() throws Exception { throw new Exception(); } + public void setThrower(final String value) { this.thrower = value; } - } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_GetAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_GetAccess.java index d50f9e8c..568a820c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_GetAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_GetAccess.java @@ -36,72 +36,72 @@ import org.onap.aaf.cadi.config.GetAccess; public class JU_GetAccess { - private String defaultVal = "some default value"; + private String defaultVal = "some default value"; - private ByteArrayOutputStream outStream; + private ByteArrayOutputStream outStream; - private PropAccess access; - private Get.AccessGet accessGet; - private File file; - private String filePath; + private PropAccess access; + private Get.AccessGet accessGet; + private File file; + private String filePath; - @Before - public void setup() throws IOException { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); - file = File.createTempFile("GetAccess_test", ""); - filePath = file.getAbsolutePath(); + file = File.createTempFile("GetAccess_test", ""); + filePath = file.getAbsolutePath(); - access = new PropAccess(); + access = new PropAccess(); access.setProperty("cadi_prop_files", filePath); - accessGet = new Get.AccessGet(access); + accessGet = new Get.AccessGet(access); - } + } - @After - public void tearDown() { - System.setOut(System.out); + @After + public void tearDown() { + System.setOut(System.out); - file.delete(); - } + file.delete(); + } @Test public void constructorTest() { String output; @SuppressWarnings("unused") - GetAccess getAccess = new GetAccess(accessGet); - String[] lines = outStream.toString().split(System.lineSeparator()); - assertThat(lines.length, is(2)); + GetAccess getAccess = new GetAccess(accessGet); + String[] lines = outStream.toString().split(System.lineSeparator()); + assertThat(lines.length, is(2)); output = lines[0].split(" ", 2)[1]; assertThat(output, is("INIT [cadi] cadi_prop_files is set to " + filePath)); - output = lines[1].split(" ", 2)[1]; + output = lines[1].split(" ", 2)[1]; assertThat(output, is("INIT [cadi] Loading CADI Properties from " + filePath)); - } + } @Test public void getPropertyTest1() { GetAccess getAccess = new GetAccess(accessGet); - getAccess.setProperty("tag", "value"); - assertThat(getAccess.getProperty("tag", defaultVal), is("value")); - assertThat(getAccess.getProperty("not_a_tag", defaultVal), is(defaultVal)); - } + getAccess.setProperty("tag", "value"); + assertThat(getAccess.getProperty("tag", defaultVal), is("value")); + assertThat(getAccess.getProperty("not_a_tag", defaultVal), is(defaultVal)); + } @Test public void getPropertyTest2() { GetAccess getAccess = new GetAccess(accessGet); - getAccess.setProperty("tag", "value"); - assertThat(getAccess.getProperty("tag"), is("value")); - assertThat(getAccess.getProperty("not_a_tag"), is(nullValue())); - } + getAccess.setProperty("tag", "value"); + assertThat(getAccess.getProperty("tag"), is("value")); + assertThat(getAccess.getProperty("not_a_tag"), is(nullValue())); + } - @Test - public void getTest() { + @Test + public void getTest() { GetAccess getAccess = new GetAccess(accessGet); - assertThat((Get.AccessGet)getAccess.get(), is(accessGet)); - } + assertThat((Get.AccessGet)getAccess.get(), is(accessGet)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java index 6510bdcd..3fbae769 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java @@ -35,34 +35,34 @@ import org.onap.aaf.cadi.config.MultiGet; public class JU_MultiGet { - private String defaultVal = "some default value"; + private String defaultVal = "some default value"; - private ByteArrayOutputStream outStream; + private ByteArrayOutputStream outStream; - private MultiGet multiGet; - private Get.AccessGet accessGet; - private PropAccess access; + private MultiGet multiGet; + private Get.AccessGet accessGet; + private PropAccess access; - @Before - public void setup() throws IOException { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); - access = new PropAccess(); - access.setProperty("tag", "value"); - accessGet = new Get.AccessGet(access); - multiGet = new MultiGet(accessGet, Get.NULL); - } + access = new PropAccess(); + access.setProperty("tag", "value"); + accessGet = new Get.AccessGet(access); + multiGet = new MultiGet(accessGet, Get.NULL); + } - @After - public void tearDown() { - System.setOut(System.out); - } + @After + public void tearDown() { + System.setOut(System.out); + } @Test public void getTest() { - assertThat(multiGet.get("tag", defaultVal, false), is("value")); - assertThat(multiGet.get("not_a_tag", defaultVal, false), is(defaultVal)); - } + assertThat(multiGet.get("tag", defaultVal, false), is("value")); + assertThat(multiGet.get("not_a_tag", defaultVal, false), is(defaultVal)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java index 001d0fe6..98c1a292 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java @@ -45,92 +45,92 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.config.SecurityInfo; public class JU_SecurityInfo { - - private static PropAccess access; - - private static final String keyStoreFileName = "src/test/resources/keystore.p12"; - private static final String keyStorePassword = "Password for the keystore"; - private static final String keyPassword = "Password for the key"; - - private static final String trustStoreFileName = "src/test/resources/truststore.jks"; - private static final String trustStorePasswd = "Password for the truststore"; - - @BeforeClass - public static void setupOnce() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - keyStore.load(null, null); - keyStore.store(new FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray()); - - KeyStore trustStore = KeyStore.getInstance("JKS"); - trustStore.load(null, null); - trustStore.store(new FileOutputStream(trustStoreFileName), trustStorePasswd.toCharArray()); - } - - @Before - public void setup() throws IOException { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - - access.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); - access.setProperty(Config.CADI_KEYSTORE_PASSWORD, access.encrypt(keyStorePassword)); - access.setProperty(Config.CADI_KEY_PASSWORD, access.encrypt(keyPassword)); - - access.setProperty(Config.CADI_TRUSTSTORE, trustStoreFileName); - access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, access.encrypt(trustStorePasswd)); - } - - @AfterClass - public static void tearDownOnce() { - File keyStoreFile = new File(keyStoreFileName); - if (keyStoreFile.exists()) { - keyStoreFile.delete(); - } - File trustStoreFile = new File(trustStoreFileName); - if (trustStoreFile.exists()) { - trustStoreFile.delete(); - } - } - - @Test - public void test() throws CadiException { - SecurityInfo si = new SecurityInfo(access); - - assertNotNull(si.getSSLSocketFactory()); - assertNotNull(si.getSSLContext()); - assertNotNull(si.getKeyManagers()); - - access.setProperty(Config.CADI_TRUST_MASKS, "123.123.123.123"); - si = new SecurityInfo(access); - } - - @Test(expected = CadiException.class) - public void nullkeyStoreTest() throws CadiException { - access.setProperty(Config.CADI_KEYSTORE, "passwords.txt"); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(access); - } - - @Test(expected = CadiException.class) - public void nullTrustStoreTest() throws CadiException { - access.setProperty(Config.CADI_TRUSTSTORE, "passwords.txt"); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(access); - } - - - @Test(expected = NumberFormatException.class) - public void badTrustMaskTest() throws CadiException { - access.setProperty(Config.CADI_TRUST_MASKS, "trustMask"); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(access); - } - - @Test - public void coverageTest() throws CadiException { - PropAccess badAccess = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(badAccess); - badAccess.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); - si = new SecurityInfo(badAccess); - } + + private static PropAccess access; + + private static final String keyStoreFileName = "src/test/resources/keystore.p12"; + private static final String keyStorePassword = "Password for the keystore"; + private static final String keyPassword = "Password for the key"; + + private static final String trustStoreFileName = "src/test/resources/truststore.jks"; + private static final String trustStorePasswd = "Password for the truststore"; + + @BeforeClass + public static void setupOnce() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(null, null); + keyStore.store(new FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray()); + + KeyStore trustStore = KeyStore.getInstance("JKS"); + trustStore.load(null, null); + trustStore.store(new FileOutputStream(trustStoreFileName), trustStorePasswd.toCharArray()); + } + + @Before + public void setup() throws IOException { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + + access.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); + access.setProperty(Config.CADI_KEYSTORE_PASSWORD, access.encrypt(keyStorePassword)); + access.setProperty(Config.CADI_KEY_PASSWORD, access.encrypt(keyPassword)); + + access.setProperty(Config.CADI_TRUSTSTORE, trustStoreFileName); + access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, access.encrypt(trustStorePasswd)); + } + + @AfterClass + public static void tearDownOnce() { + File keyStoreFile = new File(keyStoreFileName); + if (keyStoreFile.exists()) { + keyStoreFile.delete(); + } + File trustStoreFile = new File(trustStoreFileName); + if (trustStoreFile.exists()) { + trustStoreFile.delete(); + } + } + + @Test + public void test() throws CadiException { + SecurityInfo si = new SecurityInfo(access); + + assertNotNull(si.getSSLSocketFactory()); + assertNotNull(si.getSSLContext()); + assertNotNull(si.getKeyManagers()); + + access.setProperty(Config.CADI_TRUST_MASKS, "123.123.123.123"); + si = new SecurityInfo(access); + } + + @Test(expected = CadiException.class) + public void nullkeyStoreTest() throws CadiException { + access.setProperty(Config.CADI_KEYSTORE, "passwords.txt"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + @Test(expected = CadiException.class) + public void nullTrustStoreTest() throws CadiException { + access.setProperty(Config.CADI_TRUSTSTORE, "passwords.txt"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + + @Test(expected = NumberFormatException.class) + public void badTrustMaskTest() throws CadiException { + access.setProperty(Config.CADI_TRUST_MASKS, "trustMask"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + @Test + public void coverageTest() throws CadiException { + PropAccess badAccess = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(badAccess); + badAccess.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); + si = new SecurityInfo(badAccess); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java index 111f8769..735edef9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java @@ -39,71 +39,71 @@ import org.onap.aaf.cadi.config.SecurityInfoC; public class JU_SecurityInfoC { - ByteArrayOutputStream outStream; - ByteArrayOutputStream errStream; + ByteArrayOutputStream outStream; + ByteArrayOutputStream errStream; - @Before - public void setup() { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - } + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + } - @After - public void tearDown() { - System.setOut(System.out); - System.setErr(System.err); - } + @After + public void tearDown() { + System.setOut(System.out); + System.setErr(System.err); + } -// @Test -// public void instanceTest() throws CadiException, MalformedURLException { -// SecurityInfoC si = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class ); -// assertThat(si.defSS.getID(), is(SecurityInfoC.DEF_ID)); -// try { -// si.defSS.setSecurity(new HttpURLConnectionStub()); -// fail("Should have thrown an exception"); -// } catch (CadiException e) { -// assertTrue(e instanceof CadiException); -// assertThat(e.getMessage(), is("No Client Credentials set.")); -// } -// assertThat(si.defSS.setLastResponse(0), is(0)); +// @Test +// public void instanceTest() throws CadiException, MalformedURLException { +// SecurityInfoC si = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class ); +// assertThat(si.defSS.getID(), is(SecurityInfoC.DEF_ID)); +// try { +// si.defSS.setSecurity(new HttpURLConnectionStub()); +// fail("Should have thrown an exception"); +// } catch (CadiException e) { +// assertTrue(e instanceof CadiException); +// assertThat(e.getMessage(), is("No Client Credentials set.")); +// } +// assertThat(si.defSS.setLastResponse(0), is(0)); // -// // Try it again for coverage -// SecurityInfoC siClone = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class); -// assertThat(siClone, is(si)); -// } - - @Test - public void setTest() throws MalformedURLException, CadiException { - SecurityInfoC si = SecurityInfoC.instance(new PropAccess(), HttpURLConnectionStub.class); - SecuritySetter ss = new SecuritySetterStub(); - assertThat(si.set(ss), is(si)); - assertThat(si.defSS.getID(), is("Example ID")); - try { - si.defSS.setSecurity(new HttpURLConnectionStub()); - fail("Should have thrown an exception"); - } catch (CadiException e) { - assertTrue(e instanceof CadiException); - assertThat(e.getMessage(), is("Example exception")); - } - assertThat(si.defSS.setLastResponse(0), is(0)); - assertThat(si.defSS.setLastResponse(1), is(1)); - assertThat(si.defSS.setLastResponse(-1), is(-1)); - } +// // Try it again for coverage +// SecurityInfoC siClone = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class); +// assertThat(siClone, is(si)); +// } + + @Test + public void setTest() throws MalformedURLException, CadiException { + SecurityInfoC si = SecurityInfoC.instance(new PropAccess(), HttpURLConnectionStub.class); + SecuritySetter ss = new SecuritySetterStub(); + assertThat(si.set(ss), is(si)); + assertThat(si.defSS.getID(), is("Example ID")); + try { + si.defSS.setSecurity(new HttpURLConnectionStub()); + fail("Should have thrown an exception"); + } catch (CadiException e) { + assertTrue(e instanceof CadiException); + assertThat(e.getMessage(), is("Example exception")); + } + assertThat(si.defSS.setLastResponse(0), is(0)); + assertThat(si.defSS.setLastResponse(1), is(1)); + assertThat(si.defSS.setLastResponse(-1), is(-1)); + } - public static class HttpURLConnectionStub extends HttpURLConnection { - public HttpURLConnectionStub() throws MalformedURLException { super(new URL("http://www.example.com")); } - @Override public void disconnect() { } - @Override public boolean usingProxy() { return false; } - @Override public void connect() throws IOException { } - } + public static class HttpURLConnectionStub extends HttpURLConnection { + public HttpURLConnectionStub() throws MalformedURLException { super(new URL("http://www.example.com")); } + @Override public void disconnect() { } + @Override public boolean usingProxy() { return false; } + @Override public void connect() throws IOException { } + } - private class SecuritySetterStub implements SecuritySetter { - public String getID() { return "Example ID"; } - public void setSecurity(CT client) throws CadiException { throw new CadiException("Example exception"); } - public int setLastResponse(int respCode) { return respCode; } - } + private class SecuritySetterStub implements SecuritySetter { + public String getID() { return "Example ID"; } + public void setSecurity(CT client) throws CadiException { throw new CadiException("Example exception"); } + public int setLastResponse(int respCode) { return respCode; } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java index 7d7ca77c..86a12ca0 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java @@ -43,103 +43,103 @@ import org.onap.aaf.cadi.util.Split; public class JU_UsersDump { - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream stdoutSuppressor; - - private static final String expected = "\n" + - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n"; - - private final static String groups = "myname:groupA,groupB"; - private final static String names = "admin:myname,yourname;suser:hisname,hername,m1234"; - - private AbsUserCache lur; - - @Before - public void setup() throws IOException { - outStream = new ByteArrayOutputStream(); - stdoutSuppressor = new ByteArrayOutputStream(); - - System.setOut(new PrintStream(stdoutSuppressor)); - - lur = new LocalLur(new PropAccess(), groups, names); - } - - @After - public void tearDown() { - System.setOut(System.out); - } - - @Test - public void writeTest() throws IOException { - UsersDump.write(outStream, lur); - String[] actualLines = Split.splitTrim('\n', outStream.toString()); - String[] expectedLines = Split.splitTrim('\n', expected); - for (String s : actualLines) { - System.out.println(s); - } - - assertThat(actualLines.length, is(expectedLines.length)); - - // Check that the output starts with an XML tag - assertThat(actualLines[0], is(expectedLines[0])); - // Check that lines 2-4 are a comment - assertThat(actualLines[1], is(expectedLines[1])); - assertThat(actualLines[3], is(expectedLines[3])); - - // Check that the rest of the output matches the expected output - for (int i = 4; i < actualLines.length; i++) { - assertThat(actualLines[i], is(expectedLines[i])); - } - - // Run the test again with outStream as a PrintStream (for coverage) - outStream.reset(); - UsersDump.write(new PrintStream(outStream), lur); - actualLines = Split.splitTrim('\n', outStream.toString()); - - assertThat(actualLines.length, is(expectedLines.length)); - - // Check that the output starts with an XML tag - assertThat(actualLines[0], is(expectedLines[0])); - // Check that lines 2-4 are a comment - assertThat(actualLines[1], is(expectedLines[1])); - assertThat(actualLines[3], is(expectedLines[3])); - - // Check that the rest of the output matches the expected output - for (int i = 4; i < actualLines.length; i++) { - assertThat(actualLines[i], is(expectedLines[i])); - } - } - - @Test - public void updateUsersTest() { - String output; - File outputFile = new File("src/test/resources/userdump.xml"); - assertThat(outputFile.exists(), is(false)); - - output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); - assertThat(output, is(nullValue())); - assertThat(outputFile.exists(), is(true)); - - output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); - assertThat(output, is(nullValue())); - assertThat(outputFile.exists(), is(true)); - - outputFile.delete(); - } + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream stdoutSuppressor; + + private static final String expected = "\n" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + + private final static String groups = "myname:groupA,groupB"; + private final static String names = "admin:myname,yourname;suser:hisname,hername,m1234"; + + private AbsUserCache lur; + + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + stdoutSuppressor = new ByteArrayOutputStream(); + + System.setOut(new PrintStream(stdoutSuppressor)); + + lur = new LocalLur(new PropAccess(), groups, names); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void writeTest() throws IOException { + UsersDump.write(outStream, lur); + String[] actualLines = Split.splitTrim('\n', outStream.toString()); + String[] expectedLines = Split.splitTrim('\n', expected); + for (String s : actualLines) { + System.out.println(s); + } + + assertThat(actualLines.length, is(expectedLines.length)); + + // Check that the output starts with an XML tag + assertThat(actualLines[0], is(expectedLines[0])); + // Check that lines 2-4 are a comment + assertThat(actualLines[1], is(expectedLines[1])); + assertThat(actualLines[3], is(expectedLines[3])); + + // Check that the rest of the output matches the expected output + for (int i = 4; i < actualLines.length; i++) { + assertThat(actualLines[i], is(expectedLines[i])); + } + + // Run the test again with outStream as a PrintStream (for coverage) + outStream.reset(); + UsersDump.write(new PrintStream(outStream), lur); + actualLines = Split.splitTrim('\n', outStream.toString()); + + assertThat(actualLines.length, is(expectedLines.length)); + + // Check that the output starts with an XML tag + assertThat(actualLines[0], is(expectedLines[0])); + // Check that lines 2-4 are a comment + assertThat(actualLines[1], is(expectedLines[1])); + assertThat(actualLines[3], is(expectedLines[3])); + + // Check that the rest of the output matches the expected output + for (int i = 4; i < actualLines.length; i++) { + assertThat(actualLines[i], is(expectedLines[i])); + } + } + + @Test + public void updateUsersTest() { + String output; + File outputFile = new File("src/test/resources/userdump.xml"); + assertThat(outputFile.exists(), is(false)); + + output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); + assertThat(output, is(nullValue())); + assertThat(outputFile.exists(), is(true)); + + output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); + assertThat(output, is(nullValue())); + assertThat(outputFile.exists(), is(true)); + + outputFile.delete(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java index 6daa2720..f57bb93e 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java @@ -44,64 +44,64 @@ import javax.servlet.http.HttpServletResponse; public class JU_AUTHZServlet { - @Mock private Servlet servletMock; - @Mock private ServletConfig servletConfigMock; - @Mock private HttpServletRequest reqMock; - @Mock private HttpServletResponse respMock; - @Mock private ServletRequestWrapper servletWrapperMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test() throws ServletException, IOException { - AUTHZServletStub servlet = new AUTHZServletStub(Servlet.class); - - try { - servlet.init(servletConfigMock); - fail("Should've thrown an exception"); - } catch (ServletException e) { - assertThat(e.getMessage(), is("Invalid Servlet Delegate")); - } - - setPrivateField(AUTHZServlet.class, "delegate", servlet, servletMock); - servlet.init(servletConfigMock); - servlet.getServletConfig(); - servlet.getServletInfo(); - - servlet.service(reqMock, respMock); - - String[] roles = new String[] {"role1", "role2"}; - setPrivateField(AUTHZServlet.class, "roles", servlet, roles); - servlet.service(reqMock, respMock); - - when(reqMock.isUserInRole("role1")).thenReturn(true); - servlet.service(reqMock, respMock); - - try { - servlet.service(servletWrapperMock, respMock); - fail("Should've thrown an exception"); - } catch (ServletException e) { - assertThat(e.getMessage(), is("JASPIServlet only supports HTTPServletRequest/HttpServletResponse")); - } - servlet.destroy(); - } - - private class AUTHZServletStub extends AUTHZServlet { - public AUTHZServletStub(Class cls) { super(cls); } - } - - private void setPrivateField(Class clazz, String fieldName, Object target, Object value) { - try { - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(target, value); - field.setAccessible(false); - } catch(Exception e) { - System.err.println("Could not set field [" + fieldName + "] to " + value); - } - } + @Mock private Servlet servletMock; + @Mock private ServletConfig servletConfigMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private ServletRequestWrapper servletWrapperMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws ServletException, IOException { + AUTHZServletStub servlet = new AUTHZServletStub(Servlet.class); + + try { + servlet.init(servletConfigMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("Invalid Servlet Delegate")); + } + + setPrivateField(AUTHZServlet.class, "delegate", servlet, servletMock); + servlet.init(servletConfigMock); + servlet.getServletConfig(); + servlet.getServletInfo(); + + servlet.service(reqMock, respMock); + + String[] roles = new String[] {"role1", "role2"}; + setPrivateField(AUTHZServlet.class, "roles", servlet, roles); + servlet.service(reqMock, respMock); + + when(reqMock.isUserInRole("role1")).thenReturn(true); + servlet.service(reqMock, respMock); + + try { + servlet.service(servletWrapperMock, respMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("JASPIServlet only supports HTTPServletRequest/HttpServletResponse")); + } + servlet.destroy(); + } + + private class AUTHZServletStub extends AUTHZServlet { + public AUTHZServletStub(Class cls) { super(cls); } + } + + private void setPrivateField(Class clazz, String fieldName, Object target, Object value) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(target, value); + field.setAccessible(false); + } catch(Exception e) { + System.err.println("Could not set field [" + fieldName + "] to " + value); + } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java index b53a9ea9..d3b28dc4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java @@ -34,21 +34,21 @@ import org.onap.aaf.cadi.filter.AccessGetter; public class JU_AccessGetter { - private static final String tag = "tag"; - private static final String value = "value"; - - private PropAccess access; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(tag, value); - } - - @Test - public void test() { - AccessGetter getter = new AccessGetter(access); - assertThat(getter.get(tag, null, false), is(value)); - } + private static final String tag = "tag"; + private static final String value = "value"; + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(tag, value); + } + + @Test + public void test() { + AccessGetter getter = new AccessGetter(access); + assertThat(getter.get(tag, null, false), is(value)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java index 9fb951a2..397424a0 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java @@ -29,17 +29,17 @@ import org.onap.aaf.cadi.filter.MapPermConverter; public class JU_MapPermConverter { - private static final String tag = "tag"; - private static final String value = "value"; - private static final String nontag = "nontag"; + private static final String tag = "tag"; + private static final String value = "value"; + private static final String nontag = "nontag"; - @Test - public void test() { - MapPermConverter converter = new MapPermConverter(); - assertThat(converter.map().isEmpty(), is(true)); - converter.map().put(tag, value); - assertThat(converter.convert(tag), is(value)); - assertThat(converter.convert(nontag), is(nontag)); - } + @Test + public void test() { + MapPermConverter converter = new MapPermConverter(); + assertThat(converter.map().isEmpty(), is(true)); + converter.map().put(tag, value); + assertThat(converter.convert(tag), is(value)); + assertThat(converter.convert(nontag), is(nontag)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java index 0a6dc2d5..fd6d22e9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java @@ -29,10 +29,10 @@ import org.onap.aaf.cadi.filter.NullPermConverter; public class JU_NullPermConverter { - @Test - public void test() { - NullPermConverter converter = NullPermConverter.singleton(); - assertThat(converter.convert("test"), is("test")); - } + @Test + public void test() { + NullPermConverter converter = NullPermConverter.singleton(); + assertThat(converter.convert("test"), is("test")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java index a36dd462..78b0fbc6 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java @@ -48,58 +48,58 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.filter.PathFilter; public class JU_PathFilter { - - private PropAccess access; - - @Mock private FilterConfig filterConfigMock; - @Mock private ServletContext contextMock; - @Mock private HttpServletRequest reqMock; - @Mock private HttpServletResponse respMock; - @Mock private FilterChain chainMock; - @Mock private Principal princMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(filterConfigMock.getServletContext()).thenReturn(contextMock); - when(reqMock.getUserPrincipal()).thenReturn(princMock); - when(princMock.getName()).thenReturn("name"); + + private PropAccess access; + + @Mock private FilterConfig filterConfigMock; + @Mock private ServletContext contextMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private FilterChain chainMock; + @Mock private Principal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(filterConfigMock.getServletContext()).thenReturn(contextMock); + when(reqMock.getUserPrincipal()).thenReturn(princMock); + when(princMock.getName()).thenReturn("name"); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } - @Test - public void test() throws ServletException, IOException { - PathFilter pathFilter = new PathFilter(access); - try { - pathFilter.init(filterConfigMock); - fail("Should've thrown an exception"); - } catch (ServletException e) { - assertThat(e.getMessage(), is("PathFilter - pathfilter_ns is not set")); - } - - when(contextMock.getAttribute(Config.PATHFILTER_NS)).thenReturn(5); - when(contextMock.getAttribute(Config.PATHFILTER_STACK)).thenReturn(5); - when(contextMock.getAttribute(Config.PATHFILTER_URLPATTERN)).thenReturn(5); - when(contextMock.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG)).thenReturn(5); - pathFilter.init(filterConfigMock); - - pathFilter.doFilter(reqMock, respMock, chainMock); + @Test + public void test() throws ServletException, IOException { + PathFilter pathFilter = new PathFilter(access); + try { + pathFilter.init(filterConfigMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("PathFilter - pathfilter_ns is not set")); + } + + when(contextMock.getAttribute(Config.PATHFILTER_NS)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_STACK)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_URLPATTERN)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG)).thenReturn(5); + pathFilter.init(filterConfigMock); + + pathFilter.doFilter(reqMock, respMock, chainMock); - when(reqMock.isUserInRole(anyString())).thenReturn(true); - pathFilter.doFilter(reqMock, respMock, chainMock); - - pathFilter.destroy(); + when(reqMock.isUserInRole(anyString())).thenReturn(true); + pathFilter.doFilter(reqMock, respMock, chainMock); + + pathFilter.destroy(); - pathFilter = new PathFilter(); - pathFilter.init(filterConfigMock); - - pathFilter.doFilter(reqMock, respMock, chainMock); + pathFilter = new PathFilter(); + pathFilter.init(filterConfigMock); + + pathFilter.doFilter(reqMock, respMock, chainMock); - when(reqMock.isUserInRole(anyString())).thenReturn(false); - pathFilter.doFilter(reqMock, respMock, chainMock); - - pathFilter.destroy(); - } + when(reqMock.isUserInRole(anyString())).thenReturn(false); + pathFilter.doFilter(reqMock, respMock, chainMock); + + pathFilter.destroy(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java index 9853f88e..88301a6c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java @@ -32,48 +32,48 @@ import org.onap.aaf.cadi.lur.ConfigPrincipal; public class JU_ConfigPrincipal { - private final String name = "User"; - private final String pass = "pass"; + private final String name = "User"; + private final String pass = "pass"; - // Expected output of base64("User:pass") - private final String b64encoded = "VXNlcjpwYXNz"; + // Expected output of base64("User:pass") + private final String b64encoded = "VXNlcjpwYXNz"; - private Field content_field; - - @Before - public void setup() throws NoSuchFieldException { - content_field = ConfigPrincipal.class.getDeclaredField("content"); - content_field.setAccessible(true); - } + private Field content_field; + + @Before + public void setup() throws NoSuchFieldException { + content_field = ConfigPrincipal.class.getDeclaredField("content"); + content_field.setAccessible(true); + } - @Test - public void testConfigPrincipalStringString() throws IOException, IllegalArgumentException, IllegalAccessException { - ConfigPrincipal p = new ConfigPrincipal(name, pass); - - assertThat(p.getName(), is(name)); - assertThat(p.toString(), is(name)); - assertThat(p.getCred(), is(pass.getBytes())); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - content_field.set(p, "pass"); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + @Test + public void testConfigPrincipalStringString() throws IOException, IllegalArgumentException, IllegalAccessException { + ConfigPrincipal p = new ConfigPrincipal(name, pass); + + assertThat(p.getName(), is(name)); + assertThat(p.toString(), is(name)); + assertThat(p.getCred(), is(pass.getBytes())); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + content_field.set(p, "pass"); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - // One more time for coverage purposes - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - } + // One more time for coverage purposes + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + } - @Test - public void testConfigPrincipalStringByteArray() throws IOException, IllegalArgumentException, IllegalAccessException { - ConfigPrincipal p = new ConfigPrincipal(name, pass.getBytes()); - - assertThat(p.getName(), is(name)); - assertThat(p.toString(), is(name)); - assertThat(p.getCred(), is(pass.getBytes())); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - content_field.set(p, "pass"); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + @Test + public void testConfigPrincipalStringByteArray() throws IOException, IllegalArgumentException, IllegalAccessException { + ConfigPrincipal p = new ConfigPrincipal(name, pass.getBytes()); + + assertThat(p.getName(), is(name)); + assertThat(p.toString(), is(name)); + assertThat(p.getCred(), is(pass.getBytes())); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + content_field.set(p, "pass"); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - // One more time for coverage purposes - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - } - + // One more time for coverage purposes + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java index b99030eb..c1a43f0d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java @@ -45,84 +45,84 @@ import org.onap.aaf.cadi.lur.EpiLur; public class JU_EpiLur { - private ArrayList perms; - private CredValStub lurMock3; + private ArrayList perms; + private CredValStub lurMock3; - @Mock private Lur lurMock1; - @Mock private CachingLur lurMock2; - @Mock private Principal princMock; - @Mock private Permission permMock; + @Mock private Lur lurMock1; + @Mock private CachingLur lurMock2; + @Mock private Principal princMock; + @Mock private Permission permMock; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); - perms = new ArrayList<>(); - perms.add(permMock); + perms = new ArrayList<>(); + perms.add(permMock); - lurMock3 = new CredValStub(); - } + lurMock3 = new CredValStub(); + } - @Test - public void test() throws CadiException { - EpiLur lur; - try { - lur = new EpiLur(); - } catch (CadiException e) { - assertThat(e.getMessage(), is("Need at least one Lur implementation in constructor")); - } - lur = new EpiLur(lurMock1, lurMock2, lurMock3); - assertThat(lur.fish(null, null), is(false)); + @Test + public void test() throws CadiException { + EpiLur lur; + try { + lur = new EpiLur(); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Need at least one Lur implementation in constructor")); + } + lur = new EpiLur(lurMock1, lurMock2, lurMock3); + assertThat(lur.fish(null, null), is(false)); - assertThat(lur.fish(princMock, permMock), is(false)); + assertThat(lur.fish(princMock, permMock), is(false)); - when(lurMock2.handlesExclusively(permMock)).thenReturn(true); - assertThat(lur.fish(princMock, permMock), is(false)); + when(lurMock2.handlesExclusively(permMock)).thenReturn(true); + assertThat(lur.fish(princMock, permMock), is(false)); - when(lurMock2.fish(princMock, permMock)).thenReturn(true); - assertThat(lur.fish(princMock, permMock), is(true)); + when(lurMock2.fish(princMock, permMock)).thenReturn(true); + assertThat(lur.fish(princMock, permMock), is(true)); - lur.fishAll(princMock, perms); + lur.fishAll(princMock, perms); - assertThat(lur.handlesExclusively(permMock), is(false)); + assertThat(lur.handlesExclusively(permMock), is(false)); - assertThat(lur.get(-1), is(nullValue())); - assertThat(lur.get(0), is(lurMock1)); - assertThat(lur.get(1), is((Lur)lurMock2)); - assertThat(lur.get(2), is((Lur)lurMock3)); - assertThat(lur.get(3), is(nullValue())); + assertThat(lur.get(-1), is(nullValue())); + assertThat(lur.get(0), is(lurMock1)); + assertThat(lur.get(1), is((Lur)lurMock2)); + assertThat(lur.get(2), is((Lur)lurMock3)); + assertThat(lur.get(3), is(nullValue())); - assertThat(lur.handles(princMock), is(false)); - when(lurMock2.handles(princMock)).thenReturn(true); - assertThat(lur.handles(princMock), is(true)); + assertThat(lur.handles(princMock), is(false)); + when(lurMock2.handles(princMock)).thenReturn(true); + assertThat(lur.handles(princMock), is(true)); - lur.remove("id"); + lur.remove("id"); - lur.clear(princMock, null); + lur.clear(princMock, null); - assertThat(lur.createPerm("perm"), is(not(nullValue()))); + assertThat(lur.createPerm("perm"), is(not(nullValue()))); - lur.getUserPassImpl(); - assertThat(lur.getUserPassImpl(), is((CredVal)lurMock3)); + lur.getUserPassImpl(); + assertThat(lur.getUserPassImpl(), is((CredVal)lurMock3)); - lur.toString(); - lur.destroy(); + lur.toString(); + lur.destroy(); - lur = new EpiLur(lurMock1, lurMock2); - assertThat(lur.getUserPassImpl(), is(nullValue())); + lur = new EpiLur(lurMock1, lurMock2); + assertThat(lur.getUserPassImpl(), is(nullValue())); - assertThat(lur.subLur(Lur.class), is(nullValue())); - } + assertThat(lur.subLur(Lur.class), is(nullValue())); + } - private class CredValStub implements Lur, CredVal { - @Override public boolean validate(String user, Type type, byte[] cred, Object state) { return false; } - @Override public Permission createPerm(String p) { return null; } - @Override public boolean fish(Principal bait, Permission ... pond) { return false; } - @Override public void fishAll(Principal bait, List permissions) { } - @Override public void destroy() { } - @Override public boolean handlesExclusively(Permission ... pond) { return false; } - @Override public boolean handles(Principal principal) { return false; } - @Override public void clear(Principal p, StringBuilder report) { } - } + private class CredValStub implements Lur, CredVal { + @Override public boolean validate(String user, Type type, byte[] cred, Object state) { return false; } + @Override public Permission createPerm(String p) { return null; } + @Override public boolean fish(Principal bait, Permission ... pond) { return false; } + @Override public void fishAll(Principal bait, List permissions) { } + @Override public void destroy() { } + @Override public boolean handlesExclusively(Permission ... pond) { return false; } + @Override public boolean handles(Principal principal) { return false; } + @Override public void clear(Principal p, StringBuilder report) { } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java index f35f81c1..e291cd20 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java @@ -47,126 +47,126 @@ import org.onap.aaf.cadi.lur.LocalPermission; public class JU_LocalLur { - private PropAccess access; - private ByteArrayOutputStream outStream; - - @Mock Permission permMock; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - - outStream = new ByteArrayOutputStream(); - access = new PropAccess(new PrintStream(outStream), new String[0]) { - @Override public String decrypt(String encrypted, boolean anytext) throws IOException { - return rot13(encrypted); - } - @Override public String encrypt(String unencrypted) throws IOException { - return rot13(unencrypted); - } - }; - - } - - @Test - public void test() throws IOException { - final String password = ""; - final String encrypted = rot13(password); - - LocalLur lur; - List.DumpInfo> info; - - lur = new LocalLur(access, null, null); - assertThat(lur.dumpInfo().size(), is(0)); - - lur = new LocalLur(access, "user1", null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1")); - - lur.clearAll(); - assertThat(lur.dumpInfo().size(), is(0)); - - lur = new LocalLur(access, "user1%" + encrypted, null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1@none")); - - lur.clearAll(); - assertThat(lur.dumpInfo().size(), is(0)); - - lur = new LocalLur(access, "user1@domain%" + encrypted, null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1@domain")); - - lur = new LocalLur(access, "user1@domain%" + encrypted + ":groupA", null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1@domain")); - - when(permMock.getKey()).thenReturn("groupA"); - assertThat(lur.handlesExclusively(permMock), is(true)); - when(permMock.getKey()).thenReturn("groupB"); - assertThat(lur.handlesExclusively(permMock), is(false)); - - assertThat(lur.fish(null, null), is(false)); - - Principal princ = new ConfigPrincipal("user1@localized", encrypted); - - lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); - assertThat(lur.fish(princ, lur.createPerm("groupA")), is(true)); - assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); - assertThat(lur.fish(princ, permMock), is(false)); - - princ = new ConfigPrincipal("user1@domain", encrypted); - assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); - - princ = new ConfigPrincipal("user1@localized", "badpass"); - assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); - - assertThat(lur.handles(null), is(false)); - - lur.fishAll(null, null); - - List perms = new ArrayList<>(); - perms.add(lur.createPerm("groupB")); - perms.add(lur.createPerm("groupA")); - princ = new ConfigPrincipal("user1@localized", encrypted); - lur.fishAll(princ, perms); - princ = new ConfigPrincipal("user1@localized", "badpass"); - lur.fishAll(princ, perms); - - assertThat(lur.validate(null, null, null, null), is(false)); - assertThat(lur.validate("user", null, "badpass".getBytes(), null), is(false)); - assertThat(lur.validate("user1@localized", null, encrypted.getBytes(), null), is(false)); - - lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); - assertThat(lur.validate("user1@localized", Type.PASSWORD, encrypted.getBytes(), null), is(true)); - - lur = new LocalLur(access, null, "admin"); - lur = new LocalLur(access, null, "admin:user1"); - lur = new LocalLur(access, null, "admin:user1@localized"); - lur = new LocalLur(access, null, "admin:user1@localized,user2@localized%" + password + ";user:user1@localized"); - } - - public static String rot13(String input) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < input.length(); i++) { - char c = input.charAt(i); - if (c >= 'a' && c <= 'm') { - c += 13; - } else if (c >= 'A' && c <= 'M') { - c += 13; - } else if (c >= 'n' && c <= 'z') { - c -= 13; - } else if (c >= 'N' && c <= 'Z') { - c -= 13; - } - sb.append(c); - } - return sb.toString(); - } + private PropAccess access; + private ByteArrayOutputStream outStream; + + @Mock Permission permMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]) { + @Override public String decrypt(String encrypted, boolean anytext) throws IOException { + return rot13(encrypted); + } + @Override public String encrypt(String unencrypted) throws IOException { + return rot13(unencrypted); + } + }; + + } + + @Test + public void test() throws IOException { + final String password = ""; + final String encrypted = rot13(password); + + LocalLur lur; + List.DumpInfo> info; + + lur = new LocalLur(access, null, null); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1", null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1")); + + lur.clearAll(); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1%" + encrypted, null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@none")); + + lur.clearAll(); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1@domain%" + encrypted, null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@domain")); + + lur = new LocalLur(access, "user1@domain%" + encrypted + ":groupA", null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@domain")); + + when(permMock.getKey()).thenReturn("groupA"); + assertThat(lur.handlesExclusively(permMock), is(true)); + when(permMock.getKey()).thenReturn("groupB"); + assertThat(lur.handlesExclusively(permMock), is(false)); + + assertThat(lur.fish(null, null), is(false)); + + Principal princ = new ConfigPrincipal("user1@localized", encrypted); + + lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); + assertThat(lur.fish(princ, lur.createPerm("groupA")), is(true)); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + assertThat(lur.fish(princ, permMock), is(false)); + + princ = new ConfigPrincipal("user1@domain", encrypted); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + + princ = new ConfigPrincipal("user1@localized", "badpass"); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + + assertThat(lur.handles(null), is(false)); + + lur.fishAll(null, null); + + List perms = new ArrayList<>(); + perms.add(lur.createPerm("groupB")); + perms.add(lur.createPerm("groupA")); + princ = new ConfigPrincipal("user1@localized", encrypted); + lur.fishAll(princ, perms); + princ = new ConfigPrincipal("user1@localized", "badpass"); + lur.fishAll(princ, perms); + + assertThat(lur.validate(null, null, null, null), is(false)); + assertThat(lur.validate("user", null, "badpass".getBytes(), null), is(false)); + assertThat(lur.validate("user1@localized", null, encrypted.getBytes(), null), is(false)); + + lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); + assertThat(lur.validate("user1@localized", Type.PASSWORD, encrypted.getBytes(), null), is(true)); + + lur = new LocalLur(access, null, "admin"); + lur = new LocalLur(access, null, "admin:user1"); + lur = new LocalLur(access, null, "admin:user1@localized"); + lur = new LocalLur(access, null, "admin:user1@localized,user2@localized%" + password + ";user:user1@localized"); + } + + public static String rot13(String input) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < input.length(); i++) { + char c = input.charAt(i); + if (c >= 'a' && c <= 'm') { + c += 13; + } else if (c >= 'A' && c <= 'M') { + c += 13; + } else if (c >= 'n' && c <= 'z') { + c -= 13; + } else if (c >= 'N' && c <= 'Z') { + c -= 13; + } + sb.append(c); + } + return sb.toString(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java index f4b051a8..4e378cb9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java @@ -34,38 +34,38 @@ import org.onap.aaf.cadi.Permission; public class JU_LocalPermission { - @Mock - Permission perm; + @Mock + Permission perm; - private LocalPermission localPerm; - private String role = "Fake Role"; + private LocalPermission localPerm; + private String role = "Fake Role"; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(perm.getKey()).thenReturn(role); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(perm.getKey()).thenReturn(role); - localPerm = new LocalPermission(role); - } + localPerm = new LocalPermission(role); + } - @Test - public void getKeyTest() { - assertThat(localPerm.getKey(), is(role)); - } + @Test + public void getKeyTest() { + assertThat(localPerm.getKey(), is(role)); + } - @Test - public void toStringTest() { - assertThat(localPerm.toString(), is(role)); - } + @Test + public void toStringTest() { + assertThat(localPerm.toString(), is(role)); + } - @Test - public void matchTest() { - assertTrue(localPerm.match(perm)); - } + @Test + public void matchTest() { + assertTrue(localPerm.match(perm)); + } - @Test - public void permTypeTest() { - assertThat(localPerm.permType(), is("LOCAL")); - } + @Test + public void permTypeTest() { + assertThat(localPerm.permType(), is("LOCAL")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java index 1a7293d3..c88a608b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java @@ -36,45 +36,45 @@ import org.onap.aaf.cadi.lur.NullLur; public class JU_NullLur { - @Mock - Principal p; + @Mock + Principal p; - @Mock - Permission perm; + @Mock + Permission perm; - @Mock - List perms; + @Mock + List perms; - private NullLur nullLur; + private NullLur nullLur; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); - nullLur = new NullLur(); - } + nullLur = new NullLur(); + } - @Test - public void coverageTests() throws Exception { + @Test + public void coverageTests() throws Exception { - Field nullClass = NullLur.class.getDeclaredField("NULL"); - nullClass.setAccessible(true); - assertThat(((Permission) nullClass.get(NullLur.class)).permType(), is("")); - assertThat(((Permission) nullClass.get(NullLur.class)).getKey(), is("")); - assertFalse(((Permission) nullClass.get(NullLur.class)).match(perm)); + Field nullClass = NullLur.class.getDeclaredField("NULL"); + nullClass.setAccessible(true); + assertThat(((Permission) nullClass.get(NullLur.class)).permType(), is("")); + assertThat(((Permission) nullClass.get(NullLur.class)).getKey(), is("")); + assertFalse(((Permission) nullClass.get(NullLur.class)).match(perm)); - nullLur.fishAll(p, perms); - nullLur.destroy(); + nullLur.fishAll(p, perms); + nullLur.destroy(); - assertFalse(nullLur.fish(p, perm)); - assertFalse(nullLur.handlesExclusively(perm)); - assertFalse(nullLur.handles(p)); - assertThat(nullLur.createPerm(""), is(nullClass.get(NullLur.class))); + assertFalse(nullLur.fish(p, perm)); + assertFalse(nullLur.handlesExclusively(perm)); + assertFalse(nullLur.handles(p)); + assertThat(nullLur.createPerm(""), is(nullClass.get(NullLur.class))); - StringBuilder sb = new StringBuilder(); - nullLur.clear(p, sb); - assertThat(sb.toString(), is("NullLur\n")); - assertThat(nullLur.toString(), is("NullLur\n")); - } + StringBuilder sb = new StringBuilder(); + nullLur.clear(p, sb); + assertThat(sb.toString(), is("NullLur\n")); + assertThat(nullLur.toString(), is("NullLur\n")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java index 32d6cd0a..e67e096f 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java @@ -40,85 +40,85 @@ import org.onap.aaf.cadi.principal.BasicPrincipal; public class JU_BasicPrincipal { - @Test - public void Constructor1Test() throws Exception { - // Test that everything works when the content doesn't contain "Basic" - BasicPrincipal bp = new BasicPrincipal("content", "domain"); - assertThat(bp.getName(), is("content")); - assertThat(bp.getCred(), is(nullValue())); - - // Test sending a user without an implicit domain - String name = "User"; - String password = "password"; - String content = name + ":" + password; - String domain = "exampledomain.com"; - String encrypted = new String(Symm.base64.encode(content.getBytes())); - bp = new BasicPrincipal("Basic " + encrypted, domain); - assertThat(bp.getShortName(), is(name)); - assertThat(bp.getName(), is(name + "@" + domain)); - assertThat(bp.getCred(), is(password.getBytes())); - - // Test sending a user with an implicit domain - String longName = name + "@" + domain + ":" + password; - encrypted = new String(Symm.base64.encode(longName.getBytes())); - bp = new BasicPrincipal("Basic " + encrypted, domain); - assertThat(bp.getShortName(), is(name)); - assertThat(bp.getName(), is(name + "@" + domain)); - assertThat(bp.getCred(), is(password.getBytes())); - - // Check that an exception is throw if no name is given in the content - try { - bp = new BasicPrincipal("Basic " + new String(Symm.base64.encode("no name".getBytes())), ""); - fail("Should have thrown an exception"); - } catch (IOException e) { - assertThat(e.getMessage(), is("Invalid Coding")); - } - } - - @Test - public void Constructor2Test() { - String name = "User"; - String password = "password"; - BasicCred bc = mock(BasicCred.class); - when(bc.getUser()).thenReturn(name); - when(bc.getCred()).thenReturn(password.getBytes()); - - BasicPrincipal bp = new BasicPrincipal(bc, "domain"); - assertThat(bp.getName(), is(name)); - assertThat(bp.getCred(), is(password.getBytes())); - } - - @Test - public void accessorsTest() throws IOException { - String name = "User"; - String password = "password"; - String content = name + ":" + password; - String domain = "exampledomain.com"; - String encrypted = new String(Symm.base64.encode(content.getBytes())); - String bearer = "bearer"; - long created = System.currentTimeMillis(); - BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, domain); - bp.setBearer(bearer); - - String expected = "Basic Authorization for " + name + "@" + domain + " evaluated on " + new Date(bp.created()).toString(); - assertTrue(Math.abs(bp.created() - created) < 10); - assertThat(bp.toString(), is(expected)); - assertThat(bp.tag(), is("BAth")); - assertThat(bp.personalName(), is(bp.getName())); - - // This test hits the abstract class BearerPrincipal - assertThat(bp.getBearer(), is(bearer)); - } - - - @Test - public void coverageTest() throws IOException { - String name = "User"; - String password = "password:with:colons"; - String content = name + ":" + password; - String encrypted = new String(Symm.base64.encode(content.getBytes())); - @SuppressWarnings("unused") - BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, "domain"); - } + @Test + public void Constructor1Test() throws Exception { + // Test that everything works when the content doesn't contain "Basic" + BasicPrincipal bp = new BasicPrincipal("content", "domain"); + assertThat(bp.getName(), is("content")); + assertThat(bp.getCred(), is(nullValue())); + + // Test sending a user without an implicit domain + String name = "User"; + String password = "password"; + String content = name + ":" + password; + String domain = "exampledomain.com"; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + bp = new BasicPrincipal("Basic " + encrypted, domain); + assertThat(bp.getShortName(), is(name)); + assertThat(bp.getName(), is(name + "@" + domain)); + assertThat(bp.getCred(), is(password.getBytes())); + + // Test sending a user with an implicit domain + String longName = name + "@" + domain + ":" + password; + encrypted = new String(Symm.base64.encode(longName.getBytes())); + bp = new BasicPrincipal("Basic " + encrypted, domain); + assertThat(bp.getShortName(), is(name)); + assertThat(bp.getName(), is(name + "@" + domain)); + assertThat(bp.getCred(), is(password.getBytes())); + + // Check that an exception is throw if no name is given in the content + try { + bp = new BasicPrincipal("Basic " + new String(Symm.base64.encode("no name".getBytes())), ""); + fail("Should have thrown an exception"); + } catch (IOException e) { + assertThat(e.getMessage(), is("Invalid Coding")); + } + } + + @Test + public void Constructor2Test() { + String name = "User"; + String password = "password"; + BasicCred bc = mock(BasicCred.class); + when(bc.getUser()).thenReturn(name); + when(bc.getCred()).thenReturn(password.getBytes()); + + BasicPrincipal bp = new BasicPrincipal(bc, "domain"); + assertThat(bp.getName(), is(name)); + assertThat(bp.getCred(), is(password.getBytes())); + } + + @Test + public void accessorsTest() throws IOException { + String name = "User"; + String password = "password"; + String content = name + ":" + password; + String domain = "exampledomain.com"; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + String bearer = "bearer"; + long created = System.currentTimeMillis(); + BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, domain); + bp.setBearer(bearer); + + String expected = "Basic Authorization for " + name + "@" + domain + " evaluated on " + new Date(bp.created()).toString(); + assertTrue(Math.abs(bp.created() - created) < 10); + assertThat(bp.toString(), is(expected)); + assertThat(bp.tag(), is("BAth")); + assertThat(bp.personalName(), is(bp.getName())); + + // This test hits the abstract class BearerPrincipal + assertThat(bp.getBearer(), is(bearer)); + } + + + @Test + public void coverageTest() throws IOException { + String name = "User"; + String password = "password:with:colons"; + String content = name + ":" + password; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + @SuppressWarnings("unused") + BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, "domain"); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java index 20e1d4d9..5b780c9a 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java @@ -43,82 +43,82 @@ import org.onap.aaf.cadi.principal.CachedBasicPrincipal; import org.onap.aaf.cadi.taf.HttpTaf; public class JU_CachedBasicPrincipal { - private Field creatorField; - private Field timeToLiveField; - - @Mock - private HttpTaf creator; - - private CachedPrincipal.Resp resp; - - @Before - public void setup() throws NoSuchFieldException, SecurityException { - MockitoAnnotations.initMocks(this); - - creatorField = CachedBasicPrincipal.class.getDeclaredField("creator"); - timeToLiveField = CachedBasicPrincipal.class.getDeclaredField("timeToLive"); - - creatorField.setAccessible(true); - timeToLiveField.setAccessible(true); - } - - @Test - public void Constructor1Test() throws IllegalArgumentException, IllegalAccessException { - String name = "User"; - String password = "password"; - BasicCred bc = mock(BasicCred.class); - when(bc.getUser()).thenReturn(name); - when(bc.getCred()).thenReturn(password.getBytes()); - - long timeToLive = 10000L; - long expires = System.currentTimeMillis() + timeToLive; - CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, bc, "domain", timeToLive); - - assertThat((HttpTaf)creatorField.get(cbp), is(creator)); - assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - } - - @Test - public void Constructor2Test() throws Exception { - String name = "User"; - String password = "password"; - String content = name + ":" + password; - long timeToLive = 10000L; - long expires = System.currentTimeMillis() + timeToLive; - CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); - - assertThat((HttpTaf)creatorField.get(cbp), is(creator)); - assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - } - - @Test - public void revalidateTest() throws IOException, IllegalArgumentException, IllegalAccessException, InterruptedException { - resp = CachedPrincipal.Resp.REVALIDATED; - when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); - - String name = "User"; - String password = "password"; - String content = name + ":" + password; - long timeToLive = 10000L; - long expires = System.currentTimeMillis() + timeToLive; - CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); - - assertTrue(Math.abs(cbp.expires() - expires) < 10); - - Thread.sleep(1); - expires = System.currentTimeMillis() + timeToLive; - assertThat(cbp.revalidate(new Object()), is(resp)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - - resp = CachedPrincipal.Resp.UNVALIDATED; - when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); - expires = System.currentTimeMillis() + timeToLive; - cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); - - assertThat(cbp.revalidate(new Object()), is(resp)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - } + private Field creatorField; + private Field timeToLiveField; + + @Mock + private HttpTaf creator; + + private CachedPrincipal.Resp resp; + + @Before + public void setup() throws NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + creatorField = CachedBasicPrincipal.class.getDeclaredField("creator"); + timeToLiveField = CachedBasicPrincipal.class.getDeclaredField("timeToLive"); + + creatorField.setAccessible(true); + timeToLiveField.setAccessible(true); + } + + @Test + public void Constructor1Test() throws IllegalArgumentException, IllegalAccessException { + String name = "User"; + String password = "password"; + BasicCred bc = mock(BasicCred.class); + when(bc.getUser()).thenReturn(name); + when(bc.getCred()).thenReturn(password.getBytes()); + + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, bc, "domain", timeToLive); + + assertThat((HttpTaf)creatorField.get(cbp), is(creator)); + assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } + + @Test + public void Constructor2Test() throws Exception { + String name = "User"; + String password = "password"; + String content = name + ":" + password; + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertThat((HttpTaf)creatorField.get(cbp), is(creator)); + assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } + + @Test + public void revalidateTest() throws IOException, IllegalArgumentException, IllegalAccessException, InterruptedException { + resp = CachedPrincipal.Resp.REVALIDATED; + when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); + + String name = "User"; + String password = "password"; + String content = name + ":" + password; + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertTrue(Math.abs(cbp.expires() - expires) < 10); + + Thread.sleep(1); + expires = System.currentTimeMillis() + timeToLive; + assertThat(cbp.revalidate(new Object()), is(resp)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + + resp = CachedPrincipal.Resp.UNVALIDATED; + when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); + expires = System.currentTimeMillis() + timeToLive; + cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertThat(cbp.revalidate(new Object()), is(resp)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java index e9bd799c..04b9367b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java @@ -36,35 +36,35 @@ import org.onap.aaf.cadi.principal.X509Principal; public class JU_Kind { - @Mock - private TrustPrincipal trust; + @Mock + private TrustPrincipal trust; - @Mock - private X509Principal x509; + @Mock + private X509Principal x509; - @Mock - private OAuth2FormPrincipal oauth; + @Mock + private OAuth2FormPrincipal oauth; - @Mock - private BasicPrincipal basic; + @Mock + private BasicPrincipal basic; - @Before - public void setup() throws SecurityException { - MockitoAnnotations.initMocks(this); - } + @Before + public void setup() throws SecurityException { + MockitoAnnotations.initMocks(this); + } - @Test - public void getKind() { - assertThat(Kind.getKind(trust), is('U')); - assertThat(Kind.getKind(x509), is('X')); - assertThat(Kind.getKind(oauth), is('O')); - assertThat(Kind.getKind(basic), is('B')); - } + @Test + public void getKind() { + assertThat(Kind.getKind(trust), is('U')); + assertThat(Kind.getKind(x509), is('X')); + assertThat(Kind.getKind(oauth), is('O')); + assertThat(Kind.getKind(basic), is('B')); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - Kind kind = new Kind(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + Kind kind = new Kind(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java index c0b1c2af..c9623fb9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java @@ -30,27 +30,27 @@ import org.onap.aaf.cadi.principal.OAuth2FormPrincipal; public class JU_OAuth2FormPrincipal { - private String username = "user"; - private String id = "id"; - - @Test - public void accessorsTest() { - OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); - assertThat(oauth.getName(), is(username)); - assertThat(oauth.client_id(), is(id)); - assertThat(oauth.tag(), is("OAuth")); - } - - @Test - public void personalNameTest() { - OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); - assertThat(oauth.personalName(), is(username + "|" + id)); - - oauth = new OAuth2FormPrincipal(id, null); - assertThat(oauth.personalName(), is(id)); - - oauth = new OAuth2FormPrincipal(id, id); - assertThat(oauth.personalName(), is(id)); - } + private String username = "user"; + private String id = "id"; + + @Test + public void accessorsTest() { + OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); + assertThat(oauth.getName(), is(username)); + assertThat(oauth.client_id(), is(id)); + assertThat(oauth.tag(), is("OAuth")); + } + + @Test + public void personalNameTest() { + OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); + assertThat(oauth.personalName(), is(username + "|" + id)); + + oauth = new OAuth2FormPrincipal(id, null); + assertThat(oauth.personalName(), is(id)); + + oauth = new OAuth2FormPrincipal(id, id); + assertThat(oauth.personalName(), is(id)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java index cce86255..a76e01f7 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java @@ -30,11 +30,11 @@ import org.onap.aaf.cadi.principal.StringTagLookup; public class JU_StringTagLookup { - @Test - public void accessorsTest() throws Exception { - String tag = "tag"; - StringTagLookup stl = new StringTagLookup(tag); - assertThat(stl.lookup(), is(tag)); - } + @Test + public void accessorsTest() throws Exception { + String tag = "tag"; + StringTagLookup stl = new StringTagLookup(tag); + assertThat(stl.lookup(), is(tag)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java index 2bbfee23..3dfe8d86 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java @@ -33,36 +33,36 @@ import org.onap.aaf.cadi.principal.StringTagLookup; public class JU_TaggedPrincipal { - private final String name = "stubbedName"; - private final String tag = "tag"; + private final String name = "stubbedName"; + private final String tag = "tag"; - private class TaggedPrincipalStub extends TaggedPrincipal { - public TaggedPrincipalStub() { super(); } - public TaggedPrincipalStub(final TagLookup tl) { super(tl); } - @Override public String getName() { return name; } - @Override public String tag() { return null; } - } + private class TaggedPrincipalStub extends TaggedPrincipal { + public TaggedPrincipalStub() { super(); } + public TaggedPrincipalStub(final TagLookup tl) { super(tl); } + @Override public String getName() { return name; } + @Override public String tag() { return null; } + } - private class WhinyTagLookup implements TagLookup { - public WhinyTagLookup(final String tag) { } - @Override - public String lookup() throws CadiException { - throw new CadiException(); - } - } + private class WhinyTagLookup implements TagLookup { + public WhinyTagLookup(final String tag) { } + @Override + public String lookup() throws CadiException { + throw new CadiException(); + } + } - @Test - public void personalNameTest() { - TaggedPrincipal tp = new TaggedPrincipalStub(); - assertThat(tp.personalName(), is(name)); + @Test + public void personalNameTest() { + TaggedPrincipal tp = new TaggedPrincipalStub(); + assertThat(tp.personalName(), is(name)); - StringTagLookup stl = new StringTagLookup(tag); - tp = new TaggedPrincipalStub(stl); - assertThat(tp.personalName(), is(tag)); + StringTagLookup stl = new StringTagLookup(tag); + tp = new TaggedPrincipalStub(stl); + assertThat(tp.personalName(), is(tag)); - WhinyTagLookup wtl = new WhinyTagLookup(tag); - tp.setTagLookup(wtl); - assertThat(tp.personalName(), is(name)); - } + WhinyTagLookup wtl = new WhinyTagLookup(tag); + tp.setTagLookup(wtl); + assertThat(tp.personalName(), is(name)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java index 12b4bc9f..ed1ae4c9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java @@ -34,58 +34,58 @@ import org.onap.aaf.cadi.principal.TrustPrincipal; public class JU_TrustPrincipal { - private final String ucName = "UserChain"; - private final String uc = "This is a UserChain"; - private final String taggedName = "TaggedPrincipal"; - private final String tag = "tag"; - private final String pName = "Principal"; + private final String ucName = "UserChain"; + private final String uc = "This is a UserChain"; + private final String taggedName = "TaggedPrincipal"; + private final String tag = "tag"; + private final String pName = "Principal"; - private class UserChainPrincipalStub implements Principal, UserChain { - @Override public String userChain() { return uc; } - @Override public String getName() { return ucName; } - } + private class UserChainPrincipalStub implements Principal, UserChain { + @Override public String userChain() { return uc; } + @Override public String getName() { return ucName; } + } - private class TaggedPrincipalStub extends TaggedPrincipal { - public TaggedPrincipalStub() { super(); } - @Override public String getName() { return taggedName; } - @Override public String tag() { return tag; } - } + private class TaggedPrincipalStub extends TaggedPrincipal { + public TaggedPrincipalStub() { super(); } + @Override public String getName() { return taggedName; } + @Override public String tag() { return tag; } + } - private class PrincipalStub implements Principal { - @Override public String getName() { return pName; } - } + private class PrincipalStub implements Principal { + @Override public String getName() { return pName; } + } - @Test - public void userChainConstructorTest() { - UserChainPrincipalStub ucps = new UserChainPrincipalStub(); - TrustPrincipal tp = new TrustPrincipal(ucps, taggedName); - assertThat(tp.getName(), is(taggedName)); - assertThat(tp.userChain(), is(uc)); - assertSame(tp.original(), ucps); - assertThat(tp.tag(), is(uc)); - assertThat(tp.personalName(), is(ucName + '[' + uc + ']')); - } + @Test + public void userChainConstructorTest() { + UserChainPrincipalStub ucps = new UserChainPrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(ucps, taggedName); + assertThat(tp.getName(), is(taggedName)); + assertThat(tp.userChain(), is(uc)); + assertSame(tp.original(), ucps); + assertThat(tp.tag(), is(uc)); + assertThat(tp.personalName(), is(ucName + '[' + uc + ']')); + } - @Test - public void taggedPrincipalConstructorTest() { - TaggedPrincipal tagged = new TaggedPrincipalStub(); - TrustPrincipal tp = new TrustPrincipal(tagged, taggedName); - assertThat(tp.getName(), is(taggedName)); - assertThat(tp.userChain(), is(tag)); - assertSame(tp.original(), tagged); - assertThat(tp.tag(), is(tag)); - assertThat(tp.personalName(), is(taggedName + '[' + tag + ']')); - } + @Test + public void taggedPrincipalConstructorTest() { + TaggedPrincipal tagged = new TaggedPrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(tagged, taggedName); + assertThat(tp.getName(), is(taggedName)); + assertThat(tp.userChain(), is(tag)); + assertSame(tp.original(), tagged); + assertThat(tp.tag(), is(tag)); + assertThat(tp.personalName(), is(taggedName + '[' + tag + ']')); + } - @Test - public void principalConstructorTest() { - Principal principal = new PrincipalStub(); - TrustPrincipal tp = new TrustPrincipal(principal, pName); - assertThat(tp.getName(), is(pName)); - assertThat(tp.userChain(), is(principal.getClass().getSimpleName())); - assertSame(tp.original(), principal); - assertThat(tp.tag(), is(principal.getClass().getSimpleName())); - assertThat(tp.personalName(), is(pName + '[' + principal.getClass().getSimpleName() + ']')); - } + @Test + public void principalConstructorTest() { + Principal principal = new PrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(principal, pName); + assertThat(tp.getName(), is(pName)); + assertThat(tp.userChain(), is(principal.getClass().getSimpleName())); + assertSame(tp.original(), principal); + assertThat(tp.tag(), is(principal.getClass().getSimpleName())); + assertThat(tp.personalName(), is(pName + '[' + principal.getClass().getSimpleName() + ']')); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java index c0095131..60fc88e2 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java @@ -30,12 +30,12 @@ import org.onap.aaf.cadi.principal.UnAuthPrincipal; public class JU_UnAuthPrincipal { - private final String name = "name"; + private final String name = "name"; - @Test - public void accessorsTest() { - UnAuthPrincipal up = new UnAuthPrincipal(name); - assertThat(up.getName(), is(name)); - } + @Test + public void accessorsTest() { + UnAuthPrincipal up = new UnAuthPrincipal(name); + assertThat(up.getName(), is(name)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java index 0857a870..a8839f2c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java @@ -38,103 +38,103 @@ import org.onap.aaf.cadi.principal.X509Principal; public class JU_X509Principal { - private final String name = "x509 name"; - private final byte[] cred = "super duper secret password".getBytes(); - - @Mock - X509Certificate cert; - - @Mock - Principal subject; - - @Before - public void setup() throws CertificateEncodingException { - MockitoAnnotations.initMocks(this); - when(cert.getEncoded()).thenReturn(cred); - } - - @Test - public void constructor1Test() throws IOException { - X509Principal x509 = new X509Principal(name, cert); - // Call twice to hit both branches - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.toString(), is("X509 Authentication for " + name)); - assertTrue(x509.getCred().equals(cred)); - assertThat(x509.getName(), is(name)); - assertThat(x509.tag(), is("x509")); - } - - @Test - public void constructor2Test() throws IOException { - X509Principal x509 = new X509Principal(name, cert, cred,null); - // Call twice to hit both branches - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.toString(), is("X509 Authentication for " + name)); - assertTrue(x509.getCred().equals(cred)); - assertThat(x509.getName(), is(name)); - assertThat(x509.tag(), is("x509")); - } - - @Test - public void constructor3Test() throws IOException { - final String longName = "name@domain"; - when(subject.getName()).thenReturn("OU=" + longName + ",extra"); - when(cert.getSubjectDN()).thenReturn(subject); - X509Principal x509 = new X509Principal(cert, cred,null); - // Call twice to hit both branches - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.toString(), is("X509 Authentication for " + longName)); - assertTrue(x509.getCred().equals(cred)); - assertThat(x509.getName(), is(longName)); - - when(subject.getName()).thenReturn(longName + ",extra"); - when(cert.getSubjectDN()).thenReturn(subject); - try { - x509 = new X509Principal(cert, cred, null); - fail("Should have thrown an Exception"); - } catch(IOException e) { - assertThat(e.getMessage(), is("X509 does not have Identity as CN")); - } - - when(subject.getName()).thenReturn("OU=" + longName); - when(cert.getSubjectDN()).thenReturn(subject); - try { - x509 = new X509Principal(cert, cred, null); - fail("Should have thrown an Exception"); - } catch(IOException e) { - assertThat(e.getMessage(), is("X509 does not have Identity as CN")); - } - - when(subject.getName()).thenReturn("OU=" + name + ",exta"); - when(cert.getSubjectDN()).thenReturn(subject); - try { - x509 = new X509Principal(cert, cred, null); - fail("Should have thrown an Exception"); - } catch(IOException e) { - assertThat(e.getMessage(), is("X509 does not have Identity as CN")); - } - - } - - @Test - public void throwsTest() throws CertificateEncodingException { - when(cert.getEncoded()).thenThrow(new CertificateEncodingException()); - X509Principal x509 = new X509Principal(name, cert); - assertThat(x509.getCred(), is(nullValue())); - try { - x509.getAsHeader(); - fail("Should have thrown an Exception"); - } catch (IOException e) { - } - } - - @Test - public void getCredTest() { - X509Principal x509 = new X509Principal(name, cert); - // Call twice to hit both branches - assertTrue(x509.getCred().equals(cred)); - assertTrue(x509.getCred().equals(cred)); - } + private final String name = "x509 name"; + private final byte[] cred = "super duper secret password".getBytes(); + + @Mock + X509Certificate cert; + + @Mock + Principal subject; + + @Before + public void setup() throws CertificateEncodingException { + MockitoAnnotations.initMocks(this); + when(cert.getEncoded()).thenReturn(cred); + } + + @Test + public void constructor1Test() throws IOException { + X509Principal x509 = new X509Principal(name, cert); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + name)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(name)); + assertThat(x509.tag(), is("x509")); + } + + @Test + public void constructor2Test() throws IOException { + X509Principal x509 = new X509Principal(name, cert, cred,null); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + name)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(name)); + assertThat(x509.tag(), is("x509")); + } + + @Test + public void constructor3Test() throws IOException { + final String longName = "name@domain"; + when(subject.getName()).thenReturn("OU=" + longName + ",extra"); + when(cert.getSubjectDN()).thenReturn(subject); + X509Principal x509 = new X509Principal(cert, cred,null); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + longName)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(longName)); + + when(subject.getName()).thenReturn(longName + ",extra"); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch(IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + when(subject.getName()).thenReturn("OU=" + longName); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch(IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + when(subject.getName()).thenReturn("OU=" + name + ",exta"); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch(IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + } + + @Test + public void throwsTest() throws CertificateEncodingException { + when(cert.getEncoded()).thenThrow(new CertificateEncodingException()); + X509Principal x509 = new X509Principal(name, cert); + assertThat(x509.getCred(), is(nullValue())); + try { + x509.getAsHeader(); + fail("Should have thrown an Exception"); + } catch (IOException e) { + } + } + + @Test + public void getCredTest() { + X509Principal x509 = new X509Principal(name, cert); + // Call twice to hit both branches + assertTrue(x509.getCred().equals(cred)); + assertTrue(x509.getCred().equals(cred)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java index 137eab3b..b5f019d4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java @@ -67,121 +67,121 @@ import org.onap.aaf.cadi.taf.basic.BasicHttpTaf; public class JU_BasicHttpTaf { - private final static String realm = "realm"; - private final static String id = "id"; - private final static String addr = "addr"; - - private final static String name = "User"; - private final static String password = "password"; - private final static String content = name + ":" + password; - private static String encrypted; - - private final static long timeToLive = 10000L; - - private PropAccess access; - - @Mock private HttpServletResponse respMock; - @Mock private HttpServletRequest reqMock; - @Mock private CredVal rbacMock; - @Mock private CachedPrincipal princMock; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - encrypted = new String(Symm.base64.encode(content.getBytes())); - } - - @Test - public void test() { - BasicHttpTaf taf = new BasicHttpTaf(access, rbacMock, realm, timeToLive, true); - BasicCredStub bcstub = new BasicCredStub(); - assertThat(taf.validate(LifeForm.SBLF, bcstub, respMock), is(not(nullValue()))); - - assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); - - when(reqMock.getHeader("Authorization")).thenReturn("test"); - assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); - - when(reqMock.getHeader("Authorization")).thenReturn("Basic " + encrypted); - assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); - - assertThat(taf.revalidate(princMock, "state"), is(Resp.NOT_MINE)); - - assertThat(taf.toString(), is("Basic Auth enabled on realm: " + realm)); - } - - private class BasicCredStub implements HttpServletRequest, BasicCred { - @Override public String getUser() { return id; } - @Override public String getRemoteAddr() { return addr; } - - @Override public AsyncContext getAsyncContext() { return null; } - @Override public Object getAttribute(String arg0) { return null; } - @Override public Enumeration getAttributeNames() { return null; } - @Override public String getCharacterEncoding() { return null; } - @Override public int getContentLength() { return 0; } - @Override public String getContentType() { return null; } - @Override public DispatcherType getDispatcherType() { return null; } - @Override public ServletInputStream getInputStream() throws IOException { return null; } - @Override public String getLocalAddr() { return null; } - @Override public String getLocalName() { return null; } - @Override public int getLocalPort() { return 0; } - @Override public Locale getLocale() { return null; } - @Override public Enumeration getLocales() { return null; } - @Override public String getParameter(String arg0) { return null; } - @Override public Map getParameterMap() { return null; } - @Override public Enumeration getParameterNames() { return null; } - @Override public String[] getParameterValues(String arg0) { return null; } - @Override public String getProtocol() { return null; } - @Override public BufferedReader getReader() throws IOException { return null; } - @Override public String getRealPath(String arg0) { return null; } - @Override public String getRemoteHost() { return null; } - @Override public int getRemotePort() { return 0; } - @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; } - @Override public String getScheme() { return null; } - @Override public String getServerName() { return null; } - @Override public int getServerPort() { return 0; } - @Override public ServletContext getServletContext() { return null; } - @Override public boolean isAsyncStarted() { return false; } - @Override public boolean isAsyncSupported() { return false; } - @Override public boolean isSecure() { return false; } - @Override public void removeAttribute(String arg0) { } - @Override public void setAttribute(String arg0, Object arg1) { } - @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { } - @Override public AsyncContext startAsync() throws IllegalStateException { return null; } - @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) throws IllegalStateException { return null; } - @Override public byte[] getCred() { return null; } - @Override public void setUser(String user) { } - @Override public void setCred(byte[] passwd) { } - @Override public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException { return false; } - @Override public String getAuthType() { return null; } - @Override public String getContextPath() { return null; } - @Override public Cookie[] getCookies() { return null; } - @Override public long getDateHeader(String arg0) { return 0; } - @Override public String getHeader(String arg0) { return null; } - @Override public Enumeration getHeaderNames() { return null; } - @Override public Enumeration getHeaders(String arg0) { return null; } - @Override public int getIntHeader(String arg0) { return 0; } - @Override public String getMethod() { return null; } - @Override public Part getPart(String arg0) throws IOException, ServletException { return null; } - @Override public Collection getParts() throws IOException, ServletException { return null; } - @Override public String getPathInfo() { return null; } - @Override public String getPathTranslated() { return null; } - @Override public String getQueryString() { return null; } - @Override public String getRemoteUser() { return null; } - @Override public String getRequestURI() { return null; } - @Override public StringBuffer getRequestURL() { return null; } - @Override public String getRequestedSessionId() { return null; } - @Override public String getServletPath() { return null; } - @Override public HttpSession getSession() { return null; } - @Override public HttpSession getSession(boolean arg0) { return null; } - @Override public Principal getUserPrincipal() { return null; } - @Override public boolean isRequestedSessionIdFromCookie() { return false; } - @Override public boolean isRequestedSessionIdFromURL() { return false; } - @Override public boolean isRequestedSessionIdFromUrl() { return false; } - @Override public boolean isRequestedSessionIdValid() { return false; } - @Override public boolean isUserInRole(String arg0) { return false; } - @Override public void login(String arg0, String arg1) throws ServletException { } - @Override public void logout() throws ServletException { } - } + private final static String realm = "realm"; + private final static String id = "id"; + private final static String addr = "addr"; + + private final static String name = "User"; + private final static String password = "password"; + private final static String content = name + ":" + password; + private static String encrypted; + + private final static long timeToLive = 10000L; + + private PropAccess access; + + @Mock private HttpServletResponse respMock; + @Mock private HttpServletRequest reqMock; + @Mock private CredVal rbacMock; + @Mock private CachedPrincipal princMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + encrypted = new String(Symm.base64.encode(content.getBytes())); + } + + @Test + public void test() { + BasicHttpTaf taf = new BasicHttpTaf(access, rbacMock, realm, timeToLive, true); + BasicCredStub bcstub = new BasicCredStub(); + assertThat(taf.validate(LifeForm.SBLF, bcstub, respMock), is(not(nullValue()))); + + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + when(reqMock.getHeader("Authorization")).thenReturn("test"); + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + when(reqMock.getHeader("Authorization")).thenReturn("Basic " + encrypted); + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + assertThat(taf.revalidate(princMock, "state"), is(Resp.NOT_MINE)); + + assertThat(taf.toString(), is("Basic Auth enabled on realm: " + realm)); + } + + private class BasicCredStub implements HttpServletRequest, BasicCred { + @Override public String getUser() { return id; } + @Override public String getRemoteAddr() { return addr; } + + @Override public AsyncContext getAsyncContext() { return null; } + @Override public Object getAttribute(String arg0) { return null; } + @Override public Enumeration getAttributeNames() { return null; } + @Override public String getCharacterEncoding() { return null; } + @Override public int getContentLength() { return 0; } + @Override public String getContentType() { return null; } + @Override public DispatcherType getDispatcherType() { return null; } + @Override public ServletInputStream getInputStream() throws IOException { return null; } + @Override public String getLocalAddr() { return null; } + @Override public String getLocalName() { return null; } + @Override public int getLocalPort() { return 0; } + @Override public Locale getLocale() { return null; } + @Override public Enumeration getLocales() { return null; } + @Override public String getParameter(String arg0) { return null; } + @Override public Map getParameterMap() { return null; } + @Override public Enumeration getParameterNames() { return null; } + @Override public String[] getParameterValues(String arg0) { return null; } + @Override public String getProtocol() { return null; } + @Override public BufferedReader getReader() throws IOException { return null; } + @Override public String getRealPath(String arg0) { return null; } + @Override public String getRemoteHost() { return null; } + @Override public int getRemotePort() { return 0; } + @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; } + @Override public String getScheme() { return null; } + @Override public String getServerName() { return null; } + @Override public int getServerPort() { return 0; } + @Override public ServletContext getServletContext() { return null; } + @Override public boolean isAsyncStarted() { return false; } + @Override public boolean isAsyncSupported() { return false; } + @Override public boolean isSecure() { return false; } + @Override public void removeAttribute(String arg0) { } + @Override public void setAttribute(String arg0, Object arg1) { } + @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { } + @Override public AsyncContext startAsync() throws IllegalStateException { return null; } + @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) throws IllegalStateException { return null; } + @Override public byte[] getCred() { return null; } + @Override public void setUser(String user) { } + @Override public void setCred(byte[] passwd) { } + @Override public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException { return false; } + @Override public String getAuthType() { return null; } + @Override public String getContextPath() { return null; } + @Override public Cookie[] getCookies() { return null; } + @Override public long getDateHeader(String arg0) { return 0; } + @Override public String getHeader(String arg0) { return null; } + @Override public Enumeration getHeaderNames() { return null; } + @Override public Enumeration getHeaders(String arg0) { return null; } + @Override public int getIntHeader(String arg0) { return 0; } + @Override public String getMethod() { return null; } + @Override public Part getPart(String arg0) throws IOException, ServletException { return null; } + @Override public Collection getParts() throws IOException, ServletException { return null; } + @Override public String getPathInfo() { return null; } + @Override public String getPathTranslated() { return null; } + @Override public String getQueryString() { return null; } + @Override public String getRemoteUser() { return null; } + @Override public String getRequestURI() { return null; } + @Override public StringBuffer getRequestURL() { return null; } + @Override public String getRequestedSessionId() { return null; } + @Override public String getServletPath() { return null; } + @Override public HttpSession getSession() { return null; } + @Override public HttpSession getSession(boolean arg0) { return null; } + @Override public Principal getUserPrincipal() { return null; } + @Override public boolean isRequestedSessionIdFromCookie() { return false; } + @Override public boolean isRequestedSessionIdFromURL() { return false; } + @Override public boolean isRequestedSessionIdFromUrl() { return false; } + @Override public boolean isRequestedSessionIdValid() { return false; } + @Override public boolean isUserInRole(String arg0) { return false; } + @Override public void login(String arg0, String arg1) throws ServletException { } + @Override public void logout() throws ServletException { } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java index 8eba1faf..641545ca 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java @@ -41,27 +41,27 @@ import org.onap.aaf.cadi.taf.basic.BasicHttpTafResp; public class JU_BasicHttpTafResp { - private final static String realm = "realm"; - private final static String description = "description"; + private final static String realm = "realm"; + private final static String description = "description"; - private PropAccess access; + private PropAccess access; - @Mock private HttpServletResponse respMock; - @Mock private TaggedPrincipal princMock; + @Mock private HttpServletResponse respMock; + @Mock private TaggedPrincipal princMock; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } - @Test - public void test() throws IOException { - BasicHttpTafResp tafResp = new BasicHttpTafResp(access, princMock, description, RESP.IS_AUTHENTICATED, respMock, realm, false); + @Test + public void test() throws IOException { + BasicHttpTafResp tafResp = new BasicHttpTafResp(access, princMock, description, RESP.IS_AUTHENTICATED, respMock, realm, false); - assertThat(tafResp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); - assertThat(tafResp.isAuthenticated(), is (RESP.IS_AUTHENTICATED)); - assertThat(tafResp.isFailedAttempt(), is(false)); - } + assertThat(tafResp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + assertThat(tafResp.isAuthenticated(), is (RESP.IS_AUTHENTICATED)); + assertThat(tafResp.isFailedAttempt(), is(false)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java index 36f17ef1..83c93210 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java @@ -39,25 +39,25 @@ import org.onap.aaf.cadi.taf.cert.X509HttpTafResp; public class JU_X509HttpTafResp { - private final static String description = "description"; - private final static RESP status = RESP.IS_AUTHENTICATED; - - private PropAccess access; - - @Mock private TaggedPrincipal princMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws IOException { - X509HttpTafResp resp = new X509HttpTafResp(access, princMock, description, status); - assertThat(resp.authenticate(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(resp.isAuthenticated(), is(status)); - assertThat(resp.toString(), is(status.name())); - } + private final static String description = "description"; + private final static RESP status = RESP.IS_AUTHENTICATED; + + private PropAccess access; + + @Mock private TaggedPrincipal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws IOException { + X509HttpTafResp resp = new X509HttpTafResp(access, princMock, description, status); + assertThat(resp.authenticate(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.toString(), is(status.name())); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java index 997ebced..0f337d1b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java @@ -48,324 +48,324 @@ import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf.Counter; public class JU_DenialOfServiceTaf { - @Mock - HttpServletResponse respMock; - - @Mock - HttpServletRequest reqMock1; - - @Mock - HttpServletRequest reqMock2; - - @Mock - HttpServletRequest reqMock3; - - @Mock - Access accessMock; - - private File dosIPFile; - private File dosIDFile; - private File dosDir; - private final String dosDirName = "test"; - - private final String id1 = "id1"; - private final String id2 = "id2"; - - private final String ip1 = "111.111.111.111"; - private final String ip2 = "222.222.222.222"; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - - dosDir = new File(dosDirName); - dosDir.mkdirs(); - dosIPFile = new File(dosDirName, "/dosIP"); - dosIDFile = new File(dosDirName, "/dosID"); - dosIPFile.delete(); - dosIDFile.delete(); - - when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); - when(reqMock1.getRemoteAddr()).thenReturn(ip1); - when(reqMock2.getRemoteAddr()).thenReturn(ip2); - - setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); - setPrivateField(DenialOfServiceTaf.class, "deniedID", null); - setPrivateField(DenialOfServiceTaf.class, "dosIP", null); - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - } - - @After - public void tearDown() { - dosIPFile = new File(dosDirName, "/dosIP"); - dosIDFile = new File(dosDirName, "/dosID"); - dosIPFile.delete(); - dosIDFile.delete(); - } - - @Test - public void constructorTest() throws CadiException { - @SuppressWarnings("unused") - DenialOfServiceTaf dost; - - // coverage... - when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(null); - dost = new DenialOfServiceTaf(accessMock); - - when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); - dost = new DenialOfServiceTaf(accessMock); - - // more coverage... - dost = new DenialOfServiceTaf(accessMock); - - // more coverage... - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - dost = new DenialOfServiceTaf(accessMock); - } - - @Test - public void validateTest() throws CadiException { - DenialOfServiceTaf dost; - TafResp tafResp; - - dost = new DenialOfServiceTaf(accessMock); - tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); - - assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); - assertThat(tafResp.taf(), is("DenialOfServiceTaf")); - - assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); - - tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); - assertThat(tafResp.desc(), is(ip1 + " is on the IP Denial list")); - - tafResp = dost.validate(LifeForm.SBLF, reqMock2, respMock); - assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); - assertThat(tafResp.taf(), is("DenialOfServiceTaf")); - } - - @Test - public void revalidateTest() throws CadiException { - DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); - Resp resp = dost.revalidate(null, null); - assertThat(resp, is(Resp.NOT_MINE)); - } - - @Test - public void denyIPTest() throws CadiException { - assertThat(DenialOfServiceTaf.isDeniedIP(ip1), is(nullValue())); - assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyIP(ip2), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyIP(ip1), is(false)); // false because it's already been added - assertThat(DenialOfServiceTaf.denyIP(ip2), is(false)); // false because it's already been added - - Counter counter; - counter = DenialOfServiceTaf.isDeniedIP(ip1); - assertThat(counter.getName(), is(ip1)); - assertThat(counter.getCount(), is(0)); - assertThat(counter.getLast(), is(0L)); - assertThat(counter.toString(), is(ip1 + " is on the denied list, but has not attempted Access" )); - - DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); - dost.validate(LifeForm.SBLF, reqMock1, respMock); - long approxTime = System.currentTimeMillis(); - - counter = DenialOfServiceTaf.isDeniedIP(ip1); - assertThat(counter.getName(), is(ip1)); - assertThat(counter.getCount(), is(1)); - assertThat((Math.abs(approxTime - counter.getLast()) < 10), is(true)); - assertThat(counter.toString().contains(ip1), is(true)); - assertThat(counter.toString().contains(" has been denied 1 times since "), is(true)); - assertThat(counter.toString().contains(". Last denial was "), is(true)); - - // coverage... - dost.validate(LifeForm.SBLF, reqMock1, respMock); - - assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(true)); - assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(false)); - assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(true)); - assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(false)); - } - - @Test - public void denyIDTest() throws CadiException { - assertThat(DenialOfServiceTaf.isDeniedID(id1), is(nullValue())); - assertThat(DenialOfServiceTaf.denyID(id1), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyID(id2), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyID(id1), is(false)); // false because it's already been added - assertThat(DenialOfServiceTaf.denyID(id2), is(false)); // false because it's already been added - - Counter counter; - counter = DenialOfServiceTaf.isDeniedID(id1); - assertThat(counter.getName(), is(id1)); - assertThat(counter.getCount(), is(0)); - assertThat(counter.getLast(), is(0L)); - - assertThat(DenialOfServiceTaf.removeDenyID(id1), is(true)); - assertThat(DenialOfServiceTaf.removeDenyID(id1), is(false)); - assertThat(DenialOfServiceTaf.removeDenyID(id2), is(true)); - assertThat(DenialOfServiceTaf.removeDenyID(id2), is(false)); - } - - @Test - public void reportTest() throws CadiException { - DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); - List denials = dost.report(); - assertThat(denials.size(), is(0)); - - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.denyID(id2); - - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.denyIP(ip2); - - denials = dost.report(); - assertThat(denials.size(), is(4)); - for (String denied : denials) { - switch (denied.split(" ", 2)[0]) { - case ip1: - case ip2: - case id1: - case id2: - break; - default: - fail("The line: [" + denied + "] shouldn't be in the report"); - } - } - } - - @Test - public void respDenyIDTest() { - TafResp tafResp = DenialOfServiceTaf.respDenyID(accessMock, id1); - assertThat(tafResp.desc(), is(id1 + " is on the Identity Denial list")); - } - - @Test - public void ipFileIOTest() throws CadiException, IOException { - @SuppressWarnings("unused") - DenialOfServiceTaf dost; - - dosIPFile.createNewFile(); - - // coverage... - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.removeDenyIP(ip1); - - dost = new DenialOfServiceTaf(accessMock); - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.denyIP(ip2); - // coverage... - DenialOfServiceTaf.denyIP(ip2); - - String contents = readContentsFromFile(dosIPFile); - assertThat(contents.contains(ip1), is(true)); - assertThat(contents.contains(ip2), is(true)); - - // Removing all ips should delete the file - assertThat(dosIPFile.exists(), is(true)); - DenialOfServiceTaf.removeDenyIP(ip1); - DenialOfServiceTaf.removeDenyIP(ip2); - assertThat(dosIPFile.exists(), is(false)); - - dosIPFile.createNewFile(); - - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.denyIP(ip2); - - setPrivateField(DenialOfServiceTaf.class, "dosIP", null); - dost = new DenialOfServiceTaf(accessMock); - - contents = readContentsFromFile(dosIPFile); - assertThat(contents.contains(ip1), is(true)); - assertThat(contents.contains(ip2), is(true)); - - dosIPFile.delete(); - - // coverage... - setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); - DenialOfServiceTaf.denyIP(ip1); - dosIPFile.delete(); - DenialOfServiceTaf.removeDenyIP(ip1); - - // coverage... - dosIPFile.delete(); - setPrivateField(DenialOfServiceTaf.class, "dosIP", null); - dost = new DenialOfServiceTaf(accessMock); - } - - @Test - public void idFileIOTest() throws CadiException, IOException { - @SuppressWarnings("unused") - DenialOfServiceTaf dost; - - dosIDFile.createNewFile(); - - // coverage... - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.removeDenyID(id1); - - dost = new DenialOfServiceTaf(accessMock); - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.denyID(id2); - // coverage... - DenialOfServiceTaf.denyID(id2); - - String contents = readContentsFromFile(dosIDFile); - assertThat(contents.contains(id1), is(true)); - assertThat(contents.contains(id2), is(true)); - - // Removing all ids should delete the file - assertThat(dosIDFile.exists(), is(true)); - DenialOfServiceTaf.removeDenyID(id1); - DenialOfServiceTaf.removeDenyID(id2); - assertThat(dosIDFile.exists(), is(false)); - - dosIDFile.createNewFile(); - - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.denyID(id2); - - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - dost = new DenialOfServiceTaf(accessMock); - - contents = readContentsFromFile(dosIDFile); - assertThat(contents.contains(id1), is(true)); - assertThat(contents.contains(id2), is(true)); - - dosIDFile.delete(); - - // coverage... - setPrivateField(DenialOfServiceTaf.class, "deniedID", null); - DenialOfServiceTaf.denyID(id1); - dosIDFile.delete(); - DenialOfServiceTaf.removeDenyID(id1); - - // coverage... - dosIDFile.delete(); - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - dost = new DenialOfServiceTaf(accessMock); - } - - private void setPrivateField(Class clazz, String fieldName, Object value) { - try { - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(null, value); - field.setAccessible(false); - } catch(Exception e) { - System.err.println("Could not set field [" + fieldName + "] to " + value); - } - } - - private String readContentsFromFile(File file) throws IOException { - BufferedReader br = new BufferedReader(new FileReader(file)); - StringBuilder sb = new StringBuilder(); - String line; - while ((line = br.readLine()) != null) { - sb.append(line); - } - br.close(); - return sb.toString(); - } + @Mock + HttpServletResponse respMock; + + @Mock + HttpServletRequest reqMock1; + + @Mock + HttpServletRequest reqMock2; + + @Mock + HttpServletRequest reqMock3; + + @Mock + Access accessMock; + + private File dosIPFile; + private File dosIDFile; + private File dosDir; + private final String dosDirName = "test"; + + private final String id1 = "id1"; + private final String id2 = "id2"; + + private final String ip1 = "111.111.111.111"; + private final String ip2 = "222.222.222.222"; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + dosDir = new File(dosDirName); + dosDir.mkdirs(); + dosIPFile = new File(dosDirName, "/dosIP"); + dosIDFile = new File(dosDirName, "/dosID"); + dosIPFile.delete(); + dosIDFile.delete(); + + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); + when(reqMock1.getRemoteAddr()).thenReturn(ip1); + when(reqMock2.getRemoteAddr()).thenReturn(ip2); + + setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); + setPrivateField(DenialOfServiceTaf.class, "deniedID", null); + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + } + + @After + public void tearDown() { + dosIPFile = new File(dosDirName, "/dosIP"); + dosIDFile = new File(dosDirName, "/dosID"); + dosIPFile.delete(); + dosIDFile.delete(); + } + + @Test + public void constructorTest() throws CadiException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + // coverage... + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(null); + dost = new DenialOfServiceTaf(accessMock); + + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); + dost = new DenialOfServiceTaf(accessMock); + + // more coverage... + dost = new DenialOfServiceTaf(accessMock); + + // more coverage... + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + } + + @Test + public void validateTest() throws CadiException { + DenialOfServiceTaf dost; + TafResp tafResp; + + dost = new DenialOfServiceTaf(accessMock); + tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); + + assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); + assertThat(tafResp.taf(), is("DenialOfServiceTaf")); + + assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); + + tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); + assertThat(tafResp.desc(), is(ip1 + " is on the IP Denial list")); + + tafResp = dost.validate(LifeForm.SBLF, reqMock2, respMock); + assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); + assertThat(tafResp.taf(), is("DenialOfServiceTaf")); + } + + @Test + public void revalidateTest() throws CadiException { + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + Resp resp = dost.revalidate(null, null); + assertThat(resp, is(Resp.NOT_MINE)); + } + + @Test + public void denyIPTest() throws CadiException { + assertThat(DenialOfServiceTaf.isDeniedIP(ip1), is(nullValue())); + assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyIP(ip2), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyIP(ip1), is(false)); // false because it's already been added + assertThat(DenialOfServiceTaf.denyIP(ip2), is(false)); // false because it's already been added + + Counter counter; + counter = DenialOfServiceTaf.isDeniedIP(ip1); + assertThat(counter.getName(), is(ip1)); + assertThat(counter.getCount(), is(0)); + assertThat(counter.getLast(), is(0L)); + assertThat(counter.toString(), is(ip1 + " is on the denied list, but has not attempted Access" )); + + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + dost.validate(LifeForm.SBLF, reqMock1, respMock); + long approxTime = System.currentTimeMillis(); + + counter = DenialOfServiceTaf.isDeniedIP(ip1); + assertThat(counter.getName(), is(ip1)); + assertThat(counter.getCount(), is(1)); + assertThat((Math.abs(approxTime - counter.getLast()) < 10), is(true)); + assertThat(counter.toString().contains(ip1), is(true)); + assertThat(counter.toString().contains(" has been denied 1 times since "), is(true)); + assertThat(counter.toString().contains(". Last denial was "), is(true)); + + // coverage... + dost.validate(LifeForm.SBLF, reqMock1, respMock); + + assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(true)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(false)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(true)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(false)); + } + + @Test + public void denyIDTest() throws CadiException { + assertThat(DenialOfServiceTaf.isDeniedID(id1), is(nullValue())); + assertThat(DenialOfServiceTaf.denyID(id1), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyID(id2), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyID(id1), is(false)); // false because it's already been added + assertThat(DenialOfServiceTaf.denyID(id2), is(false)); // false because it's already been added + + Counter counter; + counter = DenialOfServiceTaf.isDeniedID(id1); + assertThat(counter.getName(), is(id1)); + assertThat(counter.getCount(), is(0)); + assertThat(counter.getLast(), is(0L)); + + assertThat(DenialOfServiceTaf.removeDenyID(id1), is(true)); + assertThat(DenialOfServiceTaf.removeDenyID(id1), is(false)); + assertThat(DenialOfServiceTaf.removeDenyID(id2), is(true)); + assertThat(DenialOfServiceTaf.removeDenyID(id2), is(false)); + } + + @Test + public void reportTest() throws CadiException { + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + List denials = dost.report(); + assertThat(denials.size(), is(0)); + + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + + denials = dost.report(); + assertThat(denials.size(), is(4)); + for (String denied : denials) { + switch (denied.split(" ", 2)[0]) { + case ip1: + case ip2: + case id1: + case id2: + break; + default: + fail("The line: [" + denied + "] shouldn't be in the report"); + } + } + } + + @Test + public void respDenyIDTest() { + TafResp tafResp = DenialOfServiceTaf.respDenyID(accessMock, id1); + assertThat(tafResp.desc(), is(id1 + " is on the Identity Denial list")); + } + + @Test + public void ipFileIOTest() throws CadiException, IOException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + dosIPFile.createNewFile(); + + // coverage... + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.removeDenyIP(ip1); + + dost = new DenialOfServiceTaf(accessMock); + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + // coverage... + DenialOfServiceTaf.denyIP(ip2); + + String contents = readContentsFromFile(dosIPFile); + assertThat(contents.contains(ip1), is(true)); + assertThat(contents.contains(ip2), is(true)); + + // Removing all ips should delete the file + assertThat(dosIPFile.exists(), is(true)); + DenialOfServiceTaf.removeDenyIP(ip1); + DenialOfServiceTaf.removeDenyIP(ip2); + assertThat(dosIPFile.exists(), is(false)); + + dosIPFile.createNewFile(); + + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + dost = new DenialOfServiceTaf(accessMock); + + contents = readContentsFromFile(dosIPFile); + assertThat(contents.contains(ip1), is(true)); + assertThat(contents.contains(ip2), is(true)); + + dosIPFile.delete(); + + // coverage... + setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); + DenialOfServiceTaf.denyIP(ip1); + dosIPFile.delete(); + DenialOfServiceTaf.removeDenyIP(ip1); + + // coverage... + dosIPFile.delete(); + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + dost = new DenialOfServiceTaf(accessMock); + } + + @Test + public void idFileIOTest() throws CadiException, IOException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + dosIDFile.createNewFile(); + + // coverage... + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.removeDenyID(id1); + + dost = new DenialOfServiceTaf(accessMock); + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + // coverage... + DenialOfServiceTaf.denyID(id2); + + String contents = readContentsFromFile(dosIDFile); + assertThat(contents.contains(id1), is(true)); + assertThat(contents.contains(id2), is(true)); + + // Removing all ids should delete the file + assertThat(dosIDFile.exists(), is(true)); + DenialOfServiceTaf.removeDenyID(id1); + DenialOfServiceTaf.removeDenyID(id2); + assertThat(dosIDFile.exists(), is(false)); + + dosIDFile.createNewFile(); + + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + + contents = readContentsFromFile(dosIDFile); + assertThat(contents.contains(id1), is(true)); + assertThat(contents.contains(id2), is(true)); + + dosIDFile.delete(); + + // coverage... + setPrivateField(DenialOfServiceTaf.class, "deniedID", null); + DenialOfServiceTaf.denyID(id1); + dosIDFile.delete(); + DenialOfServiceTaf.removeDenyID(id1); + + // coverage... + dosIDFile.delete(); + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + } + + private void setPrivateField(Class clazz, String fieldName, Object value) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(null, value); + field.setAccessible(false); + } catch(Exception e) { + System.err.println("Could not set field [" + fieldName + "] to " + value); + } + } + + private String readContentsFromFile(File file) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(file)); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line); + } + br.close(); + return sb.toString(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java index 34b2a513..b9b7b16d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java @@ -37,21 +37,21 @@ import org.onap.aaf.cadi.taf.dos.DenialOfServiceTafResp; public class JU_DenialOfServiceTafResp { - private final static String description = "description"; - private final static RESP status = RESP.IS_AUTHENTICATED; - - private PropAccess access; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws IOException { - DenialOfServiceTafResp resp = new DenialOfServiceTafResp(access, status, description); - assertThat(resp.isAuthenticated(), is(status)); - assertThat(resp.authenticate(), is(status)); - } + private final static String description = "description"; + private final static RESP status = RESP.IS_AUTHENTICATED; + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws IOException { + DenialOfServiceTafResp resp = new DenialOfServiceTafResp(access, status, description); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.authenticate(), is(status)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java index e4469d30..bf5a15fb 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java @@ -39,52 +39,52 @@ import org.onap.aaf.cadi.taf.AbsTafResp; import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_AbsTafResp { - - private static final String JUNIT = "Junit"; - private static final String name = "name"; - private static final String tag = "tag"; - private static final String description = "description"; - - private Access access; - private TaggedPrincipal taggedPrinc; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - taggedPrinc = new TaggedPrincipal() { - @Override public String getName() { return name; } - @Override public String tag() { return tag; } - }; - } + + private static final String JUNIT = "Junit"; + private static final String name = "name"; + private static final String tag = "tag"; + private static final String description = "description"; + + private Access access; + private TaggedPrincipal taggedPrinc; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + taggedPrinc = new TaggedPrincipal() { + @Override public String getName() { return name; } + @Override public String tag() { return tag; } + }; + } - @Test - public void test() { - AbsTafResp tafResp = new AbsTafResp(access, JUNIT, taggedPrinc, description) { - @Override public RESP authenticate() throws IOException { - return null; - } - }; + @Test + public void test() { + AbsTafResp tafResp = new AbsTafResp(access, JUNIT, taggedPrinc, description) { + @Override public RESP authenticate() throws IOException { + return null; + } + }; - assertThat(tafResp.isValid(), is(true)); - assertThat(tafResp.desc(), is(description)); - assertThat(tafResp.taf(), is(JUNIT)); - assertThat(tafResp.isAuthenticated(), is(RESP.IS_AUTHENTICATED)); - assertThat(tafResp.getPrincipal(), is(taggedPrinc)); - assertThat(tafResp.getAccess(), is(access)); - assertThat(tafResp.isFailedAttempt(), is(false)); + assertThat(tafResp.isValid(), is(true)); + assertThat(tafResp.desc(), is(description)); + assertThat(tafResp.taf(), is(JUNIT)); + assertThat(tafResp.isAuthenticated(), is(RESP.IS_AUTHENTICATED)); + assertThat(tafResp.getPrincipal(), is(taggedPrinc)); + assertThat(tafResp.getAccess(), is(access)); + assertThat(tafResp.isFailedAttempt(), is(false)); - tafResp = new AbsTafResp(null, JUNIT, null, null) { - @Override public RESP authenticate() throws IOException { - return null; - } - }; + tafResp = new AbsTafResp(null, JUNIT, null, null) { + @Override public RESP authenticate() throws IOException { + return null; + } + }; - assertThat(tafResp.isValid(), is(false)); - assertThat(tafResp.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(tafResp.getPrincipal(), is(nullValue())); - assertThat(tafResp.getAccess(), is(nullValue())); - assertThat(tafResp.taf(), is(JUNIT)); - assertThat(tafResp.isFailedAttempt(), is(false)); - } + assertThat(tafResp.isValid(), is(false)); + assertThat(tafResp.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(tafResp.getPrincipal(), is(nullValue())); + assertThat(tafResp.getAccess(), is(nullValue())); + assertThat(tafResp.taf(), is(JUNIT)); + assertThat(tafResp.isFailedAttempt(), is(false)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java index f8e20cbf..cb96f87b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java @@ -40,71 +40,71 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_EpiTaf { - @Test(expected = CadiException.class) - @SuppressWarnings("unused") - public void constructorTest() throws CadiException { - EpiTaf et = new EpiTaf(); - } + @Test(expected = CadiException.class) + @SuppressWarnings("unused") + public void constructorTest() throws CadiException { + EpiTaf et = new EpiTaf(); + } - @Test - public void validateTryAnotherTest() throws CadiException { - EpiTaf et = new EpiTaf(new TryAnotherTaf()); - TafResp output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - } + @Test + public void validateTryAnotherTest() throws CadiException { + EpiTaf et = new EpiTaf(new TryAnotherTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + } - @Test - public void validateTryAuthenticatingTest() throws CadiException { - EpiTaf et = new EpiTaf(new TryAuthenticatingTaf(), new TryAuthenticatingTaf()); - TafResp output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); - output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); - } + @Test + public void validateTryAuthenticatingTest() throws CadiException { + EpiTaf et = new EpiTaf(new TryAuthenticatingTaf(), new TryAuthenticatingTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + } - @Test - public void validateDefaultCaseTest() throws CadiException { - EpiTaf et = new EpiTaf(new NullTaf()); - TafResp output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - } + @Test + public void validateDefaultCaseTest() throws CadiException { + EpiTaf et = new EpiTaf(new NullTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + } - class TryAnotherTafResp implements TafResp { - @Override public boolean isValid() { return false; } - @Override public String desc() { return null; } - @Override public RESP isAuthenticated() { return RESP.TRY_ANOTHER_TAF; } - @Override public RESP authenticate() throws IOException { return null; } - @Override public TaggedPrincipal getPrincipal() { return null; } - @Override public Access getAccess() { return null; } - @Override public boolean isFailedAttempt() { return false; } - @Override public float timing() { return 0; } - @Override public void timing(long start) {} - @Override public String taf() {return "JUnit";} - } + class TryAnotherTafResp implements TafResp { + @Override public boolean isValid() { return false; } + @Override public String desc() { return null; } + @Override public RESP isAuthenticated() { return RESP.TRY_ANOTHER_TAF; } + @Override public RESP authenticate() throws IOException { return null; } + @Override public TaggedPrincipal getPrincipal() { return null; } + @Override public Access getAccess() { return null; } + @Override public boolean isFailedAttempt() { return false; } + @Override public float timing() { return 0; } + @Override public void timing(long start) {} + @Override public String taf() {return "JUnit";} + } - class TryAnotherTaf implements Taf { - @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAnotherTafResp(); } - } + class TryAnotherTaf implements Taf { + @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAnotherTafResp(); } + } - class TryAuthenticatingResp implements TafResp { - @Override public boolean isValid() { return false; } - @Override public String desc() { return null; } - @Override public RESP isAuthenticated() { return RESP.TRY_AUTHENTICATING; } - @Override public RESP authenticate() throws IOException { return null; } - @Override public TaggedPrincipal getPrincipal() { return null; } - @Override public Access getAccess() { return null; } - @Override public boolean isFailedAttempt() { return false; } - @Override public float timing() { return 0; } - @Override public void timing(long start) {} - @Override public String taf() {return "JUnit";} - } + class TryAuthenticatingResp implements TafResp { + @Override public boolean isValid() { return false; } + @Override public String desc() { return null; } + @Override public RESP isAuthenticated() { return RESP.TRY_AUTHENTICATING; } + @Override public RESP authenticate() throws IOException { return null; } + @Override public TaggedPrincipal getPrincipal() { return null; } + @Override public Access getAccess() { return null; } + @Override public boolean isFailedAttempt() { return false; } + @Override public float timing() { return 0; } + @Override public void timing(long start) {} + @Override public String taf() {return "JUnit";} + } - class TryAuthenticatingTaf implements Taf { - @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAuthenticatingResp(); } - } + class TryAuthenticatingTaf implements Taf { + @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAuthenticatingResp(); } + } - class EpiTafStub extends EpiTaf { - public EpiTafStub() throws CadiException { } - } + class EpiTafStub extends EpiTaf { + public EpiTafStub() throws CadiException { } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java index 93a20474..6952a042 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java @@ -54,92 +54,92 @@ import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_HttpEpiTaf { - private PropAccess access; - - @Mock private Locator locMock; - @Mock private TrustChecker trustCheckerMock; - @Mock private HttpServletRequest reqMock; - @Mock private HttpServletResponse respMock; - @Mock private HttpTaf tafMock; - @Mock private TafResp trespMock; - @Mock private Redirectable redirMock; - - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws Exception { - HttpEpiTaf taf; - try { - taf = new HttpEpiTaf(access, locMock, trustCheckerMock); - fail("Should've thrown an exception"); - } catch (CadiException e) { - assertThat(e.getMessage(), is("Need at least one HttpTaf implementation in constructor")); - } - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, new NullTaf()); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - // Coverage of tricorderScan - taf.validate(LifeForm.LFN, reqMock, respMock); - when(reqMock.getHeader("User-Agent")).thenReturn("Non-mozilla-header"); - taf.validate(LifeForm.LFN, reqMock, respMock); - when(reqMock.getHeader("User-Agent")).thenReturn("Mozilla-header"); - taf.validate(LifeForm.LFN, reqMock, respMock); - - access.setLogLevel(Level.DEBUG); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(trespMock); - when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_ANOTHER_TAF); - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(trespMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(redirMock); - when(redirMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, null, tafMock); - when(redirMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); - try { - taf.validate(LifeForm.CBLF, reqMock, respMock); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - - assertThat(taf.revalidate(null), is(false)); - assertThat(taf.revalidate(null), is(false)); - - when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE); - assertThat(taf.revalidate(null, null), is(Resp.NOT_MINE)); - when(tafMock.revalidate(null, null)).thenReturn(Resp.REVALIDATED); - assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); - - when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE).thenReturn(Resp.NOT_MINE).thenReturn(Resp.REVALIDATED); - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock, tafMock); - assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); - - taf.toString(); - - } + private PropAccess access; + + @Mock private Locator locMock; + @Mock private TrustChecker trustCheckerMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private HttpTaf tafMock; + @Mock private TafResp trespMock; + @Mock private Redirectable redirMock; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws Exception { + HttpEpiTaf taf; + try { + taf = new HttpEpiTaf(access, locMock, trustCheckerMock); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Need at least one HttpTaf implementation in constructor")); + } + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, new NullTaf()); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + // Coverage of tricorderScan + taf.validate(LifeForm.LFN, reqMock, respMock); + when(reqMock.getHeader("User-Agent")).thenReturn("Non-mozilla-header"); + taf.validate(LifeForm.LFN, reqMock, respMock); + when(reqMock.getHeader("User-Agent")).thenReturn("Mozilla-header"); + taf.validate(LifeForm.LFN, reqMock, respMock); + + access.setLogLevel(Level.DEBUG); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(trespMock); + when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_ANOTHER_TAF); + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(trespMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(redirMock); + when(redirMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, null, tafMock); + when(redirMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); + try { + taf.validate(LifeForm.CBLF, reqMock, respMock); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + assertThat(taf.revalidate(null), is(false)); + assertThat(taf.revalidate(null), is(false)); + + when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE); + assertThat(taf.revalidate(null, null), is(Resp.NOT_MINE)); + when(tafMock.revalidate(null, null)).thenReturn(Resp.REVALIDATED); + assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); + + when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE).thenReturn(Resp.NOT_MINE).thenReturn(Resp.REVALIDATED); + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock, tafMock); + assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); + + taf.toString(); + + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java index 3124bbd4..05944e5c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java @@ -52,50 +52,50 @@ import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_LoginPageTafResp { - private static final String uriString = "example.com"; + private static final String uriString = "example.com"; - private URI uri; - private Access access; - private List redirectables; + private URI uri; + private Access access; + private List redirectables; - @Mock private HttpServletResponse respMock; - @Mock private Locator locatorMock; - @Mock private Redirectable redirMock; + @Mock private HttpServletResponse respMock; + @Mock private Locator locatorMock; + @Mock private Redirectable redirMock; - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - redirectables = new ArrayList<>(); - uri = new URI(uriString); - } + redirectables = new ArrayList<>(); + uri = new URI(uriString); + } - @Test - public void test() throws LocatorException, IOException { - TafResp resp; - resp = LoginPageTafResp.create(access, null, respMock, redirectables); - assertThat(resp.desc(), is("All Authentication denied")); + @Test + public void test() throws LocatorException, IOException { + TafResp resp; + resp = LoginPageTafResp.create(access, null, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); - redirectables.add(redirMock); - redirectables.add(redirMock); - resp = LoginPageTafResp.create(access, null, respMock, redirectables); - assertThat((Redirectable)resp, is(redirMock)); + redirectables.add(redirMock); + redirectables.add(redirMock); + resp = LoginPageTafResp.create(access, null, respMock, redirectables); + assertThat((Redirectable)resp, is(redirMock)); - resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); - assertThat(resp.desc(), is("All Authentication denied")); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); - when(locatorMock.get((Item)any())).thenReturn(uri); - resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); - assertThat(resp.desc(), is("Multiple Possible HTTP Logins available. Redirecting to Login Choice Page")); - assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); - assertThat(resp.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + when(locatorMock.get((Item)any())).thenReturn(uri); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("Multiple Possible HTTP Logins available. Redirecting to Login Choice Page")); + assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + assertThat(resp.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); - redirectables = new ArrayList<>(); - resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); - assertThat(resp.desc(), is("All Authentication denied")); + redirectables = new ArrayList<>(); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); - } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java index f42184df..83bc8167 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java @@ -36,30 +36,30 @@ import org.onap.aaf.cadi.taf.NullTaf; public class JU_NullTaf { - @Test - public void test() throws IOException { - NullTaf nt = new NullTaf(); - TafResp singleton1 = nt.validate(null); - TafResp singleton2 = nt.validate(null, null, null); - Resp singleton3 = nt.revalidate(null, null); - - assertThat(singleton1, is(singleton2)); - - assertFalse(singleton1.isValid()); - - assertThat(singleton1.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - - assertThat(singleton1.desc(), is("All Authentication denied")); - - assertThat(singleton1.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); - - assertThat(singleton1.getPrincipal(), is(nullValue())); - - assertThat(singleton1.getAccess(), is(Access.NULL)); - - assertTrue(singleton1.isFailedAttempt()); + @Test + public void test() throws IOException { + NullTaf nt = new NullTaf(); + TafResp singleton1 = nt.validate(null); + TafResp singleton2 = nt.validate(null, null, null); + Resp singleton3 = nt.revalidate(null, null); + + assertThat(singleton1, is(singleton2)); + + assertFalse(singleton1.isValid()); + + assertThat(singleton1.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + + assertThat(singleton1.desc(), is("All Authentication denied")); + + assertThat(singleton1.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); + + assertThat(singleton1.getPrincipal(), is(nullValue())); + + assertThat(singleton1.getAccess(), is(Access.NULL)); + + assertTrue(singleton1.isFailedAttempt()); - assertThat(singleton3, is(Resp.NOT_MINE)); - } + assertThat(singleton3, is(Resp.NOT_MINE)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java index aacce522..a6b3bd2a 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java @@ -35,21 +35,21 @@ import org.onap.aaf.cadi.taf.PuntTafResp; public class JU_PuntTafResp { - @Test - public void test() throws IOException { - String name = "name"; - String explanation = "example explanation"; - - PuntTafResp punt = new PuntTafResp(name, explanation); - - assertFalse(punt.isValid()); - assertThat(punt.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(punt.desc(), is("Not processing this transaction: " + explanation)); - assertThat(punt.taf(), is(name)); - assertThat(punt.authenticate(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(punt.getPrincipal(), is(nullValue())); - assertThat(punt.getAccess(), is(Access.NULL)); - assertFalse(punt.isFailedAttempt()); - } + @Test + public void test() throws IOException { + String name = "name"; + String explanation = "example explanation"; + + PuntTafResp punt = new PuntTafResp(name, explanation); + + assertFalse(punt.isValid()); + assertThat(punt.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(punt.desc(), is("Not processing this transaction: " + explanation)); + assertThat(punt.taf(), is(name)); + assertThat(punt.authenticate(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(punt.getPrincipal(), is(nullValue())); + assertThat(punt.getAccess(), is(Access.NULL)); + assertFalse(punt.isFailedAttempt()); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java index b032c020..9945bfbe 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java @@ -37,36 +37,36 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_TrustNotTafResp { - @Mock - TafResp delegateMock; + @Mock + TafResp delegateMock; - @Mock - TaggedPrincipal principalMock; + @Mock + TaggedPrincipal principalMock; - @Mock - Access accessMock; + @Mock + Access accessMock; - private final String description = "Example Description"; + private final String description = "Example Description"; - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); - when(delegateMock.getPrincipal()).thenReturn(principalMock); - when(delegateMock.getAccess()).thenReturn(accessMock); - } + when(delegateMock.getPrincipal()).thenReturn(principalMock); + when(delegateMock.getAccess()).thenReturn(accessMock); + } - @Test - public void test() throws IOException { - TrustNotTafResp ttr = new TrustNotTafResp(delegateMock, description); - assertThat(ttr.isValid(), is(false)); - assertThat(ttr.desc(), is(description)); - assertThat(ttr.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); - assertThat(ttr.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - assertThat(ttr.getPrincipal(), is(principalMock)); - assertThat(ttr.getAccess(), is(accessMock)); - assertThat(ttr.isFailedAttempt(), is(true)); - assertThat(ttr.toString(), is(description)); - } + @Test + public void test() throws IOException { + TrustNotTafResp ttr = new TrustNotTafResp(delegateMock, description); + assertThat(ttr.isValid(), is(false)); + assertThat(ttr.desc(), is(description)); + assertThat(ttr.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); + assertThat(ttr.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + assertThat(ttr.getPrincipal(), is(principalMock)); + assertThat(ttr.getAccess(), is(accessMock)); + assertThat(ttr.isFailedAttempt(), is(true)); + assertThat(ttr.toString(), is(description)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java index 10b5f146..5fa1a4d9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java @@ -37,46 +37,46 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_TrustTafResp { - @Mock - TafResp delegateMock; + @Mock + TafResp delegateMock; - @Mock - TaggedPrincipal principalMock; + @Mock + TaggedPrincipal principalMock; - @Mock - Access accessMock; + @Mock + Access accessMock; - private final String description = "Example Description"; - private final String anotherDescription = "Another Description"; - private final String name = "name"; + private final String description = "Example Description"; + private final String anotherDescription = "Another Description"; + private final String name = "name"; - private final RESP resp = RESP.IS_AUTHENTICATED; + private final RESP resp = RESP.IS_AUTHENTICATED; - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); - when(delegateMock.desc()).thenReturn(anotherDescription); - when(delegateMock.isValid()).thenReturn(true); - when(delegateMock.isAuthenticated()).thenReturn(resp); - when(delegateMock.authenticate()).thenReturn(resp); - when(delegateMock.getAccess()).thenReturn(accessMock); - when(delegateMock.isFailedAttempt()).thenReturn(true); + when(delegateMock.desc()).thenReturn(anotherDescription); + when(delegateMock.isValid()).thenReturn(true); + when(delegateMock.isAuthenticated()).thenReturn(resp); + when(delegateMock.authenticate()).thenReturn(resp); + when(delegateMock.getAccess()).thenReturn(accessMock); + when(delegateMock.isFailedAttempt()).thenReturn(true); - when(principalMock.getName()).thenReturn(name); - } + when(principalMock.getName()).thenReturn(name); + } - @Test - public void test() throws IOException { - TrustTafResp ttr = new TrustTafResp(delegateMock, principalMock, description); - assertThat(ttr.isValid(), is(true)); - assertThat(ttr.desc(), is(description + ' ' + anotherDescription)); - assertThat(ttr.authenticate(), is(resp)); - assertThat(ttr.isAuthenticated(), is(resp)); - assertThat(ttr.getPrincipal(), is(principalMock)); - assertThat(ttr.getAccess(), is(accessMock)); - assertThat(ttr.isFailedAttempt(), is(true)); - assertThat(ttr.toString(), is(name + " by trust of " + description + ' ' + anotherDescription)); - } + @Test + public void test() throws IOException { + TrustTafResp ttr = new TrustTafResp(delegateMock, principalMock, description); + assertThat(ttr.isValid(), is(true)); + assertThat(ttr.desc(), is(description + ' ' + anotherDescription)); + assertThat(ttr.authenticate(), is(resp)); + assertThat(ttr.isAuthenticated(), is(resp)); + assertThat(ttr.getPrincipal(), is(principalMock)); + assertThat(ttr.getAccess(), is(accessMock)); + assertThat(ttr.isFailedAttempt(), is(true)); + assertThat(ttr.toString(), is(name + " by trust of " + description + ' ' + anotherDescription)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java index d78706dc..67dcb397 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java @@ -46,149 +46,149 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.Symm; public class JU_AES { - private AES aes; - private ByteArrayInputStream baisEncrypt; - private ByteArrayInputStream baisDecrypt; - private ByteArrayOutputStream baosEncrypt; - private ByteArrayOutputStream baosDecrypt; - - private ByteArrayOutputStream errStream; - - @Before - public void setup() throws Exception { - byte[] keyBytes = new byte[AES.AES_KEY_SIZE/8]; - char[] codeset = Symm.base64.codeset; - int offset = (Math.abs(codeset[0]) + 47) % (codeset.length - keyBytes.length); - for(int i = 0; i < keyBytes.length; ++i) { - keyBytes[i] = (byte)codeset[i+offset]; - } - aes = new AES(keyBytes, 0, keyBytes.length); - - errStream = new ByteArrayOutputStream(); - System.setErr(new PrintStream(errStream)); - } - - @After - public void tearDown() { - System.setErr(System.err); - } - - @Test - public void newKeyTest() throws Exception { - SecretKey secretKey = AES.newKey(); - assertThat(secretKey.getAlgorithm(), is(AES.class.getSimpleName())); - } - - @Test - public void encryptDecrpytFromBytes() throws Exception { - String orig = "I'm a password, really"; - byte[] encrypted = aes.encrypt(orig.getBytes()); - byte[] decrypted = aes.decrypt(encrypted); - assertThat(new String(decrypted), is(orig)); + private AES aes; + private ByteArrayInputStream baisEncrypt; + private ByteArrayInputStream baisDecrypt; + private ByteArrayOutputStream baosEncrypt; + private ByteArrayOutputStream baosDecrypt; + + private ByteArrayOutputStream errStream; + + @Before + public void setup() throws Exception { + byte[] keyBytes = new byte[AES.AES_KEY_SIZE/8]; + char[] codeset = Symm.base64.codeset; + int offset = (Math.abs(codeset[0]) + 47) % (codeset.length - keyBytes.length); + for(int i = 0; i < keyBytes.length; ++i) { + keyBytes[i] = (byte)codeset[i+offset]; + } + aes = new AES(keyBytes, 0, keyBytes.length); + + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } + + @Test + public void newKeyTest() throws Exception { + SecretKey secretKey = AES.newKey(); + assertThat(secretKey.getAlgorithm(), is(AES.class.getSimpleName())); + } + + @Test + public void encryptDecrpytFromBytes() throws Exception { + String orig = "I'm a password, really"; + byte[] encrypted = aes.encrypt(orig.getBytes()); + byte[] decrypted = aes.decrypt(encrypted); + assertThat(new String(decrypted), is(orig)); - Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); - aeskeySpec_field.setAccessible(true); - aeskeySpec_field.set(aes, null); - - try { - aes.encrypt(orig.getBytes()); - fail("Should have thrown an exception"); - } catch (CadiException e) { - } - try { - aes.decrypt(encrypted); - fail("Should have thrown an exception"); - } catch (CadiException e) { - } - } - - @Test - public void saveToFileTest() throws Exception { - String filePath = "src/test/resources/output_key"; - File keyfile = new File(filePath); - aes.save(keyfile); - assertTrue(Files.isReadable(Paths.get(filePath))); - assertFalse(Files.isWritable(Paths.get(filePath))); - assertFalse(Files.isExecutable(Paths.get(filePath))); - keyfile.delete(); - } - - @Test - public void encryptDecryptFromInputStream() throws Exception { - String orig = "I'm a password, really"; - byte[] b64encrypted; - String output; - - CipherInputStream cisEncrypt; - CipherInputStream cisDecrypt; - - // Test CipherInputStream - baisEncrypt = new ByteArrayInputStream(orig.getBytes()); - cisEncrypt = aes.inputStream(baisEncrypt, true); - baosEncrypt = new ByteArrayOutputStream(); - transferFromInputStreamToOutputStream(cisEncrypt, baosEncrypt); - cisEncrypt.close(); - - b64encrypted = baosEncrypt.toByteArray(); - - baisDecrypt = new ByteArrayInputStream(b64encrypted); - cisDecrypt = aes.inputStream(baisDecrypt, false); - baosDecrypt = new ByteArrayOutputStream(); - transferFromInputStreamToOutputStream(cisDecrypt, baosDecrypt); - cisDecrypt.close(); - - output = new String(baosDecrypt.toByteArray()); - assertThat(output, is(orig)); - - Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); - aeskeySpec_field.setAccessible(true); - aeskeySpec_field.set(aes, null); - - assertNull(aes.inputStream(baisEncrypt, true)); - assertThat(errStream.toString(), is("Error creating Aes CipherInputStream\n")); - } - - @Test - public void encryptDecryptFromOutputStream() throws Exception { - String orig = "I'm a password, really"; - byte[] b64encrypted; - String output; - - CipherOutputStream cosEncrypt; - CipherOutputStream cosDecrypt; - - // Test CipherOutputStream - baisEncrypt = new ByteArrayInputStream(orig.getBytes()); - baosEncrypt = new ByteArrayOutputStream(); - cosEncrypt = aes.outputStream(baosEncrypt, true); - transferFromInputStreamToOutputStream(baisEncrypt, cosEncrypt); - cosEncrypt.close(); - - b64encrypted = baosEncrypt.toByteArray(); - - baosDecrypt = new ByteArrayOutputStream(); - cosDecrypt = aes.outputStream(baosDecrypt, false); - baisDecrypt = new ByteArrayInputStream(b64encrypted); - transferFromInputStreamToOutputStream(baisDecrypt, cosDecrypt); - cosDecrypt.close(); - - output = new String(baosDecrypt.toByteArray()); - assertThat(output, is(orig)); - - Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); - aeskeySpec_field.setAccessible(true); - aeskeySpec_field.set(aes, null); - - assertNull(aes.outputStream(baosEncrypt, true)); - assertThat(errStream.toString(), is("Error creating Aes CipherOutputStream\n")); - } - - public void transferFromInputStreamToOutputStream(InputStream is, OutputStream os) throws IOException { - byte[] buffer = new byte[200]; - int len; - while ((len = is.read(buffer)) != -1) { - os.write(buffer, 0, len); - } - } - + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + try { + aes.encrypt(orig.getBytes()); + fail("Should have thrown an exception"); + } catch (CadiException e) { + } + try { + aes.decrypt(encrypted); + fail("Should have thrown an exception"); + } catch (CadiException e) { + } + } + + @Test + public void saveToFileTest() throws Exception { + String filePath = "src/test/resources/output_key"; + File keyfile = new File(filePath); + aes.save(keyfile); + assertTrue(Files.isReadable(Paths.get(filePath))); + assertFalse(Files.isWritable(Paths.get(filePath))); + assertFalse(Files.isExecutable(Paths.get(filePath))); + keyfile.delete(); + } + + @Test + public void encryptDecryptFromInputStream() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + CipherInputStream cisEncrypt; + CipherInputStream cisDecrypt; + + // Test CipherInputStream + baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + cisEncrypt = aes.inputStream(baisEncrypt, true); + baosEncrypt = new ByteArrayOutputStream(); + transferFromInputStreamToOutputStream(cisEncrypt, baosEncrypt); + cisEncrypt.close(); + + b64encrypted = baosEncrypt.toByteArray(); + + baisDecrypt = new ByteArrayInputStream(b64encrypted); + cisDecrypt = aes.inputStream(baisDecrypt, false); + baosDecrypt = new ByteArrayOutputStream(); + transferFromInputStreamToOutputStream(cisDecrypt, baosDecrypt); + cisDecrypt.close(); + + output = new String(baosDecrypt.toByteArray()); + assertThat(output, is(orig)); + + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + assertNull(aes.inputStream(baisEncrypt, true)); + assertThat(errStream.toString(), is("Error creating Aes CipherInputStream\n")); + } + + @Test + public void encryptDecryptFromOutputStream() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + CipherOutputStream cosEncrypt; + CipherOutputStream cosDecrypt; + + // Test CipherOutputStream + baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + baosEncrypt = new ByteArrayOutputStream(); + cosEncrypt = aes.outputStream(baosEncrypt, true); + transferFromInputStreamToOutputStream(baisEncrypt, cosEncrypt); + cosEncrypt.close(); + + b64encrypted = baosEncrypt.toByteArray(); + + baosDecrypt = new ByteArrayOutputStream(); + cosDecrypt = aes.outputStream(baosDecrypt, false); + baisDecrypt = new ByteArrayInputStream(b64encrypted); + transferFromInputStreamToOutputStream(baisDecrypt, cosDecrypt); + cosDecrypt.close(); + + output = new String(baosDecrypt.toByteArray()); + assertThat(output, is(orig)); + + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + assertNull(aes.outputStream(baosEncrypt, true)); + assertThat(errStream.toString(), is("Error creating Aes CipherOutputStream\n")); + } + + public void transferFromInputStreamToOutputStream(InputStream is, OutputStream os) throws IOException { + byte[] buffer = new byte[200]; + int len; + while ((len = is.read(buffer)) != -1) { + os.write(buffer, 0, len); + } + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java index b34e90ab..8305be83 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java @@ -56,310 +56,310 @@ import org.onap.aaf.cadi.principal.CachedBasicPrincipal; public class JU_AbsUserCache { - @Mock private CachingLur cl; - @Mock private Principal principal; - @Mock private CachedBasicPrincipal cbp; - @Mock private LocalPermission permission1; - @Mock private LocalPermission permission2; - - private Access access; - - private ByteArrayOutputStream outStream; - - private String name1 = "name1"; - private String name2 = "name2"; - private byte[] password = "password".getBytes(); - - private static Field timerField; - - @BeforeClass - public static void setupOnce() throws Exception { - timerField = AbsUserCache.class.getDeclaredField("timer"); - timerField.setAccessible(true); - } - - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); - - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - - // This must happen after changing System.out - access = new PropAccess(); - - when(permission1.getKey()).thenReturn("NewKey1"); - when(permission2.getKey()).thenReturn("NewKey2"); - - timerField.set(null, null); - } - - @After - public void tearDown() throws Exception { - System.setOut(System.out); - timerField.set(null, null); - } - - @SuppressWarnings("unused") - @Test - public void constructorTest() { - int cleanInterval = 65000; - int maxInterval = 70000; - - AbsUserCacheStub aucs1 = new AbsUserCacheStub(access, cleanInterval, maxInterval, Integer.MAX_VALUE); - String output = outStream.toString().split(" ", 2)[1]; - StringBuilder expected = new StringBuilder(); - expected.append("INIT [cadi] Cleaning Thread initialized with interval of "); - expected.append(String.valueOf(cleanInterval)); - expected.append(" ms and max objects of "); - expected.append(String.valueOf(maxInterval)); - expected.append(System.lineSeparator()); - assertThat(output, is(expected.toString())); - - outStream.reset(); - AbsUserCacheStub aucs2 = new AbsUserCacheStub(access, cleanInterval, maxInterval, Integer.MAX_VALUE); - output = outStream.toString().split(" ", 2)[1]; - expected = new StringBuilder(); - expected.append("INIT [cadi] Cleaning Thread initialized with interval of "); - expected.append(String.valueOf(cleanInterval)); - expected.append(" ms and max objects of "); - expected.append(String.valueOf(maxInterval)); - expected.append(System.lineSeparator()); - assertThat(output, is(expected.toString())); - - AbsUserCacheStub aucs3 = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - AbsUserCacheStub aucs4 = new AbsUserCacheStub(aucs1); - - // For coverage - AbsUserCacheCLStub auccls1 = new AbsUserCacheCLStub(aucs1); - aucs1.setLur(cl); - auccls1 = new AbsUserCacheCLStub(aucs1); - AbsUserCacheCLStub auccls2 = new AbsUserCacheCLStub(aucs3); - } - - @Test - public void setLurTest() { - AbsUserCacheStub aucs1 = new AbsUserCacheStub(access, 65000, 70000, Integer.MAX_VALUE); - AbsUserCacheStub aucs2 = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - aucs1.setLur(cl); - aucs2.setLur(cl); - } - - @Test - public void addUserGetUserTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - User user; - - // Test adding a user with a principal (non-GetCred). user does not have a cred - // Then test getting that user - when(principal.getName()).thenReturn(name1); - user = new User(principal, 0); - aucs.addUser(user); - assertThat(aucs.getUser(principal), is(user)); - - // Test adding a user with a principal (GetCred). user does not have a cred - // Then test getting that user - GetCredStub gc = new GetCredStub(); - user = new User(gc, 0); - aucs.addUser(user); - assertThat(aucs.getUser(gc), is(user)); - - // Test adding a user with no principal - // Then test getting that user via his name and cred - user = new User(name2, password); - aucs.addUser(user); - assertThat(aucs.getUser(name2, password), is(user)); - - // Test getting a user by a CachedBasicPrincipal - when(cbp.getName()).thenReturn(name2); - when(cbp.getCred()).thenReturn(password); - assertThat(aucs.getUser(cbp), is(user)); - - // Force the user to expire, then test that he is no longer in the cache - Field permExpiresField = User.class.getDeclaredField("permExpires"); - permExpiresField.setAccessible(true); - permExpiresField.set(user, 0); - assertThat(aucs.getUser(name2, password), is(nullValue())); - - // Test adding a user with a custom key - // Then test gettin that user - user = new User(principal, 0); - String key = principal.getName() + "NoCred"; - aucs.addUser(key, user); - assertThat(aucs.getUser(principal), is(user)); - - // Test that getUser returns null for principals that don't match any users - when(principal.getName()).thenReturn("not in the cache"); - assertThat(aucs.getUser(principal), is(nullValue())); - - // That that getUser returns null for name/creds that are not in the cache - assertThat(aucs.getUser("not a real user", "not in the cache".getBytes()), is(nullValue())); - } - - @Test - public void removeTest() { - AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - User user; - - when(principal.getName()).thenReturn(name1); - user = new User(principal); - // Add a user with a principal - aucs.addUser(user); - // Check that the user is in the cache - assertThat(aucs.getUser(principal), is(user)); - // Remove the user - when(principal.getName()).thenReturn(name1 + "NoCred"); - aucs.remove(user); - // Check that the user is no longer in the cache - when(principal.getName()).thenReturn(name1); - assertThat(aucs.getUser(principal), is(nullValue())); - - // Add the user again - aucs.addUser(user); - // Check that the user is in the cache - assertThat(aucs.getUser(principal), is(user)); - // Remove the user by name - aucs.remove(name1 + "NoCred"); - // Check that the user is no longer in the cache - assertThat(aucs.getUser(principal), is(nullValue())); - - // Coverage test - attempt to remove a user that is not in the cache - aucs.remove(name1 + "NoCred"); - assertThat(aucs.getUser(principal), is(nullValue())); - } - - @Test - public void clearAllTest() { - AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - User user1; - User user2; - - // Add some users to the cache - when(principal.getName()).thenReturn(name1); - user1 = new User(principal); - when(principal.getName()).thenReturn(name2); - user2 = new User(principal); - aucs.addUser(user1); - aucs.addUser(user2); - - // Check that the users are in the cache - when(principal.getName()).thenReturn(name1); - assertThat(aucs.getUser(principal), is(user1)); - when(principal.getName()).thenReturn(name2); - assertThat(aucs.getUser(principal), is(user2)); - - // Clear the cache - aucs.clearAll(); - - // Check that the users are no longer in the cache - when(principal.getName()).thenReturn(name1); - assertThat(aucs.getUser(principal), is(nullValue())); - when(principal.getName()).thenReturn(name2); - assertThat(aucs.getUser(principal), is(nullValue())); - } - - @Test - public void dumpInfoTest() { - AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - User user1; - User user2; - - Principal principal1 = mock(Principal.class); - Principal principal2 = mock(Principal.class); - when(principal1.getName()).thenReturn(name1); - when(principal2.getName()).thenReturn(name2); - - // Add some users with permissions to the cache - user1 = new User(principal1); - user1.add(permission1); - user1.add(permission2); - user2 = new User(principal2); - user2.add(permission1); - user2.add(permission2); - aucs.addUser(user1); - aucs.addUser(user2); - - // Dump the info - List.DumpInfo> dumpInfo = aucs.dumpInfo(); - assertThat(dumpInfo.size(), is(2)); - - // Utility lists - List names = new ArrayList<>(); - names.add(name1); - names.add(name2); - List permissions = new ArrayList<>(); - permissions.add("NewKey1"); - permissions.add("NewKey2"); - - // We need to use "contains" because the dumpInfo was created from a list, so we don't know it's order - for (AbsUserCache.DumpInfo di : dumpInfo) { - assertTrue(names.contains(di.user)); - for (String perm : di.perms) { - assertTrue(permissions.contains(perm)); - } - } - } - - @Test - public void handlesExclusivelyTest() { - AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - assertFalse(aucs.handlesExclusively(permission1)); - assertFalse(aucs.handlesExclusively(permission2)); - } - - @Test - public void destroyTest() { - AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - aucs.destroy(); - aucs = new AbsUserCacheStub(access, 1, 1, Integer.MAX_VALUE); - aucs.destroy(); - } - - @Test - public void missTest() throws IOException { - AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); - // Add the Miss to the missmap - assertTrue(aucs.addMiss("key", password)); // This one actually adds it - assertTrue(aucs.addMiss("key", password)); // this one doesn't really do anything - assertTrue(aucs.addMiss("key", password)); // neither does this one - assertFalse(aucs.addMiss("key", password)); // By this time, the missMap is tired of this nonsense, and retaliates - assertFalse(aucs.addMiss("key", password)); // Oh yea. He's angry - - // Can't really test this due to visibility - aucs.missed("key", password); - - // Coverage - AbsUserCacheStub aucs1 = new AbsUserCacheStub(access, 1, 1, Integer.MAX_VALUE); - aucs1.addMiss("key", password); - } - - class AbsUserCacheStub extends AbsUserCache { - public AbsUserCacheStub(Access access, long cleanInterval, int highCount, int usageCount) { super(access, cleanInterval, highCount, usageCount); } - public AbsUserCacheStub(AbsUserCache cache) { super(cache); } - @Override public void setLur(CachingLur lur) { super.setLur(lur); } - @Override public void addUser(User user) { super.addUser(user); } - @Override public void addUser(String key, User user) { super.addUser(key, user); } - @Override public User getUser(Principal p) { return super.getUser(p); } - @Override public User getUser(CachedBasicPrincipal p) { return super.getUser(p); } - @Override public User getUser(String user, byte[] cred) { return super.getUser(user, cred); } - @Override public void remove(User user) { super.remove(user); } - @Override public boolean addMiss(String key, byte[] bs) { return super.addMiss(key, bs); } - @Override public Miss missed(String key, byte[] bs) throws IOException { return super.missed(key, bs); } - } - - class AbsUserCacheCLStub extends AbsUserCache implements CachingLur { - public AbsUserCacheCLStub(AbsUserCache cache) { super(cache); } - @Override public Permission createPerm(String p) { return null; } - @Override public boolean fish(Principal bait, Permission ... pond) { return false; } - @Override public void fishAll(Principal bait, List permissions) { } - @Override public boolean handles(Principal principal) { return false; } - @Override public Resp reload(User user) { return null; } - @Override public void setDebug(String commaDelimIDsOrNull) { } - } - - class GetCredStub implements Principal, GetCred { - @Override public byte[] getCred() { return password; } - @Override public String getName() { return name1; } - } + @Mock private CachingLur cl; + @Mock private Principal principal; + @Mock private CachedBasicPrincipal cbp; + @Mock private LocalPermission permission1; + @Mock private LocalPermission permission2; + + private Access access; + + private ByteArrayOutputStream outStream; + + private String name1 = "name1"; + private String name2 = "name2"; + private byte[] password = "password".getBytes(); + + private static Field timerField; + + @BeforeClass + public static void setupOnce() throws Exception { + timerField = AbsUserCache.class.getDeclaredField("timer"); + timerField.setAccessible(true); + } + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + + // This must happen after changing System.out + access = new PropAccess(); + + when(permission1.getKey()).thenReturn("NewKey1"); + when(permission2.getKey()).thenReturn("NewKey2"); + + timerField.set(null, null); + } + + @After + public void tearDown() throws Exception { + System.setOut(System.out); + timerField.set(null, null); + } + + @SuppressWarnings("unused") + @Test + public void constructorTest() { + int cleanInterval = 65000; + int maxInterval = 70000; + + AbsUserCacheStub aucs1 = new AbsUserCacheStub(access, cleanInterval, maxInterval, Integer.MAX_VALUE); + String output = outStream.toString().split(" ", 2)[1]; + StringBuilder expected = new StringBuilder(); + expected.append("INIT [cadi] Cleaning Thread initialized with interval of "); + expected.append(String.valueOf(cleanInterval)); + expected.append(" ms and max objects of "); + expected.append(String.valueOf(maxInterval)); + expected.append(System.lineSeparator()); + assertThat(output, is(expected.toString())); + + outStream.reset(); + AbsUserCacheStub aucs2 = new AbsUserCacheStub(access, cleanInterval, maxInterval, Integer.MAX_VALUE); + output = outStream.toString().split(" ", 2)[1]; + expected = new StringBuilder(); + expected.append("INIT [cadi] Cleaning Thread initialized with interval of "); + expected.append(String.valueOf(cleanInterval)); + expected.append(" ms and max objects of "); + expected.append(String.valueOf(maxInterval)); + expected.append(System.lineSeparator()); + assertThat(output, is(expected.toString())); + + AbsUserCacheStub aucs3 = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + AbsUserCacheStub aucs4 = new AbsUserCacheStub(aucs1); + + // For coverage + AbsUserCacheCLStub auccls1 = new AbsUserCacheCLStub(aucs1); + aucs1.setLur(cl); + auccls1 = new AbsUserCacheCLStub(aucs1); + AbsUserCacheCLStub auccls2 = new AbsUserCacheCLStub(aucs3); + } + + @Test + public void setLurTest() { + AbsUserCacheStub aucs1 = new AbsUserCacheStub(access, 65000, 70000, Integer.MAX_VALUE); + AbsUserCacheStub aucs2 = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + aucs1.setLur(cl); + aucs2.setLur(cl); + } + + @Test + public void addUserGetUserTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + User user; + + // Test adding a user with a principal (non-GetCred). user does not have a cred + // Then test getting that user + when(principal.getName()).thenReturn(name1); + user = new User(principal, 0); + aucs.addUser(user); + assertThat(aucs.getUser(principal), is(user)); + + // Test adding a user with a principal (GetCred). user does not have a cred + // Then test getting that user + GetCredStub gc = new GetCredStub(); + user = new User(gc, 0); + aucs.addUser(user); + assertThat(aucs.getUser(gc), is(user)); + + // Test adding a user with no principal + // Then test getting that user via his name and cred + user = new User(name2, password); + aucs.addUser(user); + assertThat(aucs.getUser(name2, password), is(user)); + + // Test getting a user by a CachedBasicPrincipal + when(cbp.getName()).thenReturn(name2); + when(cbp.getCred()).thenReturn(password); + assertThat(aucs.getUser(cbp), is(user)); + + // Force the user to expire, then test that he is no longer in the cache + Field permExpiresField = User.class.getDeclaredField("permExpires"); + permExpiresField.setAccessible(true); + permExpiresField.set(user, 0); + assertThat(aucs.getUser(name2, password), is(nullValue())); + + // Test adding a user with a custom key + // Then test gettin that user + user = new User(principal, 0); + String key = principal.getName() + "NoCred"; + aucs.addUser(key, user); + assertThat(aucs.getUser(principal), is(user)); + + // Test that getUser returns null for principals that don't match any users + when(principal.getName()).thenReturn("not in the cache"); + assertThat(aucs.getUser(principal), is(nullValue())); + + // That that getUser returns null for name/creds that are not in the cache + assertThat(aucs.getUser("not a real user", "not in the cache".getBytes()), is(nullValue())); + } + + @Test + public void removeTest() { + AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + User user; + + when(principal.getName()).thenReturn(name1); + user = new User(principal); + // Add a user with a principal + aucs.addUser(user); + // Check that the user is in the cache + assertThat(aucs.getUser(principal), is(user)); + // Remove the user + when(principal.getName()).thenReturn(name1 + "NoCred"); + aucs.remove(user); + // Check that the user is no longer in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(nullValue())); + + // Add the user again + aucs.addUser(user); + // Check that the user is in the cache + assertThat(aucs.getUser(principal), is(user)); + // Remove the user by name + aucs.remove(name1 + "NoCred"); + // Check that the user is no longer in the cache + assertThat(aucs.getUser(principal), is(nullValue())); + + // Coverage test - attempt to remove a user that is not in the cache + aucs.remove(name1 + "NoCred"); + assertThat(aucs.getUser(principal), is(nullValue())); + } + + @Test + public void clearAllTest() { + AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + User user1; + User user2; + + // Add some users to the cache + when(principal.getName()).thenReturn(name1); + user1 = new User(principal); + when(principal.getName()).thenReturn(name2); + user2 = new User(principal); + aucs.addUser(user1); + aucs.addUser(user2); + + // Check that the users are in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(user1)); + when(principal.getName()).thenReturn(name2); + assertThat(aucs.getUser(principal), is(user2)); + + // Clear the cache + aucs.clearAll(); + + // Check that the users are no longer in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(nullValue())); + when(principal.getName()).thenReturn(name2); + assertThat(aucs.getUser(principal), is(nullValue())); + } + + @Test + public void dumpInfoTest() { + AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + User user1; + User user2; + + Principal principal1 = mock(Principal.class); + Principal principal2 = mock(Principal.class); + when(principal1.getName()).thenReturn(name1); + when(principal2.getName()).thenReturn(name2); + + // Add some users with permissions to the cache + user1 = new User(principal1); + user1.add(permission1); + user1.add(permission2); + user2 = new User(principal2); + user2.add(permission1); + user2.add(permission2); + aucs.addUser(user1); + aucs.addUser(user2); + + // Dump the info + List.DumpInfo> dumpInfo = aucs.dumpInfo(); + assertThat(dumpInfo.size(), is(2)); + + // Utility lists + List names = new ArrayList<>(); + names.add(name1); + names.add(name2); + List permissions = new ArrayList<>(); + permissions.add("NewKey1"); + permissions.add("NewKey2"); + + // We need to use "contains" because the dumpInfo was created from a list, so we don't know it's order + for (AbsUserCache.DumpInfo di : dumpInfo) { + assertTrue(names.contains(di.user)); + for (String perm : di.perms) { + assertTrue(permissions.contains(perm)); + } + } + } + + @Test + public void handlesExclusivelyTest() { + AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + assertFalse(aucs.handlesExclusively(permission1)); + assertFalse(aucs.handlesExclusively(permission2)); + } + + @Test + public void destroyTest() { + AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + aucs.destroy(); + aucs = new AbsUserCacheStub(access, 1, 1, Integer.MAX_VALUE); + aucs.destroy(); + } + + @Test + public void missTest() throws IOException { + AbsUserCacheStub aucs = new AbsUserCacheStub(access, 0, 0, Integer.MAX_VALUE); + // Add the Miss to the missmap + assertTrue(aucs.addMiss("key", password)); // This one actually adds it + assertTrue(aucs.addMiss("key", password)); // this one doesn't really do anything + assertTrue(aucs.addMiss("key", password)); // neither does this one + assertFalse(aucs.addMiss("key", password)); // By this time, the missMap is tired of this nonsense, and retaliates + assertFalse(aucs.addMiss("key", password)); // Oh yea. He's angry + + // Can't really test this due to visibility + aucs.missed("key", password); + + // Coverage + AbsUserCacheStub aucs1 = new AbsUserCacheStub(access, 1, 1, Integer.MAX_VALUE); + aucs1.addMiss("key", password); + } + + class AbsUserCacheStub extends AbsUserCache { + public AbsUserCacheStub(Access access, long cleanInterval, int highCount, int usageCount) { super(access, cleanInterval, highCount, usageCount); } + public AbsUserCacheStub(AbsUserCache cache) { super(cache); } + @Override public void setLur(CachingLur lur) { super.setLur(lur); } + @Override public void addUser(User user) { super.addUser(user); } + @Override public void addUser(String key, User user) { super.addUser(key, user); } + @Override public User getUser(Principal p) { return super.getUser(p); } + @Override public User getUser(CachedBasicPrincipal p) { return super.getUser(p); } + @Override public User getUser(String user, byte[] cred) { return super.getUser(user, cred); } + @Override public void remove(User user) { super.remove(user); } + @Override public boolean addMiss(String key, byte[] bs) { return super.addMiss(key, bs); } + @Override public Miss missed(String key, byte[] bs) throws IOException { return super.missed(key, bs); } + } + + class AbsUserCacheCLStub extends AbsUserCache implements CachingLur { + public AbsUserCacheCLStub(AbsUserCache cache) { super(cache); } + @Override public Permission createPerm(String p) { return null; } + @Override public boolean fish(Principal bait, Permission ... pond) { return false; } + @Override public void fishAll(Principal bait, List permissions) { } + @Override public boolean handles(Principal principal) { return false; } + @Override public Resp reload(User user) { return null; } + @Override public void setDebug(String commaDelimIDsOrNull) { } + } + + class GetCredStub implements Principal, GetCred { + @Override public byte[] getCred() { return password; } + @Override public String getName() { return name1; } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Access.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Access.java index 98903567..f97fb5fe 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Access.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Access.java @@ -32,35 +32,35 @@ import org.onap.aaf.cadi.Access.Level; public class JU_Access { - @Test - public void levelTests() { - assertTrue(Level.DEBUG.inMask(0x1)); - for (int i = 2; i > 0; i <<= 1) { - assertFalse(Level.DEBUG.inMask(i)); - } - assertFalse(Level.DEBUG.inMask(0x80000000)); + @Test + public void levelTests() { + assertTrue(Level.DEBUG.inMask(0x1)); + for (int i = 2; i > 0; i <<= 1) { + assertFalse(Level.DEBUG.inMask(i)); + } + assertFalse(Level.DEBUG.inMask(0x80000000)); - assertThat(Level.DEBUG.addToMask(0x2), is(0x3)); - assertThat(Level.DEBUG.delFromMask(0x1), is(0x0)); - assertThat(Level.DEBUG.toggle(0x2), is(0x3)); - assertThat(Level.DEBUG.toggle(0x1), is(0x0)); - assertThat(Level.DEBUG.maskOf(), is(123153)); - assertThat(Level.NONE.maskOf(), is(0)); - } + assertThat(Level.DEBUG.addToMask(0x2), is(0x3)); + assertThat(Level.DEBUG.delFromMask(0x1), is(0x0)); + assertThat(Level.DEBUG.toggle(0x2), is(0x3)); + assertThat(Level.DEBUG.toggle(0x1), is(0x0)); + assertThat(Level.DEBUG.maskOf(), is(123153)); + assertThat(Level.NONE.maskOf(), is(0)); + } - @Test - public void nullTests() throws IOException { - // These are entirely for coverage - Access.NULL.log(Level.DEBUG); - Access.NULL.printf(Level.DEBUG, ""); - Access.NULL.log(new Exception()); - Access.NULL.classLoader(); - assertThat(Access.NULL.getProperty("", ""), is(nullValue())); - Access.NULL.load(System.in); - Access.NULL.setLogLevel(Level.DEBUG); - assertThat(Access.NULL.decrypt("test", true), is("test")); - assertFalse(Access.NULL.willLog(Level.DEBUG)); - assertThat(Access.NULL.getProperties(), is(not(nullValue()))); - } + @Test + public void nullTests() throws IOException { + // These are entirely for coverage + Access.NULL.log(Level.DEBUG); + Access.NULL.printf(Level.DEBUG, ""); + Access.NULL.log(new Exception()); + Access.NULL.classLoader(); + assertThat(Access.NULL.getProperty("", ""), is(nullValue())); + Access.NULL.load(System.in); + Access.NULL.setLogLevel(Level.DEBUG); + assertThat(Access.NULL.decrypt("test", true), is("test")); + assertFalse(Access.NULL.willLog(Level.DEBUG)); + assertThat(Access.NULL.getProperties(), is(not(nullValue()))); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java index 801259d4..e819d574 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java @@ -34,59 +34,59 @@ import org.onap.aaf.cadi.Symm; import org.onap.aaf.cadi.config.Config; public class JU_Base64 { - private static final String encoding = "Man is distinguished, not only by his reason, but by this singular " + - "passion from other animals, which is a lust of the mind, that by a " + - "perseverance of delight in the continued and indefatigable generation of " + - "knowledge, exceeds the short vehemence of any carnal pleasure."; + private static final String encoding = "Man is distinguished, not only by his reason, but by this singular " + + "passion from other animals, which is a lust of the mind, that by a " + + "perseverance of delight in the continued and indefatigable generation of " + + "knowledge, exceeds the short vehemence of any carnal pleasure."; - private static final String expected = - "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz\n" + - "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg\n" + - "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu\n" + - "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo\n" + - "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; + private static final String expected = + "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz\n" + + "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg\n" + + "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu\n" + + "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo\n" + + "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; - @Test - public void test() throws Exception { - // Test with different Padding - assertEncoded("leas", "bGVhcw=="); - assertEncoded("leasu", "bGVhc3U="); - assertEncoded("leasur", "bGVhc3Vy"); - assertEncoded("leasure", "bGVhc3VyZQ=="); - assertEncoded("leasure.", "bGVhc3VyZS4="); + @Test + public void test() throws Exception { + // Test with different Padding + assertEncoded("leas", "bGVhcw=="); + assertEncoded("leasu", "bGVhc3U="); + assertEncoded("leasur", "bGVhc3Vy"); + assertEncoded("leasure", "bGVhc3VyZQ=="); + assertEncoded("leasure.", "bGVhc3VyZS4="); - // Test with line ends - assertEncoded(encoding, expected); - } + // Test with line ends + assertEncoded(encoding, expected); + } - @Test - public void symmetric() throws IOException { - String symmetric = new String(Symm.keygen()); - Symm bsym = Symm.obtain(symmetric); - String result = bsym.encode(encoding); - assertThat(bsym.decode(result), is(encoding)); + @Test + public void symmetric() throws IOException { + String symmetric = new String(Symm.keygen()); + Symm bsym = Symm.obtain(symmetric); + String result = bsym.encode(encoding); + assertThat(bsym.decode(result), is(encoding)); - char[] manipulate = symmetric.toCharArray(); - int spot = new SecureRandom().nextInt(manipulate.length); - manipulate[spot]|=0xFF; - String newsymmetric = new String(manipulate); - assertThat(symmetric, is(not(newsymmetric))); - try { - bsym = Symm.obtain(newsymmetric); - result = bsym.decode(result); - assertThat(result, is(encoding)); - } catch (IOException e) { - // this is what we want to see if key wrong - } - } + char[] manipulate = symmetric.toCharArray(); + int spot = new SecureRandom().nextInt(manipulate.length); + manipulate[spot]|=0xFF; + String newsymmetric = new String(manipulate); + assertThat(symmetric, is(not(newsymmetric))); + try { + bsym = Symm.obtain(newsymmetric); + result = bsym.decode(result); + assertThat(result, is(encoding)); + } catch (IOException e) { + // this is what we want to see if key wrong + } + } - private void assertEncoded(String toEncode, String expected) throws IOException { - String result = Symm.base64.encode(toEncode); - assertThat(result, is(expected)); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Symm.base64.decode(new ByteArrayInputStream(result.getBytes()), baos); - result = baos.toString(Config.UTF_8); - assertThat(result, is(toEncode)); - } + private void assertEncoded(String toEncode, String expected) throws IOException { + String result = Symm.base64.encode(toEncode); + assertThat(result, is(expected)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Symm.base64.decode(new ByteArrayInputStream(result.getBytes()), baos); + result = baos.toString(Config.UTF_8); + assertThat(result, is(toEncode)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java index 172270da..d01e0f07 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java @@ -28,18 +28,18 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class JU_BufferedCadiWrap { - @Mock - private HttpServletRequest request; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } + @Mock + private HttpServletRequest request; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } - @Test - public void constructorTest() { - // TODO: Ian - This will always fail beacuse the constructor is invalid - // BufferedCadiWrap bcw = new BufferedCadiWrap(request); - } + @Test + public void constructorTest() { + // TODO: Ian - This will always fail beacuse the constructor is invalid + // BufferedCadiWrap bcw = new BufferedCadiWrap(request); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java index 66ac3610..a16487f8 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java @@ -34,98 +34,98 @@ import org.onap.aaf.cadi.BufferedServletInputStream; import static junit.framework.Assert.assertEquals; public class JU_BufferedServletInputStream { - private BufferedServletInputStream bsis; - private String expected; - - @Before - public void setup() throws FileNotFoundException { - expected = new String("This is the expected output"); - bsis = new BufferedServletInputStream(new ByteArrayInputStream(expected.getBytes())); - } - - @After - public void tearDown() throws IOException { - bsis.close(); - } - - @Test - public void ByteReadNoMarkTest() throws Exception { - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - } - Assert.assertEquals(new String(output, 0, i), expected); - } - - @Test - public void ByteReadMarkTest() throws Exception { - bsis.mark(0); - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - } - Assert.assertEquals(new String(output, 0, i), expected); - } - - @Test - public void ByteReadStateIsStoreTest() throws Exception { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); - bsis.mark(0); - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - } - bsis.reset(); - Assert.assertEquals(state_field.get(bsis), 2); // state == READ - } - - @Test - public void ByteReadStateIsReadTest() throws Exception { - bsis.mark(0); // Initialize the capacitor - boolean isReset = false; - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - if ((i > 5) && !isReset) { - // Close the capacitor and start over. This is done for coverage purposes - i = 0; - isReset = true; - bsis.reset(); // Sets state to READ - } - } - Assert.assertEquals(new String(output, 0, i), expected); - } - - @Test - public void ByteReadStateIsNoneTest() throws Exception { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); - bsis.mark(0); // Initialize the capacitor - int c; - c = bsis.read(); - // Close the capacitor. This is done for coverage purposes - bsis.reset(); // Sets state to READ - state_field.setInt(bsis, 0); // state == NONE - c = bsis.read(); - Assert.assertEquals(c, -1); - } - - @Test - public void ByteArrayReadNoMarkTest() throws Exception { - byte output[] = new byte[100]; - int count = bsis.read(output, 0, expected.length()); - Assert.assertEquals(new String(output, 0, count), expected); - Assert.assertEquals(count, expected.length()); - } + private BufferedServletInputStream bsis; + private String expected; + + @Before + public void setup() throws FileNotFoundException { + expected = new String("This is the expected output"); + bsis = new BufferedServletInputStream(new ByteArrayInputStream(expected.getBytes())); + } + + @After + public void tearDown() throws IOException { + bsis.close(); + } + + @Test + public void ByteReadNoMarkTest() throws Exception { + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadMarkTest() throws Exception { + bsis.mark(0); + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadStateIsStoreTest() throws Exception { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + bsis.mark(0); + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + bsis.reset(); + Assert.assertEquals(state_field.get(bsis), 2); // state == READ + } + + @Test + public void ByteReadStateIsReadTest() throws Exception { + bsis.mark(0); // Initialize the capacitor + boolean isReset = false; + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + if ((i > 5) && !isReset) { + // Close the capacitor and start over. This is done for coverage purposes + i = 0; + isReset = true; + bsis.reset(); // Sets state to READ + } + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadStateIsNoneTest() throws Exception { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + bsis.mark(0); // Initialize the capacitor + int c; + c = bsis.read(); + // Close the capacitor. This is done for coverage purposes + bsis.reset(); // Sets state to READ + state_field.setInt(bsis, 0); // state == NONE + c = bsis.read(); + Assert.assertEquals(c, -1); + } + + @Test + public void ByteArrayReadNoMarkTest() throws Exception { + byte output[] = new byte[100]; + int count = bsis.read(output, 0, expected.length()); + Assert.assertEquals(new String(output, 0, count), expected); + Assert.assertEquals(count, expected.length()); + } @Test public void ByteArrayReadTest() throws Exception { @@ -135,50 +135,50 @@ public class JU_BufferedServletInputStream { Assert.assertEquals(new String(output, 0, expected.length()), expected); } - @Test - public void ByteArrayReadStateIsStoreTest() throws Exception { - byte output[] = new byte[100]; - bsis.mark(0); - int count = bsis.read(output, 0, expected.length()); - Assert.assertEquals(new String(output, 0, count), expected); - Assert.assertEquals(count, expected.length()); - - count = bsis.read(output, 0, 0); - Assert.assertEquals(count, -1); - } - - @Test - public void ByteArrayReadStateIsReadTest() throws Exception { - byte output[] = new byte[200]; - for(int i = 0; i < 2; ++i) { - bsis.mark(0); - bsis.read(output, 0, 100); + @Test + public void ByteArrayReadStateIsStoreTest() throws Exception { + byte output[] = new byte[100]; + bsis.mark(0); + int count = bsis.read(output, 0, expected.length()); + Assert.assertEquals(new String(output, 0, count), expected); + Assert.assertEquals(count, expected.length()); + + count = bsis.read(output, 0, 0); + Assert.assertEquals(count, -1); + } + + @Test + public void ByteArrayReadStateIsReadTest() throws Exception { + byte output[] = new byte[200]; + for(int i = 0; i < 2; ++i) { + bsis.mark(0); + bsis.read(output, 0, 100); Assert.assertEquals(new String(output, 0, expected.length()), expected); - bsis.reset(); - bsis.read(output, 0, output.length); + bsis.reset(); + bsis.read(output, 0, output.length); Assert.assertEquals(new String(output, 0, expected.length()), expected); - bsis = new BufferedServletInputStream(new ByteArrayInputStream(output)); - if(i == 0) { - output = new byte[200]; - } - } + bsis = new BufferedServletInputStream(new ByteArrayInputStream(output)); + if(i == 0) { + output = new byte[200]; + } + } Assert.assertEquals(new String(output, 0, expected.length()), expected); - } + } - @Test - public void ByteArrayReadStateIsNoneTest() throws Exception { + @Test + public void ByteArrayReadStateIsNoneTest() throws Exception { byte output[] = new byte[100]; bsis.mark(0); Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); + state_field.setAccessible(true); state_field.setInt(bsis, 0); // state == NONE int count = bsis.read(output, 0, 100); Assert.assertEquals(count, -1); - } + } @Test public void skipTest() throws Exception { @@ -210,42 +210,42 @@ public class JU_BufferedServletInputStream { @Test public void closeTest() throws Exception { - Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); - capacitor_field.setAccessible(true); + Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); + capacitor_field.setAccessible(true); bsis.mark(0); Assert.assertNotNull(capacitor_field.get(bsis)); bsis.close(); - Assert.assertNull(capacitor_field.get(bsis)); + Assert.assertNull(capacitor_field.get(bsis)); } - @Test - public void markTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); - capacitor_field.setAccessible(true); - state_field.setAccessible(true); + @Test + public void markTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); + capacitor_field.setAccessible(true); + state_field.setAccessible(true); - // capacitor is null initially - Assert.assertNull(capacitor_field.get(bsis)); + // capacitor is null initially + Assert.assertNull(capacitor_field.get(bsis)); - state_field.setInt(bsis, 0); // state == NONE - bsis.mark(0); // the value passed into mark is ignored - Assert.assertNotNull(capacitor_field.get(bsis)); - Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + state_field.setInt(bsis, 0); // state == NONE + bsis.mark(0); // the value passed into mark is ignored + Assert.assertNotNull(capacitor_field.get(bsis)); + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE - state_field.setInt(bsis, 1); // state == STORE - bsis.mark(0); // the value passed into mark is ignored - Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + state_field.setInt(bsis, 1); // state == STORE + bsis.mark(0); // the value passed into mark is ignored + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE - state_field.setInt(bsis, 2); // state == READ - bsis.mark(0); // the value passed into mark is ignored - Assert.assertEquals(state_field.get(bsis), 1); // state == STORE - } + state_field.setInt(bsis, 2); // state == READ + bsis.mark(0); // the value passed into mark is ignored + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + } @Test public void resetTest() throws Exception { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); bsis.mark(0); Assert.assertEquals(state_field.get(bsis), 1); // state == STORE @@ -254,7 +254,7 @@ public class JU_BufferedServletInputStream { bsis.reset(); Assert.assertEquals(state_field.get(bsis), 2); // state == READ - state_field.setInt(bsis, -1); // state is invalid + state_field.setInt(bsis, -1); // state is invalid bsis.reset(); // This call does nothing. It is for coverage alone Assert.assertEquals(state_field.get(bsis), -1); // state doesn't change @@ -271,50 +271,50 @@ public class JU_BufferedServletInputStream { Assert.assertTrue(bsis.markSupported()); } - // "Bug" 4/22/2013 - // Some XML code expects Buffered InputStream can never return 0... This isn't actually true, but we'll accommodate as far - // as we can. - // Here, we make sure we set and read the Buffered data, making sure the buffer is empty on the last test... - @Test - public void issue04_22_2013() throws IOException { - String testString = "We want to read in and get out with a Buffered Stream seamlessly."; - ByteArrayInputStream bais = new ByteArrayInputStream(testString.getBytes()); - BufferedServletInputStream bsis = new BufferedServletInputStream(bais); - try { - bsis.mark(0); - byte aa[] = new byte[testString.length()]; // 65 count... important for our test (divisible by 5); - - int read; - for(int i=0;i=0;i+=read) { - read = bsis.read(bb,i,5); - switch(i) { - case 65: - assertEquals(read,-1); - break; - default: - assertEquals(read,5); - } - } - // System.out.println(new String(bb)); - assertEquals(testString,new String(aa)); - assertEquals(testString,new String(bb)); - - } finally { - bsis.close(); - bais.close(); - } - - } + // "Bug" 4/22/2013 + // Some XML code expects Buffered InputStream can never return 0... This isn't actually true, but we'll accommodate as far + // as we can. + // Here, we make sure we set and read the Buffered data, making sure the buffer is empty on the last test... + @Test + public void issue04_22_2013() throws IOException { + String testString = "We want to read in and get out with a Buffered Stream seamlessly."; + ByteArrayInputStream bais = new ByteArrayInputStream(testString.getBytes()); + BufferedServletInputStream bsis = new BufferedServletInputStream(bais); + try { + bsis.mark(0); + byte aa[] = new byte[testString.length()]; // 65 count... important for our test (divisible by 5); + + int read; + for(int i=0;i=0;i+=read) { + read = bsis.read(bb,i,5); + switch(i) { + case 65: + assertEquals(read,-1); + break; + default: + assertEquals(read,5); + } + } + // System.out.println(new String(bb)); + assertEquals(testString,new String(aa)); + assertEquals(testString,new String(bb)); + + } finally { + bsis.close(); + bais.close(); + } + + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiException.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiException.java index bfcaeeab..f1b5f144 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiException.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiException.java @@ -29,92 +29,92 @@ import org.onap.aaf.cadi.CadiException; import static org.hamcrest.CoreMatchers.is; public class JU_CadiException { - @Test - public void testCadiException() { - CadiException exception = new CadiException(); - - assertNotNull(exception); - } - - @Test - public void testCadiExceptionString() { - CadiException exception = new CadiException("New Exception"); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } - - @Test - public void testCadiExceptionThrowable() { - CadiException exception = new CadiException(new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); - } - - @Test - public void testCadiExceptionStringThrowable() { - CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - - } - - @Test - public void testCadiException1() { - CadiException exception = new CadiException(); - - assertNotNull(exception); - } - - @Test - public void testCadiExceptionString1() { - CadiException exception = new CadiException("New Exception"); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } - - @Test - public void testCadiExceptionThrowable1() { - CadiException exception = new CadiException(new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); - } - - @Test - public void testCadiExceptionStringThrowable1() { - CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - - } - - @Test - public void testCadiException2() { - CadiException exception = new CadiException(); - - assertNotNull(exception); - } - - @Test - public void testCadiExceptionString2() { - CadiException exception = new CadiException("New Exception"); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } - - @Test - public void testCadiExceptionThrowable2() { - CadiException exception = new CadiException(new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); - } - - @Test - public void testCadiExceptionStringThrowable2() { - CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - - } + @Test + public void testCadiException() { + CadiException exception = new CadiException(); + + assertNotNull(exception); + } + + @Test + public void testCadiExceptionString() { + CadiException exception = new CadiException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void testCadiExceptionThrowable() { + CadiException exception = new CadiException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } + + @Test + public void testCadiExceptionStringThrowable() { + CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + + } + + @Test + public void testCadiException1() { + CadiException exception = new CadiException(); + + assertNotNull(exception); + } + + @Test + public void testCadiExceptionString1() { + CadiException exception = new CadiException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void testCadiExceptionThrowable1() { + CadiException exception = new CadiException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } + + @Test + public void testCadiExceptionStringThrowable1() { + CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + + } + + @Test + public void testCadiException2() { + CadiException exception = new CadiException(); + + assertNotNull(exception); + } + + @Test + public void testCadiExceptionString2() { + CadiException exception = new CadiException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void testCadiExceptionThrowable2() { + CadiException exception = new CadiException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } + + @Test + public void testCadiExceptionStringThrowable2() { + CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiWrap.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiWrap.java index 850dd22c..ef07fa66 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiWrap.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiWrap.java @@ -51,111 +51,111 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; import org.onap.aaf.cadi.taf.TafResp; public class JU_CadiWrap { - - @Mock - private HttpServletRequest request; - - @Mock - private TafResp tafResp; - - @Mock - private TaggedPrincipal principle; + + @Mock + private HttpServletRequest request; + + @Mock + private TafResp tafResp; + + @Mock + private TaggedPrincipal principle; - @Mock - private Lur lur; + @Mock + private Lur lur; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); - System.setOut(new PrintStream(new ByteArrayOutputStream())); - } + System.setOut(new PrintStream(new ByteArrayOutputStream())); + } - @After - public void tearDown() { - System.setOut(System.out); - } + @After + public void tearDown() { + System.setOut(System.out); + } - @SuppressWarnings("unchecked") - @Test - public void testInstantiate() throws CadiException { - Access a = new PropAccess(); - when(tafResp.getAccess()).thenReturn(a); - - lur.fishAll(isA(Principal.class), (List)isA(List.class)); - - EpiLur lur1 = new EpiLur(lur); - - CadiWrap wrap = new CadiWrap(request, tafResp, lur1); - - assertNull(wrap.getUserPrincipal()); - assertNull(wrap.getRemoteUser()); - assertNull(wrap.getUser()); - assertEquals(wrap.getPermissions(principle).size(), 0); - assertTrue(wrap.access() instanceof PropAccess); - - byte[] arr = {'1','2'}; - wrap.setCred(arr); - - assertEquals(arr, wrap.getCred()); - - wrap.setUser("User1"); - assertEquals("User1", wrap.getUser()); - - wrap.invalidate("1"); + @SuppressWarnings("unchecked") + @Test + public void testInstantiate() throws CadiException { + Access a = new PropAccess(); + when(tafResp.getAccess()).thenReturn(a); + + lur.fishAll(isA(Principal.class), (List)isA(List.class)); + + EpiLur lur1 = new EpiLur(lur); + + CadiWrap wrap = new CadiWrap(request, tafResp, lur1); + + assertNull(wrap.getUserPrincipal()); + assertNull(wrap.getRemoteUser()); + assertNull(wrap.getUser()); + assertEquals(wrap.getPermissions(principle).size(), 0); + assertTrue(wrap.access() instanceof PropAccess); + + byte[] arr = {'1','2'}; + wrap.setCred(arr); + + assertEquals(arr, wrap.getCred()); + + wrap.setUser("User1"); + assertEquals("User1", wrap.getUser()); + + wrap.invalidate("1"); - assertFalse(wrap.isUserInRole(null)); - - wrap.set(tafResp, lur); - - wrap.invalidate("2"); - - assertFalse(wrap.isUserInRole("User1")); - } + assertFalse(wrap.isUserInRole(null)); + + wrap.set(tafResp, lur); + + wrap.invalidate("2"); + + assertFalse(wrap.isUserInRole("User1")); + } - @Test - public void testInstantiateWithPermConverter() throws CadiException { - Access a = new PropAccess(); - when(tafResp.getAccess()).thenReturn(a); - when(tafResp.getPrincipal()).thenReturn(principle); - - // Anonymous object for testing purposes - CachingLur lur1 = new CachingLur() { - @Override public Permission createPerm(String p) { return null; } - @Override public boolean fish(Principal bait, Permission ... pond) { return true; } - @Override public void fishAll(Principal bait, List permissions) { } - @Override public void destroy() { } - @Override public boolean handlesExclusively(Permission ... pond) { return false; } - @Override public boolean handles(Principal principal) { return false; } - @Override public void remove(String user) { } - @Override public Resp reload(User user) { return null; } - @Override public void setDebug(String commaDelimIDsOrNull) { } - @Override public void clear(Principal p, StringBuilder sb) { } - }; - - MapPermConverter pc = new MapPermConverter(); - - CadiWrap wrap = new CadiWrap(request, tafResp, lur1, pc); - - assertNotNull(wrap.getUserPrincipal()); - assertNull(wrap.getRemoteUser()); - assertNull(wrap.getUser()); - - byte[] arr = {'1','2'}; - wrap.setCred(arr); - - assertEquals(arr, wrap.getCred()); - - wrap.setUser("User1"); - assertEquals("User1", wrap.getUser()); - - wrap.invalidate("1"); - wrap.setPermConverter(new MapPermConverter()); - - assertTrue(wrap.getLur() instanceof CachingLur); - assertTrue(wrap.isUserInRole("User1")); - - wrap.set(tafResp, lur); - assertFalse(wrap.isUserInRole("Perm1")); - } + @Test + public void testInstantiateWithPermConverter() throws CadiException { + Access a = new PropAccess(); + when(tafResp.getAccess()).thenReturn(a); + when(tafResp.getPrincipal()).thenReturn(principle); + + // Anonymous object for testing purposes + CachingLur lur1 = new CachingLur() { + @Override public Permission createPerm(String p) { return null; } + @Override public boolean fish(Principal bait, Permission ... pond) { return true; } + @Override public void fishAll(Principal bait, List permissions) { } + @Override public void destroy() { } + @Override public boolean handlesExclusively(Permission ... pond) { return false; } + @Override public boolean handles(Principal principal) { return false; } + @Override public void remove(String user) { } + @Override public Resp reload(User user) { return null; } + @Override public void setDebug(String commaDelimIDsOrNull) { } + @Override public void clear(Principal p, StringBuilder sb) { } + }; + + MapPermConverter pc = new MapPermConverter(); + + CadiWrap wrap = new CadiWrap(request, tafResp, lur1, pc); + + assertNotNull(wrap.getUserPrincipal()); + assertNull(wrap.getRemoteUser()); + assertNull(wrap.getUser()); + + byte[] arr = {'1','2'}; + wrap.setCred(arr); + + assertEquals(arr, wrap.getCred()); + + wrap.setUser("User1"); + assertEquals("User1", wrap.getUser()); + + wrap.invalidate("1"); + wrap.setPermConverter(new MapPermConverter()); + + assertTrue(wrap.getLur() instanceof CachingLur); + assertTrue(wrap.isUserInRole("User1")); + + wrap.set(tafResp, lur); + assertFalse(wrap.isUserInRole("Perm1")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java index e9bceccd..ad08d159 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java @@ -32,22 +32,22 @@ import org.onap.aaf.cadi.Capacitor; import java.lang.reflect.*; public class JU_Capacitor { - private Capacitor cap; - public final static String TEST_DATA = - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + - "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + - "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + - "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - - @Before - public void setup() { - cap = new Capacitor(); - } - - @Test - public void singleByteTest() throws Exception { + private Capacitor cap; + public final static String TEST_DATA = + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + + @Before + public void setup() { + cap = new Capacitor(); + } + + @Test + public void singleByteTest() throws Exception { assertEquals(cap.read(), -1); cap.setForRead(); Field curr_field = Capacitor.class.getDeclaredField("curr"); @@ -57,35 +57,35 @@ public class JU_Capacitor { assertNull(curr_field.get(cap)); assertEquals(idx_field.get(cap), 0); - for(int iter = 0; iter < 20; ++iter) { - for(int i = 0; i < 20; ++i) { - cap.put((byte)('a' + i)); - } - cap.setForRead(); - byte[] array = new byte[20]; - for(int i = 0; i < 20; ++i) { - array[i]=(byte)cap.read(); - } - assertEquals("abcdefghijklmnopqrst", new String(array)); - assertEquals(-1, cap.read()); - - cap.done(); - } - - for(int i = 0; i < 500; i++) { - cap.put((byte)'a'); - } - cap.setForRead(); - byte[] array = new byte[500]; - for(int i = 0; i < 500; ++i) { - array[i]=(byte)cap.read(); - } + for(int iter = 0; iter < 20; ++iter) { + for(int i = 0; i < 20; ++i) { + cap.put((byte)('a' + i)); + } + cap.setForRead(); + byte[] array = new byte[20]; + for(int i = 0; i < 20; ++i) { + array[i]=(byte)cap.read(); + } + assertEquals("abcdefghijklmnopqrst", new String(array)); + assertEquals(-1, cap.read()); + + cap.done(); + } + + for(int i = 0; i < 500; i++) { + cap.put((byte)'a'); + } + cap.setForRead(); + byte[] array = new byte[500]; + for(int i = 0; i < 500; ++i) { + array[i]=(byte)cap.read(); + } assertEquals((new String(array)).length(), 500); - assertEquals(-1, cap.read()); - } + assertEquals(-1, cap.read()); + } - @Test - public void availableTest() { + @Test + public void availableTest() { assertEquals(cap.available(), 0); for(int i = 0; i < 100; ++i) { cap.put((byte)'a'); @@ -95,9 +95,9 @@ public class JU_Capacitor { assertEquals(cap.available(), 156); } - @Test - public void byteArrayTest() { - byte[] arrayA = TEST_DATA.getBytes(); + @Test + public void byteArrayTest() { + byte[] arrayA = TEST_DATA.getBytes(); assertEquals(cap.read(arrayA, 0, arrayA.length), -1); cap.put(arrayA, 0, arrayA.length); @@ -109,24 +109,24 @@ public class JU_Capacitor { assertEquals(-1, cap.read()); cap.done(); - String b = "This is some content that we want to read"; - byte[] a = b.getBytes(); - byte[] c = new byte[b.length()]; // we want to use this to test reading offsets, etc - - for(int i = 0; i < a.length; i += 11) { - cap.put(a, i, Math.min(11, a.length-i)); - } - cap.reset(); - int read; - for(int i = 0; i < c.length; i += read) { - read = cap.read(c, i, Math.min(3, c.length-i)); - } - assertEquals(b, new String(c)); - } - - @Test - public void resetTest() throws Exception { - cap.reset(); + String b = "This is some content that we want to read"; + byte[] a = b.getBytes(); + byte[] c = new byte[b.length()]; // we want to use this to test reading offsets, etc + + for(int i = 0; i < a.length; i += 11) { + cap.put(a, i, Math.min(11, a.length-i)); + } + cap.reset(); + int read; + for(int i = 0; i < c.length; i += read) { + read = cap.read(c, i, Math.min(3, c.length-i)); + } + assertEquals(b, new String(c)); + } + + @Test + public void resetTest() throws Exception { + cap.reset(); Field curr_field = Capacitor.class.getDeclaredField("curr"); curr_field.setAccessible(true); Field idx_field = Capacitor.class.getDeclaredField("idx"); @@ -134,22 +134,22 @@ public class JU_Capacitor { assertNull(curr_field.get(cap)); assertEquals(idx_field.get(cap), 0); - cap.put((byte)'a'); - cap.reset(); + cap.put((byte)'a'); + cap.reset(); assertNotNull(curr_field.get(cap)); assertEquals(idx_field.get(cap), 1); - } - - @Test - public void skipTest() throws Exception { - // capacitor can't skip if nothing has been put into it - assertEquals(cap.skip(10), 0); - cap.put((byte)'a'); - // The Capacitor can hold 256 bytes. If we try to skip 100 bytes, - // it should only skip 1 byte, leaving 255 remaining - assertEquals(cap.skip(100), 255); - - // Skipping 200 bytes leaves 0 remaining - assertEquals(cap.skip(200), 0); - } + } + + @Test + public void skipTest() throws Exception { + // capacitor can't skip if nothing has been put into it + assertEquals(cap.skip(10), 0); + cap.put((byte)'a'); + // The Capacitor can hold 256 bytes. If we try to skip 100 bytes, + // it should only skip 1 byte, leaving 255 remaining + assertEquals(cap.skip(100), 255); + + // Skipping 200 bytes leaves 0 remaining + assertEquals(cap.skip(200), 0); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java index bf4304d9..3a996df4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java @@ -48,226 +48,226 @@ import org.onap.aaf.cadi.Symm; public class JU_CmdLine { - @Mock - private OutputStream thrower; - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - - private String password; - private String keyfile; - private String quickBrownFoxPlain = "The quick brown fox jumps over the lazy dog"; - private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; - private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; - private Symm symm; - - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); - - System.setOut(new PrintStream(outContent)); - - Properties p = new Properties(); - p.setProperty("force_exit", "false"); - - CmdLine.setSystemExit(false); - keyfile = "src/test/resources/keyfile"; - password = "password"; - - File keyF = new File("src/test/resources", "keyfile"); - FileInputStream fis = new FileInputStream(keyF); - try { - symm = Symm.obtain(fis); - } finally { - fis.close(); - } - } - - @After - public void restoreStreams() throws IOException { - System.setOut(System.out); - System.setIn(System.in); - } - - @Test - public void digestTest() throws Exception { - CmdLine.main(new String[]{"digest", password, keyfile}); - String decrypted = symm.depass(outContent.toString()); - assertThat(decrypted, is(password)); - - System.setIn(new ByteArrayInputStream(password.getBytes())); - CmdLine.main(new String[]{"digest", "-i", keyfile}); - decrypted = symm.depass(outContent.toString()); - assertThat(decrypted, is(password)); - } - - @Test - public void encode64Test() throws Exception { - CmdLine.main(new String[]{"encode64", password}); - String decrypted = Symm.base64.decode(outContent.toString()); - assertThat(decrypted, is(password)); - } - - @Test - public void decode64Test() throws Exception { - String encrypted = Symm.base64.encode(password); - CmdLine.main(new String[]{"decode64", encrypted}); - assertThat(outContent.toString(), is(password + System.lineSeparator())); - } - - @Test - public void encode64urlTest() throws Exception { - CmdLine.main(new String[]{"encode64url", password}); - String decrypted = Symm.base64url.decode(outContent.toString()); - assertThat(decrypted, is(password)); - } - - @Test - public void decode64urlTest() throws Exception { - String encrypted = Symm.base64url.encode(password); - CmdLine.main(new String[]{"decode64url", encrypted}); - assertThat(outContent.toString(), is(password + System.lineSeparator())); - } - - @Test - public void md5Test() throws Exception { - CmdLine.main(new String[]{"md5", quickBrownFoxPlain}); - assertThat(outContent.toString(), is(quickBrownFoxMD5 + System.lineSeparator())); - } - - @Test - public void sha256Test() throws Exception { - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain}); - assertThat(outContent.toString(), is(quickBrownFoxSHA256 + System.lineSeparator())); - - outContent.reset(); - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); - String hash1 = outContent.toString(); - - outContent.reset(); - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); - String hash2 = outContent.toString(); - - outContent.reset(); - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "11"}); - String hash3 = outContent.toString(); - - assertThat(hash1, is(hash2)); - assertThat(hash1, is(not(hash3))); - } - - @Test - public void keygenTest() throws Exception { - CmdLine.main(new String[]{"keygen"}); - assertThat(outContent.toString().length(), is(2074)); - - String filePath = "test/output_key"; - File testDir = new File("test"); - if(!testDir.exists()) { - testDir.mkdirs(); - } - CmdLine.main(new String[]{"keygen", filePath}); - File keyfile = new File(filePath); - assertTrue(Files.isReadable(Paths.get(filePath))); - assertFalse(Files.isWritable(Paths.get(filePath))); - //assertFalse(Files.isExecutable(Paths.get(filePath))); - keyfile.delete(); - } - - @Test - public void passgenTest() throws Exception { - CmdLine.main(new String[]{"passgen"}); - String output = outContent.toString().trim(); - assertThat(output.length(), is(24)); - assertTrue(containsAny(output, "+!@#$%^&*(){}[]?:;,.")); - assertTrue(containsAny(output, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")); - assertTrue(containsAny(output, "abcdefghijklmnopqrstuvwxyz")); - assertTrue(containsAny(output, "0123456789")); - - int length = 10; - outContent.reset(); - CmdLine.main(new String[]{"passgen", String.valueOf(length)}); - output = outContent.toString().trim(); - assertThat(output.length(), is(length)); - - length = 5; - outContent.reset(); - CmdLine.main(new String[]{"passgen", String.valueOf(length)}); - output = outContent.toString().trim(); - assertThat(output.length(), is(8)); - - // Check that the custom hasRepeats method works - assertTrue(hasRepeats("aa")); - assertTrue(hasRepeats("baa")); - assertTrue(hasRepeats("aab")); - assertTrue(hasRepeats("baab")); - assertFalse(hasRepeats("abc")); - assertFalse(hasRepeats("aba")); - - // Run this a bunch of times for coverage - for (int i = 0; i < 1000; i++) { - outContent.reset(); - CmdLine.main(new String[]{"passgen"}); - output = outContent.toString().trim(); - assertFalse(hasRepeats(output)); - } - } - - @Test - public void urlgenTest() throws Exception { - CmdLine.main(new String[]{"urlgen"}); - String output = outContent.toString().trim(); - assertThat(output.length(), is(24)); - - int length = 5; - outContent.reset(); - CmdLine.main(new String[]{"urlgen", String.valueOf(length)}); - output = outContent.toString().trim(); - assertThat(output.length(), is(5)); - } - - @Test - public void showHelpTest() { - String lineSeparator = System.lineSeparator(); - String expected = - "Usage: java -jar ..." + lineSeparator + - " keygen [] (Generates Key on file, or Std Out)" + lineSeparator + - " digest [|-i|] (Encrypts Password with \"keyfile\"" + lineSeparator + - " if passwd = -i, will read StdIn" + lineSeparator + - " if passwd is blank, will ask securely)" + lineSeparator + - " passgen (Generate Password of given size)" + lineSeparator + - " urlgen (Generate URL field of given size)" + lineSeparator + - " encode64 (Encodes to Base64)" + lineSeparator + - " decode64 (Decodes from Base64)" + lineSeparator + - " encode64url (Encodes to Base64 URL charset)" + lineSeparator + - " decode64url (Decodes from Base64 URL charset)" + lineSeparator + - " sha256 (Digest String into SHA256 Hash)" + lineSeparator + - " md5 (Digest String into MD5 Hash)" + lineSeparator; - - CmdLine.main(new String[]{}); - - assertThat(outContent.toString(), is(expected)); - } - - private boolean containsAny(String str, String searchChars) { - for (char c : searchChars.toCharArray()) { - if (str.indexOf(c) >= 0) { - return true; - } - } - return false; - } - - private boolean hasRepeats(String str) { - int c = -1; - int last; - for (int i = 0; i < str.length(); i++) { - last = c; - c = str.charAt(i); - if (c == last) { - return true; - } - } - return false; - } + @Mock + private OutputStream thrower; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + + private String password; + private String keyfile; + private String quickBrownFoxPlain = "The quick brown fox jumps over the lazy dog"; + private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; + private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; + private Symm symm; + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + + System.setOut(new PrintStream(outContent)); + + Properties p = new Properties(); + p.setProperty("force_exit", "false"); + + CmdLine.setSystemExit(false); + keyfile = "src/test/resources/keyfile"; + password = "password"; + + File keyF = new File("src/test/resources", "keyfile"); + FileInputStream fis = new FileInputStream(keyF); + try { + symm = Symm.obtain(fis); + } finally { + fis.close(); + } + } + + @After + public void restoreStreams() throws IOException { + System.setOut(System.out); + System.setIn(System.in); + } + + @Test + public void digestTest() throws Exception { + CmdLine.main(new String[]{"digest", password, keyfile}); + String decrypted = symm.depass(outContent.toString()); + assertThat(decrypted, is(password)); + + System.setIn(new ByteArrayInputStream(password.getBytes())); + CmdLine.main(new String[]{"digest", "-i", keyfile}); + decrypted = symm.depass(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void encode64Test() throws Exception { + CmdLine.main(new String[]{"encode64", password}); + String decrypted = Symm.base64.decode(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void decode64Test() throws Exception { + String encrypted = Symm.base64.encode(password); + CmdLine.main(new String[]{"decode64", encrypted}); + assertThat(outContent.toString(), is(password + System.lineSeparator())); + } + + @Test + public void encode64urlTest() throws Exception { + CmdLine.main(new String[]{"encode64url", password}); + String decrypted = Symm.base64url.decode(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void decode64urlTest() throws Exception { + String encrypted = Symm.base64url.encode(password); + CmdLine.main(new String[]{"decode64url", encrypted}); + assertThat(outContent.toString(), is(password + System.lineSeparator())); + } + + @Test + public void md5Test() throws Exception { + CmdLine.main(new String[]{"md5", quickBrownFoxPlain}); + assertThat(outContent.toString(), is(quickBrownFoxMD5 + System.lineSeparator())); + } + + @Test + public void sha256Test() throws Exception { + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain}); + assertThat(outContent.toString(), is(quickBrownFoxSHA256 + System.lineSeparator())); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); + String hash1 = outContent.toString(); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); + String hash2 = outContent.toString(); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "11"}); + String hash3 = outContent.toString(); + + assertThat(hash1, is(hash2)); + assertThat(hash1, is(not(hash3))); + } + + @Test + public void keygenTest() throws Exception { + CmdLine.main(new String[]{"keygen"}); + assertThat(outContent.toString().length(), is(2074)); + + String filePath = "test/output_key"; + File testDir = new File("test"); + if(!testDir.exists()) { + testDir.mkdirs(); + } + CmdLine.main(new String[]{"keygen", filePath}); + File keyfile = new File(filePath); + assertTrue(Files.isReadable(Paths.get(filePath))); + assertFalse(Files.isWritable(Paths.get(filePath))); + //assertFalse(Files.isExecutable(Paths.get(filePath))); + keyfile.delete(); + } + + @Test + public void passgenTest() throws Exception { + CmdLine.main(new String[]{"passgen"}); + String output = outContent.toString().trim(); + assertThat(output.length(), is(24)); + assertTrue(containsAny(output, "+!@#$%^&*(){}[]?:;,.")); + assertTrue(containsAny(output, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + assertTrue(containsAny(output, "abcdefghijklmnopqrstuvwxyz")); + assertTrue(containsAny(output, "0123456789")); + + int length = 10; + outContent.reset(); + CmdLine.main(new String[]{"passgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(length)); + + length = 5; + outContent.reset(); + CmdLine.main(new String[]{"passgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(8)); + + // Check that the custom hasRepeats method works + assertTrue(hasRepeats("aa")); + assertTrue(hasRepeats("baa")); + assertTrue(hasRepeats("aab")); + assertTrue(hasRepeats("baab")); + assertFalse(hasRepeats("abc")); + assertFalse(hasRepeats("aba")); + + // Run this a bunch of times for coverage + for (int i = 0; i < 1000; i++) { + outContent.reset(); + CmdLine.main(new String[]{"passgen"}); + output = outContent.toString().trim(); + assertFalse(hasRepeats(output)); + } + } + + @Test + public void urlgenTest() throws Exception { + CmdLine.main(new String[]{"urlgen"}); + String output = outContent.toString().trim(); + assertThat(output.length(), is(24)); + + int length = 5; + outContent.reset(); + CmdLine.main(new String[]{"urlgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(5)); + } + + @Test + public void showHelpTest() { + String lineSeparator = System.lineSeparator(); + String expected = + "Usage: java -jar ..." + lineSeparator + + " keygen [] (Generates Key on file, or Std Out)" + lineSeparator + + " digest [|-i|] (Encrypts Password with \"keyfile\"" + lineSeparator + + " if passwd = -i, will read StdIn" + lineSeparator + + " if passwd is blank, will ask securely)" + lineSeparator + + " passgen (Generate Password of given size)" + lineSeparator + + " urlgen (Generate URL field of given size)" + lineSeparator + + " encode64 (Encodes to Base64)" + lineSeparator + + " decode64 (Decodes from Base64)" + lineSeparator + + " encode64url (Encodes to Base64 URL charset)" + lineSeparator + + " decode64url (Decodes from Base64 URL charset)" + lineSeparator + + " sha256 (Digest String into SHA256 Hash)" + lineSeparator + + " md5 (Digest String into MD5 Hash)" + lineSeparator; + + CmdLine.main(new String[]{}); + + assertThat(outContent.toString(), is(expected)); + } + + private boolean containsAny(String str, String searchChars) { + for (char c : searchChars.toCharArray()) { + if (str.indexOf(c) >= 0) { + return true; + } + } + return false; + } + + private boolean hasRepeats(String str) { + int c = -1; + int last; + for (int i = 0; i < str.length(); i++) { + last = c; + c = str.charAt(i); + if (c == last) { + return true; + } + } + return false; + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java index f5c4d872..343dd22a 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java @@ -32,156 +32,156 @@ import org.junit.BeforeClass; import static org.hamcrest.CoreMatchers.*; public class JU_Hash { - // Some common test vectors - private String quickBrownFoxVector = "The quick brown fox jumps over the lazy dog"; - private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; - private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; - - private String emptyVector = ""; - private String emptyMD5 = "0xd41d8cd98f00b204e9800998ecf8427e"; - private String emptySHA256 = "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - - - private byte[] same1 = "this is a twin".getBytes(); - private byte[] same2 = "this is a twin".getBytes(); - private byte[] different1 = "guvf vf n gjva".getBytes(); - private byte[] different2 = "this is an only child".getBytes(); - - - private String uppersDec = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - private String uppersHex1 = "0x4142434445464748494A4B4C4D4E4F505152535455565758595A"; - private String uppersHex2 = "0x4142434445464748494a4b4c4d4e4f505152535455565758595a"; - private String uppersHexNo0x1 = "4142434445464748494a4b4c4d4e4f505152535455565758595a"; - private String uppersHexNo0x2 = "4142434445464748494A4B4C4D4E4F505152535455565758595A"; - - private String lowersDec = "abcdefghijklmnopqrstuvwxyz"; - private String lowersHex = "0x6162636465666768696a6b6c6d6e6f707172737475767778797a"; - private String lowersHexNo0x1 = "6162636465666768696a6b6c6d6e6f707172737475767778797a"; - private String lowersHexNo0x2 = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; - - private String numbersDec = "1234567890"; - private String numbersHex = "0x31323334353637383930"; - private String numbersHexNo0x = "31323334353637383930"; - - @SuppressWarnings("unused") - @BeforeClass - public static void getCoverage() { - // All of this class's methods are static, so we never need to instantiate an object. - // That said, we can't get 100% coverage unless we instantiate one - Hash hash = new Hash(); - } + // Some common test vectors + private String quickBrownFoxVector = "The quick brown fox jumps over the lazy dog"; + private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; + private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; + + private String emptyVector = ""; + private String emptyMD5 = "0xd41d8cd98f00b204e9800998ecf8427e"; + private String emptySHA256 = "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + + private byte[] same1 = "this is a twin".getBytes(); + private byte[] same2 = "this is a twin".getBytes(); + private byte[] different1 = "guvf vf n gjva".getBytes(); + private byte[] different2 = "this is an only child".getBytes(); + + + private String uppersDec = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private String uppersHex1 = "0x4142434445464748494A4B4C4D4E4F505152535455565758595A"; + private String uppersHex2 = "0x4142434445464748494a4b4c4d4e4f505152535455565758595a"; + private String uppersHexNo0x1 = "4142434445464748494a4b4c4d4e4f505152535455565758595a"; + private String uppersHexNo0x2 = "4142434445464748494A4B4C4D4E4F505152535455565758595A"; + + private String lowersDec = "abcdefghijklmnopqrstuvwxyz"; + private String lowersHex = "0x6162636465666768696a6b6c6d6e6f707172737475767778797a"; + private String lowersHexNo0x1 = "6162636465666768696a6b6c6d6e6f707172737475767778797a"; + private String lowersHexNo0x2 = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; + + private String numbersDec = "1234567890"; + private String numbersHex = "0x31323334353637383930"; + private String numbersHexNo0x = "31323334353637383930"; + + @SuppressWarnings("unused") + @BeforeClass + public static void getCoverage() { + // All of this class's methods are static, so we never need to instantiate an object. + // That said, we can't get 100% coverage unless we instantiate one + Hash hash = new Hash(); + } @Test public void hashMD5Test() throws Exception { byte[] output = Hash.hashMD5(quickBrownFoxVector.getBytes()); - assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); output = Hash.hashMD5(emptyVector.getBytes()); - assertEquals(emptyMD5, new String(Hash.toHex(output))); + assertEquals(emptyMD5, new String(Hash.toHex(output))); } @Test public void hashMD5WithOffsetTest() throws Exception { byte[] output = Hash.hashMD5(quickBrownFoxVector.getBytes(), 0, quickBrownFoxVector.length()); - assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); output = Hash.hashMD5(emptyVector.getBytes(), 0, emptyVector.length()); - assertEquals(emptyMD5, new String(Hash.toHex(output))); + assertEquals(emptyMD5, new String(Hash.toHex(output))); } @Test public void hashMD5AsStringHexTest() throws Exception { String output = Hash.hashMD5asStringHex(quickBrownFoxVector); - assertEquals(quickBrownFoxMD5, output); + assertEquals(quickBrownFoxMD5, output); output = Hash.hashMD5asStringHex(emptyVector); - assertEquals(emptyMD5, output); + assertEquals(emptyMD5, output); } @Test public void hashSHA256Test() throws Exception { byte[] output = Hash.hashSHA256(quickBrownFoxVector.getBytes()); - assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); output = Hash.hashSHA256(emptyVector.getBytes()); - assertEquals(emptySHA256, new String(Hash.toHex(output))); + assertEquals(emptySHA256, new String(Hash.toHex(output))); } @Test public void hashSHA256WithOffsetTest() throws Exception { byte[] output = Hash.hashSHA256(quickBrownFoxVector.getBytes(), 0, quickBrownFoxVector.length()); - assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); output = Hash.hashSHA256(emptyVector.getBytes(), 0, emptyVector.length()); - assertEquals(emptySHA256, new String(Hash.toHex(output))); + assertEquals(emptySHA256, new String(Hash.toHex(output))); } @Test public void hashSHA256AsStringHexTest() throws Exception { String output = Hash.hashSHA256asStringHex(quickBrownFoxVector); - assertEquals(quickBrownFoxSHA256, output); + assertEquals(quickBrownFoxSHA256, output); output = Hash.hashSHA256asStringHex(emptyVector); - assertEquals(emptySHA256, output); + assertEquals(emptySHA256, output); } @Test public void hashSaltySHA256AsStringHexTest() throws Exception { - String input = "password"; - String hash1 = Hash.hashSHA256asStringHex(input, 10); - String hash2 = Hash.hashSHA256asStringHex(input, 10); - String hash3 = Hash.hashSHA256asStringHex(input, 11); + String input = "password"; + String hash1 = Hash.hashSHA256asStringHex(input, 10); + String hash2 = Hash.hashSHA256asStringHex(input, 10); + String hash3 = Hash.hashSHA256asStringHex(input, 11); - assertEquals(hash1, hash2); - assertThat(hash1, not(equalTo(hash3))); + assertEquals(hash1, hash2); + assertThat(hash1, not(equalTo(hash3))); } - @Test - public void isEqualTest() throws Exception { - assertTrue(Hash.isEqual(same1, same2)); - assertFalse(Hash.isEqual(same1, different1)); - assertFalse(Hash.isEqual(same1, different2)); - } - - @Test - public void compareToTest() throws Exception { - assertEquals(0, Hash.compareTo(same1, same2)); - // different1 is rot13(same1), so the difference should be 13 - assertEquals(13, Hash.compareTo(same1, different1)); - assertEquals(-78, Hash.compareTo(same1, different2)); - } - - @Test - public void toHexNo0xTest() throws Exception { - assertEquals(uppersHexNo0x1, Hash.toHexNo0x(uppersDec.getBytes())); - assertEquals(lowersHexNo0x1, Hash.toHexNo0x(lowersDec.getBytes())); - assertEquals(numbersHexNo0x, Hash.toHexNo0x(numbersDec.getBytes())); - } - - @Test - public void toHexTest() throws Exception { - assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes())); - assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes())); - assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes())); - } + @Test + public void isEqualTest() throws Exception { + assertTrue(Hash.isEqual(same1, same2)); + assertFalse(Hash.isEqual(same1, different1)); + assertFalse(Hash.isEqual(same1, different2)); + } + + @Test + public void compareToTest() throws Exception { + assertEquals(0, Hash.compareTo(same1, same2)); + // different1 is rot13(same1), so the difference should be 13 + assertEquals(13, Hash.compareTo(same1, different1)); + assertEquals(-78, Hash.compareTo(same1, different2)); + } + + @Test + public void toHexNo0xTest() throws Exception { + assertEquals(uppersHexNo0x1, Hash.toHexNo0x(uppersDec.getBytes())); + assertEquals(lowersHexNo0x1, Hash.toHexNo0x(lowersDec.getBytes())); + assertEquals(numbersHexNo0x, Hash.toHexNo0x(numbersDec.getBytes())); + } + + @Test + public void toHexTest() throws Exception { + assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes())); + assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes())); + assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes())); + } @Test public void toHexWithOffset() throws Exception { - assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes(), 0, uppersDec.length())); - assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes(), 0, lowersDec.length())); - assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes(), 0, numbersDec.length())); + assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes(), 0, uppersDec.length())); + assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes(), 0, lowersDec.length())); + assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes(), 0, numbersDec.length())); } - @Test - public void fromHexTest() throws Exception { - assertEquals(uppersDec, new String(Hash.fromHex(uppersHex1))); - assertEquals(lowersDec, new String(Hash.fromHex(lowersHex))); - assertEquals(numbersDec, new String(Hash.fromHex(numbersHex))); + @Test + public void fromHexTest() throws Exception { + assertEquals(uppersDec, new String(Hash.fromHex(uppersHex1))); + assertEquals(lowersDec, new String(Hash.fromHex(lowersHex))); + assertEquals(numbersDec, new String(Hash.fromHex(numbersHex))); try { // This string doesn't begin with "0x" Hash.fromHex("0X65"); - fail("Should have thrown CadiException"); + fail("Should have thrown CadiException"); } catch (CadiException e) { assertEquals("HexString must start with \"0x\"", e.getMessage()); } @@ -189,22 +189,22 @@ public class JU_Hash { try { // This string has invalid hex characters Hash.fromHex("0xQ"); - fail("Should have thrown CadiException"); + fail("Should have thrown CadiException"); } catch (CadiException e) { // 81 is dec(Q) assertEquals("Invalid char '81' in HexString", e.getMessage()); } - } - - @Test - public void fromHexNo0xTest() throws Exception { - assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x1))); - assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x1))); - assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x2))); - assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x2))); - assertEquals(numbersDec, new String(Hash.fromHexNo0x(numbersHexNo0x))); - byte[] output = Hash.fromHexNo0x("ABC"); - assertEquals(new String(new byte[] {(byte)0x0A, (byte)0xB0}), new String(output)); - assertNull(Hash.fromHexNo0x("~~")); - } + } + + @Test + public void fromHexNo0xTest() throws Exception { + assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x1))); + assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x1))); + assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x2))); + assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x2))); + assertEquals(numbersDec, new String(Hash.fromHexNo0x(numbersHexNo0x))); + byte[] output = Hash.fromHexNo0x("ABC"); + assertEquals(new String(new byte[] {(byte)0x0A, (byte)0xB0}), new String(output)); + assertNull(Hash.fromHexNo0x("~~")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java index 96cf8e51..ef354438 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java @@ -29,32 +29,32 @@ import org.onap.aaf.cadi.LocatorException; import static org.hamcrest.CoreMatchers.is; public class JU_LocatorException { - @Test - public void stringTest() { - LocatorException exception = new LocatorException("New Exception"); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } + @Test + public void stringTest() { + LocatorException exception = new LocatorException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } - @Test - public void throwableTest() { - LocatorException exception = new LocatorException(new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); - } + @Test + public void throwableTest() { + LocatorException exception = new LocatorException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } - @Test - public void stringThrowableTest() { - LocatorException exception = new LocatorException("New Exception",new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } + @Test + public void stringThrowableTest() { + LocatorException exception = new LocatorException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } - @Test - public void characterSequenceTest() { - CharSequence testCS = new String("New Exception"); - LocatorException exception = new LocatorException(testCS); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } + @Test + public void characterSequenceTest() { + CharSequence testCS = new String("New Exception"); + LocatorException exception = new LocatorException(testCS); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java index 7b5da6c1..eb5d32c6 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java @@ -38,114 +38,114 @@ import java.util.Properties; @SuppressWarnings("unused") public class JU_PropAccess { - // Note: We can't actually get coverage of the protected constructor - - // that will be done later, when testing the child class "ServletContextAccess" - - - @Test - public void ConstructorTest() throws Exception { - PropAccess prop = new PropAccess(); - assertThat(prop.getProperties(), is(not(nullValue()))); - } - - @Test - public void noPrintStreamConstructionTest() throws Exception { - // Test for coverage - PropAccess prop = new PropAccess((PrintStream)null, new String[]{"Invalid argument"}); - } - - @Test - public void noLogItConstructionTest() throws Exception { - // Test for coverage - PropAccess prop = new PropAccess((LogIt)null, new String[]{"Invalid argument"}); - } - - @Test - public void propertiesConstructionTest() throws Exception { - // Coverage tests - PropAccess prop = new PropAccess(System.getProperties()); - prop = new PropAccess((PrintStream)null, System.getProperties()); - } - - @Test - public void stringConstructionTest() throws Exception { - Properties testSystemProps = new Properties(System.getProperties()); - testSystemProps.setProperty("cadi_name", "user"); - System.setProperties(testSystemProps); - PropAccess prop = new PropAccess("cadi_keyfile=src/test/resources/keyfile", "cadi_loglevel=DEBUG", "cadi_prop_files=test/cadi.properties:not_a_file"); - } - - @Test - public void loadTest() throws Exception { - // Coverage tests - Properties props = mock(Properties.class); - when(props.getProperty("cadi_prop_files")).thenReturn("test/cadi.properties").thenReturn(null); - PropAccess pa = new PropAccess(); - Field props_field = PropAccess.class.getDeclaredField("props"); - props_field.setAccessible(true); - props_field.set(pa, props); - ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); - pa.load(bais); - } - - @Test - public void specialConversionsTest() throws Exception { - // Coverage tests - Properties testSystemProps = new Properties(System.getProperties()); - testSystemProps.setProperty("java.specification.version", "1.7"); - System.setProperties(testSystemProps); - PropAccess pa = new PropAccess("AFT_LATITUDE=1", "AFT_LONGITUDE=1", "cadi_protocols=TLSv1.2"); - } - - @Test - public void logTest() throws Exception { - // Coverage tests - PropAccess pa = new PropAccess(); - - pa.log(Level.DEBUG); - pa.printf(Level.DEBUG, "not a real format string"); - - pa.setLogLevel(Level.DEBUG); - pa.log(Level.DEBUG); - pa.log(Level.DEBUG, 1, " ", null, ""); - pa.log(Level.DEBUG, "This is a string", "This is another"); - pa.set(new LogIt() { - @Override public void push(Level level, Object ... elements) {} - }); - try { - pa.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { - fail("Should have thrown an exception"); - } - } - - @Test - public void classLoaderTest() { - PropAccess pa = new PropAccess(); - assertThat(pa.classLoader(), instanceOf(ClassLoader.class)); - } - - @Test - public void encryptionTest() throws Exception { - PropAccess pa = new PropAccess(); - String plainText = "This is a secret message"; - String secret_message = pa.encrypt(plainText); - String modified = secret_message.substring(4); - // Plenty of assertions to hit all branches - assertThat(pa.decrypt(secret_message, false), is(plainText)); - assertThat(pa.decrypt(null, false), is(nullValue())); - assertThat(pa.decrypt(modified, true), is(plainText)); - assertThat(pa.decrypt(modified, false), is(modified)); - } - - @Test - public void setPropertyTest() { - PropAccess pa = new PropAccess(); - pa.setProperty("test", null); - String prop = "New Property"; - String val ="And it's faithful value"; - pa.setProperty(prop, val); - - assertThat(pa.getProperty(prop), is(val)); - } + // Note: We can't actually get coverage of the protected constructor - + // that will be done later, when testing the child class "ServletContextAccess" + + + @Test + public void ConstructorTest() throws Exception { + PropAccess prop = new PropAccess(); + assertThat(prop.getProperties(), is(not(nullValue()))); + } + + @Test + public void noPrintStreamConstructionTest() throws Exception { + // Test for coverage + PropAccess prop = new PropAccess((PrintStream)null, new String[]{"Invalid argument"}); + } + + @Test + public void noLogItConstructionTest() throws Exception { + // Test for coverage + PropAccess prop = new PropAccess((LogIt)null, new String[]{"Invalid argument"}); + } + + @Test + public void propertiesConstructionTest() throws Exception { + // Coverage tests + PropAccess prop = new PropAccess(System.getProperties()); + prop = new PropAccess((PrintStream)null, System.getProperties()); + } + + @Test + public void stringConstructionTest() throws Exception { + Properties testSystemProps = new Properties(System.getProperties()); + testSystemProps.setProperty("cadi_name", "user"); + System.setProperties(testSystemProps); + PropAccess prop = new PropAccess("cadi_keyfile=src/test/resources/keyfile", "cadi_loglevel=DEBUG", "cadi_prop_files=test/cadi.properties:not_a_file"); + } + + @Test + public void loadTest() throws Exception { + // Coverage tests + Properties props = mock(Properties.class); + when(props.getProperty("cadi_prop_files")).thenReturn("test/cadi.properties").thenReturn(null); + PropAccess pa = new PropAccess(); + Field props_field = PropAccess.class.getDeclaredField("props"); + props_field.setAccessible(true); + props_field.set(pa, props); + ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); + pa.load(bais); + } + + @Test + public void specialConversionsTest() throws Exception { + // Coverage tests + Properties testSystemProps = new Properties(System.getProperties()); + testSystemProps.setProperty("java.specification.version", "1.7"); + System.setProperties(testSystemProps); + PropAccess pa = new PropAccess("AFT_LATITUDE=1", "AFT_LONGITUDE=1", "cadi_protocols=TLSv1.2"); + } + + @Test + public void logTest() throws Exception { + // Coverage tests + PropAccess pa = new PropAccess(); + + pa.log(Level.DEBUG); + pa.printf(Level.DEBUG, "not a real format string"); + + pa.setLogLevel(Level.DEBUG); + pa.log(Level.DEBUG); + pa.log(Level.DEBUG, 1, " ", null, ""); + pa.log(Level.DEBUG, "This is a string", "This is another"); + pa.set(new LogIt() { + @Override public void push(Level level, Object ... elements) {} + }); + try { + pa.log(new Exception("This exception was thrown intentionally, please ignore it")); + } catch(Exception e) { + fail("Should have thrown an exception"); + } + } + + @Test + public void classLoaderTest() { + PropAccess pa = new PropAccess(); + assertThat(pa.classLoader(), instanceOf(ClassLoader.class)); + } + + @Test + public void encryptionTest() throws Exception { + PropAccess pa = new PropAccess(); + String plainText = "This is a secret message"; + String secret_message = pa.encrypt(plainText); + String modified = secret_message.substring(4); + // Plenty of assertions to hit all branches + assertThat(pa.decrypt(secret_message, false), is(plainText)); + assertThat(pa.decrypt(null, false), is(nullValue())); + assertThat(pa.decrypt(modified, true), is(plainText)); + assertThat(pa.decrypt(modified, false), is(modified)); + } + + @Test + public void setPropertyTest() { + PropAccess pa = new PropAccess(); + pa.setProperty("test", null); + String prop = "New Property"; + String val ="And it's faithful value"; + pa.setProperty(prop, val); + + assertThat(pa.getProperty(prop), is(val)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java index 8531e1d1..e7689eae 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java @@ -47,58 +47,58 @@ import javax.servlet.ServletContext; @SuppressWarnings("unused") public class JU_ServletContextAccess { - private FilterConfig filter_mock; - Enumeration enumeration; - - private class CustomEnumeration implements Enumeration { - private int idx = 0; - private final String[] elements = {"This", "is", "a", "test"}; - @Override - public String nextElement() { - return idx >= elements.length ? null : elements[idx++]; - } - @Override - public boolean hasMoreElements() { - return idx < elements.length; - } - } + private FilterConfig filter_mock; + Enumeration enumeration; + + private class CustomEnumeration implements Enumeration { + private int idx = 0; + private final String[] elements = {"This", "is", "a", "test"}; + @Override + public String nextElement() { + return idx >= elements.length ? null : elements[idx++]; + } + @Override + public boolean hasMoreElements() { + return idx < elements.length; + } + } - @Before - public void setup() { - enumeration = new CustomEnumeration(); - filter_mock = mock(FilterConfig.class); - when(filter_mock.getInitParameterNames()).thenReturn(enumeration); - } - - @Test - public void ConstructorTest() throws Exception { - ServletContextAccess sca = new ServletContextAccess(filter_mock); - } + @Before + public void setup() { + enumeration = new CustomEnumeration(); + filter_mock = mock(FilterConfig.class); + when(filter_mock.getInitParameterNames()).thenReturn(enumeration); + } + + @Test + public void ConstructorTest() throws Exception { + ServletContextAccess sca = new ServletContextAccess(filter_mock); + } - @Test - public void logTest() throws Exception { - ServletContext sc_mock = mock(ServletContext.class); - when(filter_mock.getServletContext()).thenReturn(sc_mock); - ServletContextAccess sca = new ServletContextAccess(filter_mock); + @Test + public void logTest() throws Exception { + ServletContext sc_mock = mock(ServletContext.class); + when(filter_mock.getServletContext()).thenReturn(sc_mock); + ServletContextAccess sca = new ServletContextAccess(filter_mock); - sca.log(Level.DEBUG); + sca.log(Level.DEBUG); - sca.setLogLevel(Level.DEBUG); - sca.log(Level.DEBUG); + sca.setLogLevel(Level.DEBUG); + sca.log(Level.DEBUG); - try { - sca.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { - fail("Should have thrown an exception"); - } - } + try { + sca.log(new Exception("This exception was thrown intentionally, please ignore it")); + } catch(Exception e) { + fail("Should have thrown an exception"); + } + } - @Test - public void contextTest() { - ServletContext sc_mock = mock(ServletContext.class); - when(filter_mock.getServletContext()).thenReturn(sc_mock); - ServletContextAccess sca = new ServletContextAccess(filter_mock); - assertThat(sca.context(), instanceOf(ServletContext.class)); - } + @Test + public void contextTest() { + ServletContext sc_mock = mock(ServletContext.class); + when(filter_mock.getServletContext()).thenReturn(sc_mock); + ServletContextAccess sca = new ServletContextAccess(filter_mock); + assertThat(sca.context(), instanceOf(ServletContext.class)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java index 753451ed..abbc9e90 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java @@ -37,176 +37,176 @@ import org.onap.aaf.cadi.PropAccess; import org.onap.aaf.cadi.Symm; public class JU_Symm { - private Symm defaultSymm; - - private ByteArrayOutputStream outStream; - - @Before - public void setup() throws Exception { - defaultSymm = new Symm( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() - ,76, "Use default!" ,true); - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - } - - @After - public void tearDown() { - System.setOut(System.out); - } - - @Test - public void constructorTest() throws Exception { - Symm myCustomSymm = new Symm( - "ACEGIKMOQSUWYacegikmoqsuwy02468+/".toCharArray(), 76, "Default", true); - Field convert_field = Symm.class.getDeclaredField("convert"); - convert_field.setAccessible(true); - - Class Unordered_class = Class.forName("org.onap.aaf.cadi.Symm$Unordered"); - assertThat(convert_field.get(myCustomSymm), instanceOf(Unordered_class)); - } - - @SuppressWarnings("unused") - @Test - public void copyTest() throws Exception { - Symm copy = Symm.base64.copy(76); - } - - @SuppressWarnings("deprecation") - @Test - public void deprecatedTest() { - assertEquals(Symm.base64(), Symm.base64); - assertEquals(Symm.base64noSplit(), Symm.base64noSplit); - assertEquals(Symm.base64url(), Symm.base64url); - assertEquals(Symm.baseCrypt(), Symm.encrypt); - } - - @Test - public void encodeDecodeStringTest() throws Exception { - String orig = "hello"; - String b64encrypted = Symm.base64.encode(orig); - assertEquals(Symm.base64.decode(b64encrypted), orig); - - String defaultEnrypted = defaultSymm.encode(orig); - assertEquals(defaultSymm.decode(defaultEnrypted), orig); - } - - @Test - public void encodeDecodeByteArrayTest() throws Exception { - String orig = "hello"; - byte[] b64encrypted = Symm.base64.encode(orig.getBytes()); - assertEquals(new String(Symm.base64.decode(b64encrypted)), orig); - - byte[] empty = null; - assertTrue(Arrays.equals(Symm.base64.encode(empty), new byte[0])); - } - - @Test - public void encodeDecodeStringToStreamTest() throws Exception { - String orig = "I'm a password, really"; - String b64encrypted; - String output; - - ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); - Symm.base64.encode(orig, baosEncrypt); - b64encrypted = new String(baosEncrypt.toByteArray()); - - ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); - Symm.base64.decode(b64encrypted, baosDecrypt); - output = new String(baosDecrypt.toByteArray()); - - assertEquals(orig, output); - } - - @Test - public void encryptDecryptStreamWithPrefixTest() throws Exception { - String orig = "I'm a password, really"; - byte[] b64encrypted; - String output; - - byte[] prefix = "enc:".getBytes(); - - ByteArrayInputStream baisEncrypt = new ByteArrayInputStream(orig.getBytes()); - ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); - Symm.base64.encode(baisEncrypt, baosEncrypt, prefix); - - b64encrypted = baosEncrypt.toByteArray(); - - ByteArrayInputStream baisDecrypt = new ByteArrayInputStream(b64encrypted); - ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); - Symm.base64.decode(baisDecrypt, baosDecrypt, prefix.length); - - output = new String(baosDecrypt.toByteArray()); - assertEquals(orig, output); - } - - @Test - public void randomGenTest() { - // Ian - There really isn't a great way to test for randomness... - String prev = null; - for (int i = 0; i < 10; i++) { - String current = Symm.randomGen(100); - if (current.equals(prev)) { - fail("I don't know how, but you generated the exact same random string twice in a row"); - } - prev = current; - } - assertTrue(true); - } - - @Test - public void obtainTest() throws Exception { - Symm symm = Symm.base64.obtain(); - - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - } - - @Test - public void InputStreamObtainTest() throws Exception { - byte[] keygen = Symm.keygen(); - - Symm symm = Symm.obtain(new ByteArrayInputStream(keygen)); - - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - } - - @Test - public void StringObtainTest() throws Exception { - byte[] keygen = Symm.keygen(); - - Symm symm = Symm.obtain(new String(keygen)); - - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - } - - @Test - public void AccessObtainTest() throws Exception { - PropAccess pa = new PropAccess("cadi_keyfile=src/test/resources/keyfile"); - Symm symm = Symm.obtain(pa); - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - - try { - PropAccess badPa = mock(PropAccess.class); - when(badPa.getProperty("cadi_keyfile", null)).thenReturn("not_a_real_file.txt"); - symm = Symm.obtain(badPa); - fail("Should have thrown an exception"); - } catch (CadiException e) { - assertTrue(e.getMessage().contains("ERROR: ")); - assertTrue(e.getMessage().contains("not_a_real_file.txt")); - assertTrue(e.getMessage().contains(" does not exist!")); - } - } - + private Symm defaultSymm; + + private ByteArrayOutputStream outStream; + + @Before + public void setup() throws Exception { + defaultSymm = new Symm( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() + ,76, "Use default!" ,true); + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void constructorTest() throws Exception { + Symm myCustomSymm = new Symm( + "ACEGIKMOQSUWYacegikmoqsuwy02468+/".toCharArray(), 76, "Default", true); + Field convert_field = Symm.class.getDeclaredField("convert"); + convert_field.setAccessible(true); + + Class Unordered_class = Class.forName("org.onap.aaf.cadi.Symm$Unordered"); + assertThat(convert_field.get(myCustomSymm), instanceOf(Unordered_class)); + } + + @SuppressWarnings("unused") + @Test + public void copyTest() throws Exception { + Symm copy = Symm.base64.copy(76); + } + + @SuppressWarnings("deprecation") + @Test + public void deprecatedTest() { + assertEquals(Symm.base64(), Symm.base64); + assertEquals(Symm.base64noSplit(), Symm.base64noSplit); + assertEquals(Symm.base64url(), Symm.base64url); + assertEquals(Symm.baseCrypt(), Symm.encrypt); + } + + @Test + public void encodeDecodeStringTest() throws Exception { + String orig = "hello"; + String b64encrypted = Symm.base64.encode(orig); + assertEquals(Symm.base64.decode(b64encrypted), orig); + + String defaultEnrypted = defaultSymm.encode(orig); + assertEquals(defaultSymm.decode(defaultEnrypted), orig); + } + + @Test + public void encodeDecodeByteArrayTest() throws Exception { + String orig = "hello"; + byte[] b64encrypted = Symm.base64.encode(orig.getBytes()); + assertEquals(new String(Symm.base64.decode(b64encrypted)), orig); + + byte[] empty = null; + assertTrue(Arrays.equals(Symm.base64.encode(empty), new byte[0])); + } + + @Test + public void encodeDecodeStringToStreamTest() throws Exception { + String orig = "I'm a password, really"; + String b64encrypted; + String output; + + ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); + Symm.base64.encode(orig, baosEncrypt); + b64encrypted = new String(baosEncrypt.toByteArray()); + + ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); + Symm.base64.decode(b64encrypted, baosDecrypt); + output = new String(baosDecrypt.toByteArray()); + + assertEquals(orig, output); + } + + @Test + public void encryptDecryptStreamWithPrefixTest() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + byte[] prefix = "enc:".getBytes(); + + ByteArrayInputStream baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); + Symm.base64.encode(baisEncrypt, baosEncrypt, prefix); + + b64encrypted = baosEncrypt.toByteArray(); + + ByteArrayInputStream baisDecrypt = new ByteArrayInputStream(b64encrypted); + ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); + Symm.base64.decode(baisDecrypt, baosDecrypt, prefix.length); + + output = new String(baosDecrypt.toByteArray()); + assertEquals(orig, output); + } + + @Test + public void randomGenTest() { + // Ian - There really isn't a great way to test for randomness... + String prev = null; + for (int i = 0; i < 10; i++) { + String current = Symm.randomGen(100); + if (current.equals(prev)) { + fail("I don't know how, but you generated the exact same random string twice in a row"); + } + prev = current; + } + assertTrue(true); + } + + @Test + public void obtainTest() throws Exception { + Symm symm = Symm.base64.obtain(); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void InputStreamObtainTest() throws Exception { + byte[] keygen = Symm.keygen(); + + Symm symm = Symm.obtain(new ByteArrayInputStream(keygen)); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void StringObtainTest() throws Exception { + byte[] keygen = Symm.keygen(); + + Symm symm = Symm.obtain(new String(keygen)); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void AccessObtainTest() throws Exception { + PropAccess pa = new PropAccess("cadi_keyfile=src/test/resources/keyfile"); + Symm symm = Symm.obtain(pa); + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + + try { + PropAccess badPa = mock(PropAccess.class); + when(badPa.getProperty("cadi_keyfile", null)).thenReturn("not_a_real_file.txt"); + symm = Symm.obtain(badPa); + fail("Should have thrown an exception"); + } catch (CadiException e) { + assertTrue(e.getMessage().contains("ERROR: ")); + assertTrue(e.getMessage().contains("not_a_real_file.txt")); + assertTrue(e.getMessage().contains(" does not exist!")); + } + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java index 511c6ee3..c6070d7d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java @@ -29,9 +29,9 @@ import org.onap.aaf.cadi.TrustChecker; public class JU_TrustChecker { - @Test - public void noTrustTests() { - assertThat(TrustChecker.NOTRUST.mayTrust(null, null), is(nullValue())); - TrustChecker.NOTRUST.setLur(null); - } + @Test + public void noTrustTests() { + assertThat(TrustChecker.NOTRUST.mayTrust(null, null), is(nullValue())); + TrustChecker.NOTRUST.setLur(null); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java index 2d5ba8d2..857170a7 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java @@ -45,141 +45,141 @@ import org.onap.aaf.cadi.lur.LocalPermission; public class JU_User { - private final Long SECOND = 1000L; - private final String name = "Fakey McFake"; - private final String cred = "Fake credentials"; - - private Field perms_field; - private Field count_field; - - @Mock - private Principal principal; - - @Mock - private LocalPermission permission; - @Mock - private LocalPermission permission2; - - @Before - public void setup() throws NoSuchFieldException, SecurityException { - MockitoAnnotations.initMocks(this); - - when(principal.getName()).thenReturn("Principal"); - - when(permission.getKey()).thenReturn("NewKey"); - when(permission.match(permission)).thenReturn(true); - - when(permission2.getKey()).thenReturn("NewKey2"); - when(permission2.match(permission)).thenReturn(false); - - perms_field = User.class.getDeclaredField("perms"); - perms_field.setAccessible(true); - - count_field = User.class.getDeclaredField("count"); - count_field.setAccessible(true); - } - - @Test - public void constructorPrincipalTest() throws IllegalArgumentException, IllegalAccessException { - User user = new User(principal); - assertThat(user.name, is(principal.getName())); - assertThat(user.principal, is(principal)); - assertThat(user.permExpires(), is(Long.MAX_VALUE)); - assertThat((int)count_field.get(user), is(0)); - } - - @Test - public void constructorNameCredTest() throws IllegalArgumentException, IllegalAccessException { - User user = new User(name, cred.getBytes()); - assertThat(user.name, is(name)); - assertThat(user.principal, is(nullValue())); - assertThat(user.permExpires(), is(Long.MAX_VALUE)); - assertThat((int)count_field.get(user), is(0)); - assertThat(user.getCred(), is(cred.getBytes())); - } - - @Test - public void constructorPrincipalIntervalTest() throws IllegalArgumentException, IllegalAccessException { - User user = new User(principal, 61 * SECOND); - Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; - assertThat(user.name, is(principal.getName())); - assertThat(user.principal, is(principal)); - assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); - assertThat((int)count_field.get(user), is(0)); - } - - @Test - public void constructorNameCredIntervalTest() throws IllegalArgumentException, IllegalAccessException { - String name = "Fakey McFake"; - User user = new User(name, cred.getBytes(), 61 * SECOND); - Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; - assertThat(user.name, is(name)); - assertThat(user.principal, is(nullValue())); - assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); - assertThat((int)count_field.get(user), is(0)); - assertThat(user.getCred(), is(cred.getBytes())); - } - - @Test - public void countCheckTest() throws IllegalArgumentException, IllegalAccessException { - User user = new User(principal); - user.resetCount(); - assertThat((int)count_field.get(user), is(0)); - user.incCount(); - assertThat((int)count_field.get(user), is(1)); - user.incCount(); - assertThat((int)count_field.get(user), is(2)); - user.resetCount(); - assertThat((int)count_field.get(user), is(0)); - } - - @Test - public void permTest() throws InterruptedException, IllegalArgumentException, IllegalAccessException { - User user = new User(principal); - assertThat(user.permExpires(), is(Long.MAX_VALUE)); - user.renewPerm(); - Thread.sleep(1); // Let it expire - assertThat(user.permExpired(), is(true)); - - user = new User(principal,100); - assertTrue(user.noPerms()); - user.add(permission); - assertFalse(user.permsUnloaded()); - assertFalse(user.noPerms()); - user.setNoPerms(); - assertThat(user.permExpired(), is(false)); - assertTrue(user.permsUnloaded()); - assertTrue(user.noPerms()); - perms_field.set(user, null); - assertTrue(user.permsUnloaded()); - assertTrue(user.noPerms()); - } - - @Test - public void addValuesToNewMapTest() { - User user = new User(principal); - Map newMap = new HashMap<>(); - - assertFalse(user.contains(permission)); - - user.add(newMap, permission); - user.setMap(newMap); - - assertTrue(user.contains(permission)); - - List sink = new ArrayList<>(); - user.copyPermsTo(sink); - - assertThat(sink.size(), is(1)); - assertTrue(sink.contains(permission)); - - assertThat(user.toString(), is("Principal|:NewKey")); - - user.add(newMap, permission2); - user.setMap(newMap); - assertFalse(user.contains(permission2)); - - assertThat(user.toString(), is("Principal|:NewKey2,NewKey")); - } - + private final Long SECOND = 1000L; + private final String name = "Fakey McFake"; + private final String cred = "Fake credentials"; + + private Field perms_field; + private Field count_field; + + @Mock + private Principal principal; + + @Mock + private LocalPermission permission; + @Mock + private LocalPermission permission2; + + @Before + public void setup() throws NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + when(principal.getName()).thenReturn("Principal"); + + when(permission.getKey()).thenReturn("NewKey"); + when(permission.match(permission)).thenReturn(true); + + when(permission2.getKey()).thenReturn("NewKey2"); + when(permission2.match(permission)).thenReturn(false); + + perms_field = User.class.getDeclaredField("perms"); + perms_field.setAccessible(true); + + count_field = User.class.getDeclaredField("count"); + count_field.setAccessible(true); + } + + @Test + public void constructorPrincipalTest() throws IllegalArgumentException, IllegalAccessException { + User user = new User(principal); + assertThat(user.name, is(principal.getName())); + assertThat(user.principal, is(principal)); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void constructorNameCredTest() throws IllegalArgumentException, IllegalAccessException { + User user = new User(name, cred.getBytes()); + assertThat(user.name, is(name)); + assertThat(user.principal, is(nullValue())); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + assertThat((int)count_field.get(user), is(0)); + assertThat(user.getCred(), is(cred.getBytes())); + } + + @Test + public void constructorPrincipalIntervalTest() throws IllegalArgumentException, IllegalAccessException { + User user = new User(principal, 61 * SECOND); + Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; + assertThat(user.name, is(principal.getName())); + assertThat(user.principal, is(principal)); + assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void constructorNameCredIntervalTest() throws IllegalArgumentException, IllegalAccessException { + String name = "Fakey McFake"; + User user = new User(name, cred.getBytes(), 61 * SECOND); + Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; + assertThat(user.name, is(name)); + assertThat(user.principal, is(nullValue())); + assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); + assertThat((int)count_field.get(user), is(0)); + assertThat(user.getCred(), is(cred.getBytes())); + } + + @Test + public void countCheckTest() throws IllegalArgumentException, IllegalAccessException { + User user = new User(principal); + user.resetCount(); + assertThat((int)count_field.get(user), is(0)); + user.incCount(); + assertThat((int)count_field.get(user), is(1)); + user.incCount(); + assertThat((int)count_field.get(user), is(2)); + user.resetCount(); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void permTest() throws InterruptedException, IllegalArgumentException, IllegalAccessException { + User user = new User(principal); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + user.renewPerm(); + Thread.sleep(1); // Let it expire + assertThat(user.permExpired(), is(true)); + + user = new User(principal,100); + assertTrue(user.noPerms()); + user.add(permission); + assertFalse(user.permsUnloaded()); + assertFalse(user.noPerms()); + user.setNoPerms(); + assertThat(user.permExpired(), is(false)); + assertTrue(user.permsUnloaded()); + assertTrue(user.noPerms()); + perms_field.set(user, null); + assertTrue(user.permsUnloaded()); + assertTrue(user.noPerms()); + } + + @Test + public void addValuesToNewMapTest() { + User user = new User(principal); + Map newMap = new HashMap<>(); + + assertFalse(user.contains(permission)); + + user.add(newMap, permission); + user.setMap(newMap); + + assertTrue(user.contains(permission)); + + List sink = new ArrayList<>(); + user.copyPermsTo(sink); + + assertThat(sink.size(), is(1)); + assertTrue(sink.contains(permission)); + + assertThat(user.toString(), is("Principal|:NewKey")); + + user.add(newMap, permission2); + user.setMap(newMap); + assertFalse(user.contains(permission2)); + + assertThat(user.toString(), is("Principal|:NewKey2,NewKey")); + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java index 62114189..f8905bb5 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java @@ -37,39 +37,39 @@ import org.onap.aaf.cadi.util.Chmod; public class JU_Chmod { - private File file; - private String filePath; + private File file; + private String filePath; - @Before - public void setup() throws IOException { - file = File.createTempFile("chmod_test", ""); - filePath = file.getAbsolutePath(); - } + @Before + public void setup() throws IOException { + file = File.createTempFile("chmod_test", ""); + filePath = file.getAbsolutePath(); + } - @After - public void tearDown() { - file.delete(); - } + @After + public void tearDown() { + file.delete(); + } - @Test - public void to755Test() throws IOException { - Chmod.to755.chmod(file); - Set set = Files.getPosixFilePermissions(Paths.get(filePath)); - assertThat(PosixFilePermissions.toString(set), is("rwxr-xr-x")); - } + @Test + public void to755Test() throws IOException { + Chmod.to755.chmod(file); + Set set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("rwxr-xr-x")); + } - @Test - public void to644Test() throws IOException { - Chmod.to644.chmod(file); - Set set = Files.getPosixFilePermissions(Paths.get(filePath)); - assertThat(PosixFilePermissions.toString(set), is("rw-r--r--")); - } + @Test + public void to644Test() throws IOException { + Chmod.to644.chmod(file); + Set set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("rw-r--r--")); + } - @Test - public void to400Test() throws IOException { - Chmod.to400.chmod(file); - Set set = Files.getPosixFilePermissions(Paths.get(filePath)); - assertThat(PosixFilePermissions.toString(set), is("r--------")); - } + @Test + public void to400Test() throws IOException { + Chmod.to400.chmod(file); + Set set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("r--------")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_FQI.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_FQI.java index bcd2f776..3daa6cb7 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_FQI.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_FQI.java @@ -30,15 +30,15 @@ import org.onap.aaf.cadi.util.FQI; public class JU_FQI { - @Test - public void reverseDomainTest() { - assertThat(FQI.reverseDomain("user@att.com"), is("com.att")); - } + @Test + public void reverseDomainTest() { + assertThat(FQI.reverseDomain("user@att.com"), is("com.att")); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - FQI fqi = new FQI(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + FQI fqi = new FQI(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java index da3557cb..b3d7797c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java @@ -36,58 +36,58 @@ import org.onap.aaf.cadi.util.JsonOutputStream; public class JU_JsonOutputStream { - private JsonOutputStream jos; - - @Before - public void setup() { - jos = new JsonOutputStream(new ByteArrayOutputStream()); - } - - @Test - public void constructorTest() { - jos = new JsonOutputStream(System.out); - jos = new JsonOutputStream(System.err); - } - - @Test - public void writeTest() throws IOException { - byte[] json = ("{" + - "name: user," + - "password: pass," + - "contact: {" + - "email: user@att.com," + - "phone: 555-5555" + - "}," + - "list: [" + - "item1," + - "item2" + - "],[],{}," + - "list:" + - "[" + - "item1," + - "item2" + - "]" + - "}").getBytes(); - jos.write(json); - } - - @Test - public void resetIndentTest() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - Field indentField = JsonOutputStream.class.getDeclaredField("indent"); - indentField.setAccessible(true); - - assertThat((int)indentField.get(jos), is(0)); - jos.resetIndent(); - assertThat((int)indentField.get(jos), is(1)); - } - - @Test - public void coverageTest() throws IOException { - jos.flush(); - jos.close(); - - jos = new JsonOutputStream(System.out); - jos.close(); - } + private JsonOutputStream jos; + + @Before + public void setup() { + jos = new JsonOutputStream(new ByteArrayOutputStream()); + } + + @Test + public void constructorTest() { + jos = new JsonOutputStream(System.out); + jos = new JsonOutputStream(System.err); + } + + @Test + public void writeTest() throws IOException { + byte[] json = ("{" + + "name: user," + + "password: pass," + + "contact: {" + + "email: user@att.com," + + "phone: 555-5555" + + "}," + + "list: [" + + "item1," + + "item2" + + "],[],{}," + + "list:" + + "[" + + "item1," + + "item2" + + "]" + + "}").getBytes(); + jos.write(json); + } + + @Test + public void resetIndentTest() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + Field indentField = JsonOutputStream.class.getDeclaredField("indent"); + indentField.setAccessible(true); + + assertThat((int)indentField.get(jos), is(0)); + jos.resetIndent(); + assertThat((int)indentField.get(jos), is(1)); + } + + @Test + public void coverageTest() throws IOException { + jos.flush(); + jos.close(); + + jos = new JsonOutputStream(System.out); + jos.close(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java index ea743430..ba03b6b1 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java @@ -30,15 +30,15 @@ import org.onap.aaf.cadi.util.MaskFormatException; public class JU_MaskFormatException { - @Test - public void throwsTest() { - String errorMessage = "This is a MaskFormatException"; - try { - throw new MaskFormatException(errorMessage); - } catch (Exception e) { - assertThat(e.getMessage(), is(errorMessage)); - assertTrue(e instanceof MaskFormatException); - } - } + @Test + public void throwsTest() { + String errorMessage = "This is a MaskFormatException"; + try { + throw new MaskFormatException(errorMessage); + } catch (Exception e) { + assertThat(e.getMessage(), is(errorMessage)); + assertTrue(e instanceof MaskFormatException); + } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java index 403f1f1e..f2e393d9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java @@ -27,39 +27,39 @@ import org.onap.aaf.cadi.util.NetMask; public class JU_NetMask { - @Test - public void deriveTest() { - String test = "test"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } + @Test + public void deriveTest() { + String test = "test"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } - @Test - public void deriveTest2() { - String test = "1.2.3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest3() { - String test = "1.2.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest4() { - String test = "1.3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest5() { - String test = "2.3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest6() { - String test = "3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } + @Test + public void deriveTest2() { + String test = "1.2.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest3() { + String test = "1.2.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest4() { + String test = "1.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest5() { + String test = "2.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest6() { + String test = "3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java index b9f0e997..5862d792 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java @@ -33,127 +33,127 @@ import org.onap.aaf.cadi.util.Pool.*; public class JU_Pool { - private StringBuilder sb = new StringBuilder(); - - private class IntegerCreator implements Creator { - private int current = 0; - - @Override - public Integer create() { - return current++; - } - - @Override - public void destroy(Integer t) { - t = 0; - } - - @Override - public boolean isValid(Integer t) { - return (t & 0x1) == 0; - } - - @Override - public void reuse(Integer t) { - } - } - - private class CustomLogger implements Log { - @Override - public void log(Object... o) { - for (Object item : o) { - sb.append(item.toString()); - } - } - } - - @Test - public void getTest() throws CadiException { - Pool intPool = new Pool(new IntegerCreator()); - - List> gotten = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - gotten.add(intPool.get()); - assertThat(gotten.get(i).content, is(i)); - } - - gotten.get(9).done(); - gotten.set(9, intPool.get()); - assertThat(gotten.get(9).content, is(9)); - - for (int i = 0; i < 10; i++) { - gotten.get(i).done(); - } - - for (int i = 0; i < 10; i++) { - gotten.set(i, intPool.get()); - if (i < 5) { - assertThat(gotten.get(i).content, is(i)); - } else { - assertThat(gotten.get(i).content, is(i + 5)); - } - } - - for (int i = 0; i < 10; i++) { - gotten.get(i).toss(); - // Coverage calls - gotten.get(i).toss(); - gotten.get(i).done(); - - // only set some objects to null -> this is for the finalize coverage test - if (i < 5) { - gotten.set(i, null); - } - } - - // Coverage of finalize() - System.gc(); - } - - @Test - public void bulkTest() throws CadiException { - Pool intPool = new Pool(new IntegerCreator()); - - intPool.prime(10); - // Remove all of the invalid items (in this case, odd numbers) - assertFalse(intPool.validate()); - - // Make sure we got them all - assertTrue(intPool.validate()); - - // Get an item from the pool - Pooled gotten = intPool.get(); - assertThat(gotten.content, is(0)); - - // finalize that item, then check the next one to make sure we actually purged - // the odd numbers - gotten = intPool.get(); - assertThat(gotten.content, is(2)); - - intPool.drain(); - - } - - @Test - public void setMaxTest() { - Pool intPool = new Pool(new IntegerCreator()); - intPool.setMaxRange(10); - assertThat(intPool.getMaxRange(), is(10)); - intPool.setMaxRange(-10); - assertThat(intPool.getMaxRange(), is(0)); - } - - @Test - public void loggingTest() { - Pool intPool = new Pool(new IntegerCreator()); - - // Log to Log.NULL for coverage - intPool.log("Test log output"); - - intPool.setLogger(new CustomLogger()); - intPool.log("Test log output"); - - assertThat(sb.toString(), is("Test log output")); - } + private StringBuilder sb = new StringBuilder(); + + private class IntegerCreator implements Creator { + private int current = 0; + + @Override + public Integer create() { + return current++; + } + + @Override + public void destroy(Integer t) { + t = 0; + } + + @Override + public boolean isValid(Integer t) { + return (t & 0x1) == 0; + } + + @Override + public void reuse(Integer t) { + } + } + + private class CustomLogger implements Log { + @Override + public void log(Object... o) { + for (Object item : o) { + sb.append(item.toString()); + } + } + } + + @Test + public void getTest() throws CadiException { + Pool intPool = new Pool(new IntegerCreator()); + + List> gotten = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + gotten.add(intPool.get()); + assertThat(gotten.get(i).content, is(i)); + } + + gotten.get(9).done(); + gotten.set(9, intPool.get()); + assertThat(gotten.get(9).content, is(9)); + + for (int i = 0; i < 10; i++) { + gotten.get(i).done(); + } + + for (int i = 0; i < 10; i++) { + gotten.set(i, intPool.get()); + if (i < 5) { + assertThat(gotten.get(i).content, is(i)); + } else { + assertThat(gotten.get(i).content, is(i + 5)); + } + } + + for (int i = 0; i < 10; i++) { + gotten.get(i).toss(); + // Coverage calls + gotten.get(i).toss(); + gotten.get(i).done(); + + // only set some objects to null -> this is for the finalize coverage test + if (i < 5) { + gotten.set(i, null); + } + } + + // Coverage of finalize() + System.gc(); + } + + @Test + public void bulkTest() throws CadiException { + Pool intPool = new Pool(new IntegerCreator()); + + intPool.prime(10); + // Remove all of the invalid items (in this case, odd numbers) + assertFalse(intPool.validate()); + + // Make sure we got them all + assertTrue(intPool.validate()); + + // Get an item from the pool + Pooled gotten = intPool.get(); + assertThat(gotten.content, is(0)); + + // finalize that item, then check the next one to make sure we actually purged + // the odd numbers + gotten = intPool.get(); + assertThat(gotten.content, is(2)); + + intPool.drain(); + + } + + @Test + public void setMaxTest() { + Pool intPool = new Pool(new IntegerCreator()); + intPool.setMaxRange(10); + assertThat(intPool.getMaxRange(), is(10)); + intPool.setMaxRange(-10); + assertThat(intPool.getMaxRange(), is(0)); + } + + @Test + public void loggingTest() { + Pool intPool = new Pool(new IntegerCreator()); + + // Log to Log.NULL for coverage + intPool.log("Test log output"); + + intPool.setLogger(new CustomLogger()); + intPool.log("Test log output"); + + assertThat(sb.toString(), is("Test log output")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Split.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Split.java index 12be4e15..8977a4f4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Split.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Split.java @@ -28,86 +28,86 @@ import org.onap.aaf.cadi.util.Split; public class JU_Split { - @Test - public void splitTest() { - String[] output = Split.split('c', "ctestctc", 0, "ctestctc".length()); - assertThat(output.length, is(4)); - assertThat(output[0], is("")); - assertThat(output[1], is("test")); - assertThat(output[2], is("t")); - assertThat(output[3], is("")); - - output = Split.split('c', "ctestctc", 0, 4); - assertThat(output.length, is(2)); - assertThat(output[0], is("")); - assertThat(output[1], is("tes")); + @Test + public void splitTest() { + String[] output = Split.split('c', "ctestctc", 0, "ctestctc".length()); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("test")); + assertThat(output[2], is("t")); + assertThat(output[3], is("")); + + output = Split.split('c', "ctestctc", 0, 4); + assertThat(output.length, is(2)); + assertThat(output[0], is("")); + assertThat(output[1], is("tes")); output = Split.split('c', "test", 0, "test".length()); - assertThat(output.length, is(1)); - assertThat(output[0], is("test")); + assertThat(output.length, is(1)); + assertThat(output[0], is("test")); - assertThat(Split.split('c', null, 0, 0).length, is(0)); + assertThat(Split.split('c', null, 0, 0).length, is(0)); // Test with fewer arguments - output = Split.split('c', "ctestctc"); - assertThat(output.length, is(4)); - assertThat(output[0], is("")); - assertThat(output[1], is("test")); - assertThat(output[2], is("t")); - assertThat(output[3], is("")); - } - - @Test - public void splitTrimTest() { - String[] output = Split.splitTrim('c', " cte stc ctc ", 0, " cte stc ctc ".length()); - assertThat(output.length, is(5)); - assertThat(output[0], is("")); - assertThat(output[1], is("te st")); - assertThat(output[2], is("")); - assertThat(output[3], is("t")); - assertThat(output[4], is("")); - - output = Split.splitTrim('c', " cte stc ctc ", 0, 5); - assertThat(output.length, is(2)); - assertThat(output[0], is("")); - assertThat(output[1], is("te")); - - assertThat(Split.splitTrim('c', " te st ", 0, " te st ".length())[0], is("te st")); + output = Split.split('c', "ctestctc"); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("test")); + assertThat(output[2], is("t")); + assertThat(output[3], is("")); + } + + @Test + public void splitTrimTest() { + String[] output = Split.splitTrim('c', " cte stc ctc ", 0, " cte stc ctc ".length()); + assertThat(output.length, is(5)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + assertThat(output[3], is("t")); + assertThat(output[4], is("")); + + output = Split.splitTrim('c', " cte stc ctc ", 0, 5); + assertThat(output.length, is(2)); + assertThat(output[0], is("")); + assertThat(output[1], is("te")); + + assertThat(Split.splitTrim('c', " te st ", 0, " te st ".length())[0], is("te st")); assertThat(Split.splitTrim('c', null, 0, 0).length, is(0)); - // Test with 2 arguments - output = Split.splitTrim('c', " cte stc ctc "); - assertThat(output.length, is(5)); - assertThat(output[0], is("")); - assertThat(output[1], is("te st")); - assertThat(output[2], is("")); - assertThat(output[3], is("t")); - assertThat(output[4], is("")); - - // Tests with 1 argument - output = Split.splitTrim('c', " cte stc ctc ", 1); - assertThat(output.length, is(1)); - assertThat(output[0], is("cte stc ctc")); - - output = Split.splitTrim('c', "testctest2", 2); - assertThat(output.length, is(2)); - assertThat(output[0], is("test")); - assertThat(output[1], is("test2")); - - output = Split.splitTrim('c', " cte stc ctc ", 4); - assertThat(output.length, is(4)); - assertThat(output[0], is("")); - assertThat(output[1], is("te st")); - assertThat(output[2], is("")); - - assertThat(Split.splitTrim('c', null, 0).length, is(0)); - } - - @Test - public void coverageTest() { - @SuppressWarnings("unused") - Split split = new Split(); - } + // Test with 2 arguments + output = Split.splitTrim('c', " cte stc ctc "); + assertThat(output.length, is(5)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + assertThat(output[3], is("t")); + assertThat(output[4], is("")); + + // Tests with 1 argument + output = Split.splitTrim('c', " cte stc ctc ", 1); + assertThat(output.length, is(1)); + assertThat(output[0], is("cte stc ctc")); + + output = Split.splitTrim('c', "testctest2", 2); + assertThat(output.length, is(2)); + assertThat(output[0], is("test")); + assertThat(output[1], is("test2")); + + output = Split.splitTrim('c', " cte stc ctc ", 4); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + + assertThat(Split.splitTrim('c', null, 0).length, is(0)); + } + + @Test + public void coverageTest() { + @SuppressWarnings("unused") + Split split = new Split(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java index 712b9891..5bc1be21 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java @@ -36,90 +36,90 @@ import org.onap.aaf.cadi.util.SubStandardConsole; public class JU_SubStandardConsole { - private String inputString = "An input string"; - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream errStream; - private String lineSeparator = System.lineSeparator(); - - @Before - public void setup() { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - } - - @After - public void tearDown() { - System.setOut(System.out); - System.setErr(System.err); - } - - @Test - public void readLineTest() { - byte[] input = inputString.getBytes(); - System.setIn(new ByteArrayInputStream(input)); - SubStandardConsole ssc = new SubStandardConsole(); - String output = ssc.readLine("%s" + lineSeparator, ">>> "); - assertThat(output, is(inputString)); - assertThat(outStream.toString(), is(">>> " + lineSeparator)); - } - - @Test - public void readLineTest2() { - byte[] input = inputString.getBytes(); - System.setIn(new ByteArrayInputStream(input)); - SubStandardConsole ssc = new SubStandardConsole(); - String output = ssc.readLine("%s %s" + lineSeparator, ">>> ", "Another argument for coverage"); - assertThat(output, is(inputString)); - } - - @Test - public void readLineTest3() { - byte[] input = "\n".getBytes(); - System.setIn(new ByteArrayInputStream(input)); - SubStandardConsole ssc = new SubStandardConsole(); - String output = ssc.readLine("%s" + lineSeparator, ">>> "); - assertThat(output, is(">>> ")); - assertThat(outStream.toString(), is(">>> " + lineSeparator)); - } - - @Test - public void readPasswordTest() { - byte[] input = inputString.getBytes(); - System.setIn(new ByteArrayInputStream(input)); - SubStandardConsole ssc = new SubStandardConsole(); - char[] output = ssc.readPassword("%s" + lineSeparator, ">>> "); - System.out.println(output); - assertThat(output, is(inputString.toCharArray())); - assertThat(outStream.toString(), is(">>> " + lineSeparator + "An input string" + lineSeparator)); - } - - @Test - public void printfTest() { - byte[] input = inputString.getBytes(); - System.setIn(new ByteArrayInputStream(input)); - SubStandardConsole ssc = new SubStandardConsole(); - ssc.printf("%s", "A format specifier"); - assertThat(outStream.toString(), is("A format specifier")); - } - - @Test - public void throwsTest() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - BufferedReader brMock = mock(BufferedReader.class); - when(brMock.readLine()).thenThrow(new IOException()); - - SubStandardConsole ssc = new SubStandardConsole(); - - Field brField = SubStandardConsole.class.getDeclaredField("br"); - brField.setAccessible(true); - brField.set(ssc, brMock); - - assertThat(ssc.readLine(""), is("")); - assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); + private String inputString = "An input string"; + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + private String lineSeparator = System.lineSeparator(); + + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + System.setErr(System.err); + } + + @Test + public void readLineTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s" + lineSeparator, ">>> "); + assertThat(output, is(inputString)); + assertThat(outStream.toString(), is(">>> " + lineSeparator)); + } + + @Test + public void readLineTest2() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s %s" + lineSeparator, ">>> ", "Another argument for coverage"); + assertThat(output, is(inputString)); + } + + @Test + public void readLineTest3() { + byte[] input = "\n".getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s" + lineSeparator, ">>> "); + assertThat(output, is(">>> ")); + assertThat(outStream.toString(), is(">>> " + lineSeparator)); + } + + @Test + public void readPasswordTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + char[] output = ssc.readPassword("%s" + lineSeparator, ">>> "); + System.out.println(output); + assertThat(output, is(inputString.toCharArray())); + assertThat(outStream.toString(), is(">>> " + lineSeparator + "An input string" + lineSeparator)); + } + + @Test + public void printfTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + ssc.printf("%s", "A format specifier"); + assertThat(outStream.toString(), is("A format specifier")); + } + + @Test + public void throwsTest() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + BufferedReader brMock = mock(BufferedReader.class); + when(brMock.readLine()).thenThrow(new IOException()); + + SubStandardConsole ssc = new SubStandardConsole(); + + Field brField = SubStandardConsole.class.getDeclaredField("br"); + brField.setAccessible(true); + brField.set(ssc, brMock); + + assertThat(ssc.readLine(""), is("")); + assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); errStream.reset(); - assertThat(ssc.readPassword("").length, is(0)); - assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); - } + assertThat(ssc.readPassword("").length, is(0)); + assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java index 40f88a3a..025e3e67 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java @@ -27,8 +27,8 @@ import org.onap.aaf.cadi.util.TheConsole; public class JU_TheConsole { - @Test - public void implemented(){ - assertEquals(TheConsole.implemented(),false); - } + @Test + public void implemented(){ + assertEquals(TheConsole.implemented(),false); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java index 21f8c21b..9e4cd88d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java @@ -29,39 +29,39 @@ import org.onap.aaf.cadi.util.UserChainManip; public class JU_UserChainManip { - @Test - public void build(){ - UserChain.Protocol baseAuth=UserChain.Protocol.BasicAuth; - StringBuilder sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, true); - assertThat(sb.toString(), is("app:id:BasicAuth:AS")); + @Test + public void build(){ + UserChain.Protocol baseAuth=UserChain.Protocol.BasicAuth; + StringBuilder sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, true); + assertThat(sb.toString(), is("app:id:BasicAuth:AS")); - // for coverage - sb = UserChainManip.build(sb, "app", "id", baseAuth, true); - assertThat(sb.toString(), is("app:id:BasicAuth:AS,app:id:BasicAuth")); + // for coverage + sb = UserChainManip.build(sb, "app", "id", baseAuth, true); + assertThat(sb.toString(), is("app:id:BasicAuth:AS,app:id:BasicAuth")); - sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, false); - assertThat(sb.toString(), is("app:id:BasicAuth")); - } + sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, false); + assertThat(sb.toString(), is("app:id:BasicAuth")); + } - @Test - public void idToNSTEST() { - assertThat(UserChainManip.idToNS(null), is("")); - assertThat(UserChainManip.idToNS(""), is("")); - assertThat(UserChainManip.idToNS("something"), is("")); - assertThat(UserChainManip.idToNS("something@@"), is("")); - assertThat(UserChainManip.idToNS("something@@."), is("")); - assertThat(UserChainManip.idToNS("something@com"), is("com")); - assertThat(UserChainManip.idToNS("something@random.com"), is("com.random")); - assertThat(UserChainManip.idToNS("@random.com"), is("com.random")); - assertThat(UserChainManip.idToNS("something@random.com."), is("com.random")); - assertThat(UserChainManip.idToNS("something@..random...com..."), is("com.random")); - assertThat(UserChainManip.idToNS("something@this.random.com"), is("com.random.this")); - } + @Test + public void idToNSTEST() { + assertThat(UserChainManip.idToNS(null), is("")); + assertThat(UserChainManip.idToNS(""), is("")); + assertThat(UserChainManip.idToNS("something"), is("")); + assertThat(UserChainManip.idToNS("something@@"), is("")); + assertThat(UserChainManip.idToNS("something@@."), is("")); + assertThat(UserChainManip.idToNS("something@com"), is("com")); + assertThat(UserChainManip.idToNS("something@random.com"), is("com.random")); + assertThat(UserChainManip.idToNS("@random.com"), is("com.random")); + assertThat(UserChainManip.idToNS("something@random.com."), is("com.random")); + assertThat(UserChainManip.idToNS("something@..random...com..."), is("com.random")); + assertThat(UserChainManip.idToNS("something@this.random.com"), is("com.random.this")); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - UserChainManip ucm = new UserChainManip(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + UserChainManip ucm = new UserChainManip(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java index 551f725d..3eb43df4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java @@ -29,120 +29,120 @@ import org.junit.Test; import org.onap.aaf.cadi.util.Vars; public class JU_Vars { - - @Test - public void coverage() { - @SuppressWarnings("unused") - Vars my_nonstatic_object_for_coverage = new Vars(); - } + + @Test + public void coverage() { + @SuppressWarnings("unused") + Vars my_nonstatic_object_for_coverage = new Vars(); + } - @Test - public void convert() { - String test = "test"; - List list = new ArrayList<>(); - list.add("method"); - assertEquals(Vars.convert(test, list), test); - } + @Test + public void convert() { + String test = "test"; + List list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert(test, list), test); + } - @Test - public void convertTest1() { - List list = new ArrayList<>(); - list.add("method"); - assertEquals(Vars.convert("test", list), "test"); - } + @Test + public void convertTest1() { + List list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert("test", list), "test"); + } - @Test - public void convertTest2() { - List list = new ArrayList<>(); - list.add("method"); - assertEquals(Vars.convert("test", list), "test"); - } + @Test + public void convertTest2() { + List list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert("test", list), "test"); + } - @Test - public void test() { - StringBuilder holder = new StringBuilder(); - String str,bstr; - assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "a","b")); - assertEquals("set a to b",holder.toString()); - assertEquals(str,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "a","b")); - assertEquals("set a to b",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "a","b")); - - holder.setLength(0); - assertEquals(str = "%1=%2",Vars.convert(holder,str, "a","b")); - assertEquals("a=b",holder.toString()); - assertEquals(str,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="%s=%s", "a","b")); - assertEquals("a=b",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "a","b")); - - holder.setLength(0); - assertEquals(str = "%1%2",Vars.convert(holder,str, "a","b")); - assertEquals("ab",holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="%s%s", "a","b")); - assertEquals("ab",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "a","b")); + @Test + public void test() { + StringBuilder holder = new StringBuilder(); + String str,bstr; + assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "a","b")); + assertEquals("set a to b",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "a","b")); + assertEquals("set a to b",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = "%1=%2",Vars.convert(holder,str, "a","b")); + assertEquals("a=b",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="%s=%s", "a","b")); + assertEquals("a=b",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = "%1%2",Vars.convert(holder,str, "a","b")); + assertEquals("ab",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="%s%s", "a","b")); + assertEquals("ab",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); - holder.setLength(0); - assertEquals(str = " %1=%2 ",Vars.convert(holder,str, "a","b")); - assertEquals(" a=b ",holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr = " %s=%s ", "a","b")); - assertEquals(" a=b ",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "a","b")); + holder.setLength(0); + assertEquals(str = " %1=%2 ",Vars.convert(holder,str, "a","b")); + assertEquals(" a=b ",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr = " %s=%s ", "a","b")); + assertEquals(" a=b ",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); - holder.setLength(0); - assertEquals(str = " %1%2%10 ",Vars.convert(holder,str, "a","b","c","d","e","f","g","h","i","j")); - assertEquals(" abj ",holder.toString()); - assertEquals(str,Vars.convert(null,str, "a","b","c","d","e","f","g","h","i","j")); - holder.setLength(0); - assertEquals(str=" %1%2%3 ",Vars.convert(holder,bstr = " %s%s%s ", "a","b","c","d","e","f","g","h","i","j")); - assertEquals(" abc ",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "a","b","c","d","e","f","g","h","i","j")); - + holder.setLength(0); + assertEquals(str = " %1%2%10 ",Vars.convert(holder,str, "a","b","c","d","e","f","g","h","i","j")); + assertEquals(" abj ",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b","c","d","e","f","g","h","i","j")); + holder.setLength(0); + assertEquals(str=" %1%2%3 ",Vars.convert(holder,bstr = " %s%s%s ", "a","b","c","d","e","f","g","h","i","j")); + assertEquals(" abc ",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b","c","d","e","f","g","h","i","j")); + - holder.setLength(0); - assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "Something much","larger")); - assertEquals("set Something much to larger",holder.toString()); - assertEquals(str,Vars.convert(null,str,"Something much","larger")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "Something much","larger")); - assertEquals("set Something much to larger",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "Something much","larger")); + holder.setLength(0); + assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "Something much","larger")); + assertEquals("set Something much to larger",holder.toString()); + assertEquals(str,Vars.convert(null,str,"Something much","larger")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "Something much","larger")); + assertEquals("set Something much to larger",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "Something much","larger")); - holder.setLength(0); - assertEquals(str = "Text without Vars",Vars.convert(holder,str)); - assertEquals(str,holder.toString()); - assertEquals(str = "Text without Vars",Vars.convert(null,str)); - - - holder.setLength(0); - assertEquals(str = "Not %1 Enough %2 Vars %3",Vars.convert(holder,str, "a","b")); - assertEquals("Not a Enough b Vars ",holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="Not %s Enough %s Vars %s", "a","b")); - assertEquals("Not a Enough b Vars ",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "a","b")); + holder.setLength(0); + assertEquals(str = "Text without Vars",Vars.convert(holder,str)); + assertEquals(str,holder.toString()); + assertEquals(str = "Text without Vars",Vars.convert(null,str)); + + + holder.setLength(0); + assertEquals(str = "Not %1 Enough %2 Vars %3",Vars.convert(holder,str, "a","b")); + assertEquals("Not a Enough b Vars ",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="Not %s Enough %s Vars %s", "a","b")); + assertEquals("Not a Enough b Vars ",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); - holder.setLength(0); - assertEquals(str = "!@#$%^*()-+?/,:;.",Vars.convert(holder,str, "a","b")); - assertEquals(str,holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str = "!@#$%^*()-+?/,:;.",Vars.convert(holder,str, "a","b")); + assertEquals(str,holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - bstr = "%s !@#$%^*()-+?/,:;."; - str = "%1 !@#$%^*()-+?/,:;."; - assertEquals(str,Vars.convert(holder,bstr, "Not Acceptable")); - assertEquals("Not Acceptable !@#$%^*()-+?/,:;.",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "Not Acceptable")); - } - + holder.setLength(0); + bstr = "%s !@#$%^*()-+?/,:;."; + str = "%1 !@#$%^*()-+?/,:;."; + assertEquals(str,Vars.convert(holder,bstr, "Not Acceptable")); + assertEquals("Not Acceptable !@#$%^*()-+?/,:;.",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "Not Acceptable")); + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java index 0d7bdc2c..eca34963 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java @@ -26,138 +26,138 @@ import org.onap.aaf.cadi.wsse.WSSEParser; public class JU_WSSEParser { - @Test - public void test() { - @SuppressWarnings("unused") - WSSEParser wp = new WSSEParser(); + @Test + public void test() { + @SuppressWarnings("unused") + WSSEParser wp = new WSSEParser(); - // TODO: test the rest of this class -// final BasicCred bc = new BasicCred() { -// private String user; -// private byte[] password; + // TODO: test the rest of this class +// final BasicCred bc = new BasicCred() { +// private String user; +// private byte[] password; // -// public void setUser(String user) { this.user = user; } -// public void setCred(byte[] passwd) { this.password = passwd; } -// public String getUser() { return user; } -// public byte[] getCred() { return password; } -// }; +// public void setUser(String user) { this.user = user; } +// public void setCred(byte[] passwd) { this.password = passwd; } +// public String getUser() { return user; } +// public byte[] getCred() { return password; } +// }; -// FileInputStream fis; -// fis = new FileInputStream("test/example.xml"); -// BufferedServletInputStream is = new BufferedServletInputStream(fis); -// try { -// is.mark(1536); -// try { -// assertNull(wp.parse(bc, is)); -// } finally { -// is.reset(); -// assertEquals(814,is.buffered()); -// } -// String password = new String(bc.getCred()); -// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); -// assertEquals("some_user", bc.getUser()); -// assertEquals("some_password", password); -// -// } finally { -// fis.close(); -// } +// FileInputStream fis; +// fis = new FileInputStream("test/example.xml"); +// BufferedServletInputStream is = new BufferedServletInputStream(fis); +// try { +// is.mark(1536); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// is.reset(); +// assertEquals(814,is.buffered()); +// } +// String password = new String(bc.getCred()); +// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); +// assertEquals("some_user", bc.getUser()); +// assertEquals("some_password", password); +// +// } finally { +// fis.close(); +// } // -// // CBUS (larger) -// fis = new FileInputStream("test/CBUSevent.xml"); -// is = new BufferedServletInputStream(fis); -// try { -// is.mark(1536); -// try { -// assertNull(wp.parse(bc, is)); -// } finally { -// is.reset(); -// assertEquals(667,is.buffered()); -// } -// String password = new String(bc.getCred()); -// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); -// assertEquals("none", bc.getUser()); -// assertEquals("none", password); -// -// } finally { -// fis.close(); -// } +// // CBUS (larger) +// fis = new FileInputStream("test/CBUSevent.xml"); +// is = new BufferedServletInputStream(fis); +// try { +// is.mark(1536); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// is.reset(); +// assertEquals(667,is.buffered()); +// } +// String password = new String(bc.getCred()); +// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); +// assertEquals("none", bc.getUser()); +// assertEquals("none", password); +// +// } finally { +// fis.close(); +// } // -// // Closed Stream -// fis = new FileInputStream("test/example.xml"); -// fis.close(); -// bc.setCred(null); -// bc.setUser(null); -// XMLStreamException ex = wp.parse(bc, fis); -// assertNotNull(ex); -// assertNull(bc.getUser()); -// assertNull(bc.getCred()); +// // Closed Stream +// fis = new FileInputStream("test/example.xml"); +// fis.close(); +// bc.setCred(null); +// bc.setUser(null); +// XMLStreamException ex = wp.parse(bc, fis); +// assertNotNull(ex); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); // // -// fis = new FileInputStream("test/exampleNoSecurity.xml"); -// try { -// bc.setCred(null); -// bc.setUser(null); -// assertNull(wp.parse(bc, fis)); -// assertNull(bc.getUser()); -// assertNull(bc.getCred()); -// } finally { -// fis.close(); -// } +// fis = new FileInputStream("test/exampleNoSecurity.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } // -// fis = new FileInputStream("test/exampleBad1.xml"); -// try { -// bc.setCred(null); -// bc.setUser(null); -// assertNull(wp.parse(bc, fis)); -// assertNull(bc.getUser()); -// assertNull(bc.getCred()); -// } finally { -// fis.close(); -// } +// fis = new FileInputStream("test/exampleBad1.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } // -// XMLStreamException e = wp.parse(bc, new ByteArrayInputStream("Not XML".getBytes())); // empty -// assertNotNull(e); +// XMLStreamException e = wp.parse(bc, new ByteArrayInputStream("Not XML".getBytes())); // empty +// assertNotNull(e); // -// e = wp.parse(bc, new ByteArrayInputStream("".getBytes())); // empty -// assertNotNull(e); -// -// -// long start, count = 0L; -// int iter = 30000; -// File f = new File("test/CBUSevent.xml"); -// fis = new FileInputStream(f); -// is = new BufferedServletInputStream(fis); -// is.mark(0); -// try { -// while(is.read()>=0); -// } finally { -// fis.close(); -// } +// e = wp.parse(bc, new ByteArrayInputStream("".getBytes())); // empty +// assertNotNull(e); +// +// +// long start, count = 0L; +// int iter = 30000; +// File f = new File("test/CBUSevent.xml"); +// fis = new FileInputStream(f); +// is = new BufferedServletInputStream(fis); +// is.mark(0); +// try { +// while(is.read()>=0); +// } finally { +// fis.close(); +// } // -// for(int i=0;i"); - writer.println(""); - writer.println(""); - writer.println("<" + OUTER_TAG + ">"); - writer.println(" <" + INNER_TAG + ">"); - writer.println(" <" + DATA_TAG + ">" + DATA + ""); - writer.println(" <" + SELF_CLOSING_TAG + " withAnAttribute=\"That has nested \\\" marks\" />"); - writer.println(" <" + PREFIX + ":" + SUFFIX + "/>"); - writer.println(" "); - writer.println(""); - writer.flush(); - writer.close(); - return xmlFile; - } + private final static String TEST_DIR_NAME = "src/test/resources"; + private final static String TEST_XML_NAME = "test.xml"; + private static File testXML; + + private final static String COMMENT = "a comment"; + private final static String OUTER_TAG = "outerTag"; + private final static String INNER_TAG = "innerTag"; + private final static String DATA_TAG = "dataTag"; + private final static String DATA = "some text that represents data"; + private final static String SELF_CLOSING_TAG = "selfClosingTag"; + private final static String PREFIX = "prefix"; + private final static String SUFFIX = "suffix"; + + @BeforeClass + public static void setupOnce() throws IOException { + testXML = setupXMLFile(); + } + + @AfterClass + public static void tearDownOnce() { + testXML.delete(); + } + + @Test + public void test() throws XMLStreamException, IOException { + FileInputStream fis = new FileInputStream(TEST_DIR_NAME + '/' + TEST_XML_NAME); + try { + XReader xr = new XReader(fis); + assertThat(xr.hasNext(), is(true)); + XEvent xe; + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_DOCUMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.COMMENT)); + assertThat(((XEvent.Comment)xe).value, is(COMMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(OUTER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(INNER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(DATA_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.CHARACTERS)); + assertThat(xe.asCharacters().getData().toString(), is(DATA)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(DATA_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(SELF_CLOSING_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(SUFFIX)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(INNER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(OUTER_TAG)); + + assertThat(xr.hasNext(), is(false)); + + } finally { + fis.close(); + } + } + + private static XEvent getNextEvent(XReader xr) throws XMLStreamException { + if (xr.hasNext()) { + return xr.nextEvent(); + } + return null; + } + + private static File setupXMLFile() throws IOException { + File xmlFile = new File(TEST_DIR_NAME, TEST_XML_NAME); + PrintWriter writer = new PrintWriter(xmlFile); + writer.println(" "); // Whitespace before the document - this is for coverage + writer.println(""); + writer.println(""); + writer.println(""); + writer.println("<" + OUTER_TAG + ">"); + writer.println(" <" + INNER_TAG + ">"); + writer.println(" <" + DATA_TAG + ">" + DATA + ""); + writer.println(" <" + SELF_CLOSING_TAG + " withAnAttribute=\"That has nested \\\" marks\" />"); + writer.println(" <" + PREFIX + ":" + SUFFIX + "/>"); + writer.println(" "); + writer.println(""); + writer.flush(); + writer.close(); + return xmlFile; + } } diff --git a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java index 50eaa759..2a1ecdeb 100644 --- a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java +++ b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java @@ -33,24 +33,24 @@ import org.onap.aaf.cadi.oauth.TokenClientFactory; import org.onap.aaf.misc.env.APIException; public class ClientFactory { - private final TokenClientFactory tcf; - public ClientFactory(final PropAccess access) throws APIException, CadiException { - try { - tcf = TokenClientFactory.instance(access); - } catch (GeneralSecurityException | IOException e) { - throw new CadiException(e); - } - } - - public ClientFactory(String[] args) throws APIException, CadiException { - this(new PropAccess(args)); - } + private final TokenClientFactory tcf; + public ClientFactory(final PropAccess access) throws APIException, CadiException { + try { + tcf = TokenClientFactory.instance(access); + } catch (GeneralSecurityException | IOException e) { + throw new CadiException(e); + } + } + + public ClientFactory(String[] args) throws APIException, CadiException { + this(new PropAccess(args)); + } - public SimpleRESTClient simpleRESTClient(final String endpoint, final String ... scopes) throws URISyntaxException, LocatorException, CadiException, APIException { - return new SimpleRESTClient(tcf, Config.AAF_OAUTH2_TOKEN_URL, endpoint, scopes); - } + public SimpleRESTClient simpleRESTClient(final String endpoint, final String ... scopes) throws URISyntaxException, LocatorException, CadiException, APIException { + return new SimpleRESTClient(tcf, Config.AAF_OAUTH2_TOKEN_URL, endpoint, scopes); + } - public Access getAccess() { - return tcf.access; - } + public Access getAccess() { + return tcf.access; + } } diff --git a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java index 95c9fe85..107e1d89 100644 --- a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java +++ b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java @@ -23,44 +23,44 @@ package org.onap.aaf.cadi.enduser; import org.onap.aaf.cadi.client.Future; public class RESTException extends Exception { - /** - * - */ - private static final long serialVersionUID = -5232371598208651058L; - private Future future; + /** + * + */ + private static final long serialVersionUID = -5232371598208651058L; + private Future future; - public RESTException(Future future) { - this.future = future; - } - - public int getCode() { - return future.code(); - } - - public String getMsg() { - return future.body(); - } + public RESTException(Future future) { + this.future = future; + } + + public int getCode() { + return future.code(); + } + + public String getMsg() { + return future.body(); + } - public String errorString() { - String body = future.body(); - return "RESTClient Error: " + future.code() + ": " + (body.isEmpty()?"":body); - } + public String errorString() { + String body = future.body(); + return "RESTClient Error: " + future.code() + ": " + (body.isEmpty()?"":body); + } - /* (non-Javadoc) - * @see java.lang.Throwable#getMessage() - */ - @Override - public String getMessage() { - return errorString(); - } + /* (non-Javadoc) + * @see java.lang.Throwable#getMessage() + */ + @Override + public String getMessage() { + return errorString(); + } - /* (non-Javadoc) - * @see java.lang.Throwable#getLocalizedMessage() - */ - @Override - public String getLocalizedMessage() { - return errorString(); - } - + /* (non-Javadoc) + * @see java.lang.Throwable#getLocalizedMessage() + */ + @Override + public String getLocalizedMessage() { + return errorString(); + } + } diff --git a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java index 30344de5..7c633640 100644 --- a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java +++ b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java @@ -43,266 +43,266 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.util.StringBuilderWriter; public class SimpleRESTClient { - private static final String APPLICATION_JSON = "application/json"; - private static final String[] EMPTY = new String[0]; - private final TokenClient tokenClient; - private final TzClient restClient; - private int callTimeout; - private String client_id; - private String app; - private String chain; - private Headers headers = new Headers() { - @Override - public String[] headers() { - return EMPTY; - }}; - - public SimpleRESTClient(final TokenClientFactory tcf, final String tokenURL, final String endpoint, final String[] scope) throws CadiException, LocatorException, APIException { - callTimeout = Integer.parseInt(tcf.access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); - tokenClient = tcf.newClient(tokenURL); - Result rtt = tokenClient.getToken(scope); - if(rtt.isOK()) { - restClient = tcf.newTzClient(endpoint); - - if((client_id = tcf.access.getProperty(Config.AAF_APPID, null))==null) { - if((client_id = tcf.access.getProperty(Config.CADI_ALIAS, null))==null) { - throw new CadiException(Config.AAF_APPID + " or " + Config.CADI_ALIAS + " needs to be defined"); - } - } - try { - restClient.setToken(client_id,rtt.value); - } catch (IOException e) { - throw new CadiException(e); - } - } else { - throw new CadiException(rtt.error); - } - } - - public SimpleRESTClient timeout(int newTimeout) { - callTimeout = newTimeout; - return this; - } + private static final String APPLICATION_JSON = "application/json"; + private static final String[] EMPTY = new String[0]; + private final TokenClient tokenClient; + private final TzClient restClient; + private int callTimeout; + private String client_id; + private String app; + private String chain; + private Headers headers = new Headers() { + @Override + public String[] headers() { + return EMPTY; + }}; + + public SimpleRESTClient(final TokenClientFactory tcf, final String tokenURL, final String endpoint, final String[] scope) throws CadiException, LocatorException, APIException { + callTimeout = Integer.parseInt(tcf.access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); + tokenClient = tcf.newClient(tokenURL); + Result rtt = tokenClient.getToken(scope); + if(rtt.isOK()) { + restClient = tcf.newTzClient(endpoint); + + if((client_id = tcf.access.getProperty(Config.AAF_APPID, null))==null) { + if((client_id = tcf.access.getProperty(Config.CADI_ALIAS, null))==null) { + throw new CadiException(Config.AAF_APPID + " or " + Config.CADI_ALIAS + " needs to be defined"); + } + } + try { + restClient.setToken(client_id,rtt.value); + } catch (IOException e) { + throw new CadiException(e); + } + } else { + throw new CadiException(rtt.error); + } + } + + public SimpleRESTClient timeout(int newTimeout) { + callTimeout = newTimeout; + return this; + } - //Format:::[:AS][,::]* - public SimpleRESTClient endUser(Principal principal) { - if(principal==null) { - chain = null; - } else { - if(principal instanceof TaggedPrincipal) { - TaggedPrincipal tp = (TaggedPrincipal)principal; - chain = tp.getName() + ':' + (app==null?"":app) + ':' + tp.tag() + ":AS"; - } else { - chain = principal.getName() + (app==null?"":':'+app); - } - } - return this; - } - - /** - * Single Threaded Class for building up content - * @author jg1555 - * - */ - public static class Input { - private static final byte[] EMPTY_STREAM_BYTES = "".getBytes(); + //Format:::[:AS][,::]* + public SimpleRESTClient endUser(Principal principal) { + if(principal==null) { + chain = null; + } else { + if(principal instanceof TaggedPrincipal) { + TaggedPrincipal tp = (TaggedPrincipal)principal; + chain = tp.getName() + ':' + (app==null?"":app) + ':' + tp.tag() + ":AS"; + } else { + chain = principal.getName() + (app==null?"":':'+app); + } + } + return this; + } + + /** + * Single Threaded Class for building up content + * @author jg1555 + * + */ + public static class Input { + private static final byte[] EMPTY_STREAM_BYTES = "".getBytes(); - private String content; - private StringBuilder sb; - - public Input() { - content = null; - sb = null; - } - - public Input(final String content) { - this.content = content; - } - - public void set(final String content) { - this.content = content; - } - - public PrintWriter writer() { - return new PrintWriter(new StringBuilderWriter(builder())); - } - - public StringBuilder builder() { - if(sb==null) { - sb = new StringBuilder(); - content = null; - } - return sb; - } - - /** - * Reuse StringBuilder object - */ - public void clear() { - content = null; - if(sb!=null) { - sb.setLength(0); - } - } - - @Override - public String toString() { - if(content!=null) { - return content; - } else if(sb!=null) { - return sb.toString(); - } else { - return ""; - } - } + private String content; + private StringBuilder sb; + + public Input() { + content = null; + sb = null; + } + + public Input(final String content) { + this.content = content; + } + + public void set(final String content) { + this.content = content; + } + + public PrintWriter writer() { + return new PrintWriter(new StringBuilderWriter(builder())); + } + + public StringBuilder builder() { + if(sb==null) { + sb = new StringBuilder(); + content = null; + } + return sb; + } + + /** + * Reuse StringBuilder object + */ + public void clear() { + content = null; + if(sb!=null) { + sb.setLength(0); + } + } + + @Override + public String toString() { + if(content!=null) { + return content; + } else if(sb!=null) { + return sb.toString(); + } else { + return ""; + } + } - public byte[] getBytes() { - byte[] rv; - if(content==null) { - if(sb==null) { - rv = EMPTY_STREAM_BYTES; - } else { - rv = sb.toString().getBytes(); - } - } else { - rv = content.getBytes(); - } - content = null; - return rv; - } - } + public byte[] getBytes() { + byte[] rv; + if(content==null) { + if(sb==null) { + rv = EMPTY_STREAM_BYTES; + } else { + rv = sb.toString().getBytes(); + } + } else { + rv = content.getBytes(); + } + content = null; + return rv; + } + } - ///////////////////////////////////////////////////////////// - // - // CREATE - // - ///////////////////////////////////////////////////////////// - public void create(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { - post(path,APPLICATION_JSON, input); - } + ///////////////////////////////////////////////////////////// + // + // CREATE + // + ///////////////////////////////////////////////////////////// + public void create(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { + post(path,APPLICATION_JSON, input); + } - public void post(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { - post(path,APPLICATION_JSON, input); - } + public void post(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { + post(path,APPLICATION_JSON, input); + } - public void post(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException { - Future future = restClient.best(new Retryable>() { - @Override - public Future code(Rcli client) throws CadiException, ConnectException, APIException { - return client.create(path, contentType, new ETransfer(input)); - } - }); - if(!future.get(callTimeout)) { - throw new RESTException(future); - } - } + public void post(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException { + Future future = restClient.best(new Retryable>() { + @Override + public Future code(Rcli client) throws CadiException, ConnectException, APIException { + return client.create(path, contentType, new ETransfer(input)); + } + }); + if(!future.get(callTimeout)) { + throw new RESTException(future); + } + } - ///////////////////////////////////////////////////////////// - // - // READ - // - ///////////////////////////////////////////////////////////// - public String read(final String path) throws RESTException, CadiException, LocatorException, APIException { - return get(path,APPLICATION_JSON); - } + ///////////////////////////////////////////////////////////// + // + // READ + // + ///////////////////////////////////////////////////////////// + public String read(final String path) throws RESTException, CadiException, LocatorException, APIException { + return get(path,APPLICATION_JSON); + } - public String get(final String path) throws RESTException, CadiException, LocatorException, APIException { - return get(path,APPLICATION_JSON); - } + public String get(final String path) throws RESTException, CadiException, LocatorException, APIException { + return get(path,APPLICATION_JSON); + } - public String get(final String path, final String accepts) throws RESTException, CadiException, LocatorException, APIException { - Future future = restClient.best(new Retryable>() { - @Override - public Future code(Rcli client) throws CadiException, ConnectException, APIException { - return client.read(path,accepts, headers()); - } - }); - if(future.get(callTimeout)) { - return future.value; - } else { - throw new RESTException(future); - } - } - - ///////////////////////////////////////////////////////////// - // - // UPDATE - // - ///////////////////////////////////////////////////////////// + public String get(final String path, final String accepts) throws RESTException, CadiException, LocatorException, APIException { + Future future = restClient.best(new Retryable>() { + @Override + public Future code(Rcli client) throws CadiException, ConnectException, APIException { + return client.read(path,accepts, headers()); + } + }); + if(future.get(callTimeout)) { + return future.value; + } else { + throw new RESTException(future); + } + } + + ///////////////////////////////////////////////////////////// + // + // UPDATE + // + ///////////////////////////////////////////////////////////// - public String update(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { - return put(path,APPLICATION_JSON, input); - } + public String update(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { + return put(path,APPLICATION_JSON, input); + } - public String put(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { - return put(path,APPLICATION_JSON, input); - } + public String put(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException { + return put(path,APPLICATION_JSON, input); + } - public String put(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException { - Future future = restClient.best(new Retryable>() { - @Override - public Future code(Rcli client) throws CadiException, ConnectException, APIException { - return client.update(path, contentType, new ETransfer(input)); - } - }); - if(future.get(callTimeout)) { - return future.value; - } else { - throw new RESTException(future); - } - } + public String put(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException { + Future future = restClient.best(new Retryable>() { + @Override + public Future code(Rcli client) throws CadiException, ConnectException, APIException { + return client.update(path, contentType, new ETransfer(input)); + } + }); + if(future.get(callTimeout)) { + return future.value; + } else { + throw new RESTException(future); + } + } - ///////////////////////////////////////////////////////////// - // - // DELETE - // - ///////////////////////////////////////////////////////////// - public void delete(final String path) throws RESTException, CadiException, LocatorException, APIException { - delete(path,APPLICATION_JSON); - } - - public void delete(final String path, final String contentType) throws RESTException, CadiException, LocatorException, APIException { - Future future = restClient.best(new Retryable>() { - @Override - public Future code(Rcli client) throws CadiException, ConnectException, APIException { - return client.delete(path, contentType); - } - }); - if(!future.get(callTimeout)) { - throw new RESTException(future); - } - } + ///////////////////////////////////////////////////////////// + // + // DELETE + // + ///////////////////////////////////////////////////////////// + public void delete(final String path) throws RESTException, CadiException, LocatorException, APIException { + delete(path,APPLICATION_JSON); + } + + public void delete(final String path, final String contentType) throws RESTException, CadiException, LocatorException, APIException { + Future future = restClient.best(new Retryable>() { + @Override + public Future code(Rcli client) throws CadiException, ConnectException, APIException { + return client.delete(path, contentType); + } + }); + if(!future.get(callTimeout)) { + throw new RESTException(future); + } + } - ///////////////////////////////////////////////////////////// - - private static class ETransfer implements EClient.Transfer { - private Input input; - public ETransfer(final Input input) { - this.input = input; - } - - @Override - public void transfer(OutputStream os) throws IOException, APIException { - os.write(input.getBytes()); - } - } + ///////////////////////////////////////////////////////////// + + private static class ETransfer implements EClient.Transfer { + private Input input; + public ETransfer(final Input input) { + this.input = input; + } + + @Override + public void transfer(OutputStream os) throws IOException, APIException { + os.write(input.getBytes()); + } + } - public interface Headers { - String[] headers(); - } - - public String[] headers() { - if(chain==null) { - return headers.headers(); - } else { - String[] strs = headers.headers(); - String[] rv = new String[strs.length+2]; - rv[0]=Config.CADI_USER_CHAIN; - rv[1]=chain; - for(int i = 0;i rtt = tc.getToken(ns,"org.onap.test"); - - // Note: you can clear a Token's Disk/Memory presence by - // 1) removing the Token from the "token/outgoing" directory on the O/S - // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set - // tc.clearToken("org.onap.aaf","org.onap.test"); - - // Result Object can be queried for success - if(rtt.isOK()) { - TimedToken token = rtt.value; - print(token); // Take a look at what's in a Token - - // Use this Token in your client calls with "Tokenized Client" (TzClient) - // These should NOT be used cross thread. - TzClient helloClient = tcf.newTzClient(endServicesURL); - helloClient.setToken(client_id, token); - - // This client call style, "best" call with "Retryable" inner class covers finding an available Service - // (when Multi-services exist) for the best service, based (currently) on distance. - // - // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method - // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" - String rv = helloClient.best(new Retryable() { - @Override - public String code(Rcli client) throws CadiException, ConnectException, APIException { - Future future = client.read("hello","text/plain"); - // The "future" calling method allows you to do other processing, such as call more than one backend - // client before picking up the result - // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then - if(future.get(CALL_TIMEOUT)) { - // Client Returned expected value - return future.value; - } else { - throw new APIException(future.code() + future.body()); - } - } - }); - - // You want to do something with returned value. Here, we say "hello" - System.out.printf("\nPositive Response from Hello: %s\n",rv); - - - ////////////////////////////////////////////////////////////////////// - // Scenario 2: - // As a Service, read Introspection information as proof of Authenticated Authorization - ////////////////////////////////////////////////////////////////////// - // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( - // i.e. if(isUserInRole("ns.perm|instance|action")) {... - // - // Here, however, is a way to introspect via Java - // - // now, call Introspect (making sure right URLs are set in properties) - // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) - TokenClient tci = tcf.newClient(tokenIntrospectURL); - tci.client_creds(client_id, client_secret); - Result is = tci.introspect(token.getAccessToken()); - if(is.isOK()) { - // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure - print(is.value); // do something with Introspect Object - } else { - access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", - token.getAccessToken(),rtt.code,rtt.error); - } - } else { - access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); - } - - } catch (CadiException | LocatorException | APIException | IOException e) { - e.printStackTrace(); - } - } - - ///////////////////////////////////////////////////////////// - // Examples of Object Access - ///////////////////////////////////////////////////////////// - private static void print(Token t) { - GregorianCalendar exp_date = new GregorianCalendar(); - exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); - System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", - t.getAccessToken(), - t.getTokenType(), - t.getExpiresIn(), - Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), - t.getScope(), - t.getRefreshToken()); - } - - private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { - System.out.println("Empty Introspect"); - return; - } - Date exp = new Date(ti.getExp()*1000); // seconds - System.out.printf("Introspect\n" - + "\tAccessToken:\t%s\n" - + "\tClient-id:\t%s\n" - + "\tClient Type:\t%s\n" - + "\tActive: \t%s\n" - + "\tUserName:\t%s\n" - + "\tExpires: \t%d (%s)\n" - + "\tScope:\t\t%s\n" - + "\tContent:\t%s\n", - ti.getAccessToken(), - ti.getClientId(), - ti.getClientType(), - ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), - ti.getUsername(), - ti.getExp(), - Chrono.timeStamp(exp), - ti.getScope(), - ti.getContent()==null?"":ti.getContent()); - - System.out.println(); - } + // Now, we can get a Token. Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in + // Note: getToken checks if Token is expired, if so, then refreshes before handing back. + Result rtt = tc.getToken(ns,"org.onap.test"); + + // Note: you can clear a Token's Disk/Memory presence by + // 1) removing the Token from the "token/outgoing" directory on the O/S + // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set + // tc.clearToken("org.onap.aaf","org.onap.test"); + + // Result Object can be queried for success + if(rtt.isOK()) { + TimedToken token = rtt.value; + print(token); // Take a look at what's in a Token + + // Use this Token in your client calls with "Tokenized Client" (TzClient) + // These should NOT be used cross thread. + TzClient helloClient = tcf.newTzClient(endServicesURL); + helloClient.setToken(client_id, token); + + // This client call style, "best" call with "Retryable" inner class covers finding an available Service + // (when Multi-services exist) for the best service, based (currently) on distance. + // + // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method + // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" + String rv = helloClient.best(new Retryable() { + @Override + public String code(Rcli client) throws CadiException, ConnectException, APIException { + Future future = client.read("hello","text/plain"); + // The "future" calling method allows you to do other processing, such as call more than one backend + // client before picking up the result + // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then + if(future.get(CALL_TIMEOUT)) { + // Client Returned expected value + return future.value; + } else { + throw new APIException(future.code() + future.body()); + } + } + }); + + // You want to do something with returned value. Here, we say "hello" + System.out.printf("\nPositive Response from Hello: %s\n",rv); + + + ////////////////////////////////////////////////////////////////////// + // Scenario 2: + // As a Service, read Introspection information as proof of Authenticated Authorization + ////////////////////////////////////////////////////////////////////// + // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( + // i.e. if(isUserInRole("ns.perm|instance|action")) {... + // + // Here, however, is a way to introspect via Java + // + // now, call Introspect (making sure right URLs are set in properties) + // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) + TokenClient tci = tcf.newClient(tokenIntrospectURL); + tci.client_creds(client_id, client_secret); + Result is = tci.introspect(token.getAccessToken()); + if(is.isOK()) { + // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure + print(is.value); // do something with Introspect Object + } else { + access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", + token.getAccessToken(),rtt.code,rtt.error); + } + } else { + access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); + } + + } catch (CadiException | LocatorException | APIException | IOException e) { + e.printStackTrace(); + } + } + + ///////////////////////////////////////////////////////////// + // Examples of Object Access + ///////////////////////////////////////////////////////////// + private static void print(Token t) { + GregorianCalendar exp_date = new GregorianCalendar(); + exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); + System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", + t.getAccessToken(), + t.getTokenType(), + t.getExpiresIn(), + Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), + t.getScope(), + t.getRefreshToken()); + } + + private static void print(Introspect ti) { + if(ti==null || ti.getClientId()==null) { + System.out.println("Empty Introspect"); + return; + } + Date exp = new Date(ti.getExp()*1000); // seconds + System.out.printf("Introspect\n" + + "\tAccessToken:\t%s\n" + + "\tClient-id:\t%s\n" + + "\tClient Type:\t%s\n" + + "\tActive: \t%s\n" + + "\tUserName:\t%s\n" + + "\tExpires: \t%d (%s)\n" + + "\tScope:\t\t%s\n" + + "\tContent:\t%s\n", + ti.getAccessToken(), + ti.getClientId(), + ti.getClientType(), + ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), + ti.getUsername(), + ti.getExp(), + Chrono.timeStamp(exp), + ti.getScope(), + ti.getContent()==null?"":ti.getContent()); + + System.out.println(); + } } diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java index c82a7c5d..657a9b78 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java @@ -50,161 +50,161 @@ import aafoauth.v2_0.Token; public class OnapClientExample { - private static TokenClientFactory tcf; - private static PropAccess access; + private static TokenClientFactory tcf; + private static PropAccess access; - public final static void main(final String args[]) { - // These Objects are expected to be Long-Lived... Construct once - - // Property Access - // This method will allow you to set "cadi_prop_files" (or any other property) on Command line - access = new PropAccess(args); - - // access = PropAccess(); - // Note: This style will load "cadi_prop_files" from VM Args - - // Token aware Client Factory - try { - tcf = TokenClientFactory.instance(access); - } catch (APIException | GeneralSecurityException | IOException | CadiException e1) { - access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast"); - System.exit(1); - } - - final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); - - try { - ////////////////////////////////////////////////////////////////////// - // Scenario 1: - // Get and use an OAuth Client, which understands Token Management - ////////////////////////////////////////////////////////////////////// - // Create a Token Client, that gets its tokens from expected OAuth Server - // In this example, it is AAF, but it can be the Alternate OAuth + public final static void main(final String args[]) { + // These Objects are expected to be Long-Lived... Construct once + + // Property Access + // This method will allow you to set "cadi_prop_files" (or any other property) on Command line + access = new PropAccess(args); + + // access = PropAccess(); + // Note: This style will load "cadi_prop_files" from VM Args + + // Token aware Client Factory + try { + tcf = TokenClientFactory.instance(access); + } catch (APIException | GeneralSecurityException | IOException | CadiException e1) { + access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast"); + System.exit(1); + } + + final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); + + try { + ////////////////////////////////////////////////////////////////////// + // Scenario 1: + // Get and use an OAuth Client, which understands Token Management + ////////////////////////////////////////////////////////////////////// + // Create a Token Client, that gets its tokens from expected OAuth Server + // In this example, it is AAF, but it can be the Alternate OAuth - TokenClient tc = tcf.newClient(Config.AAF_OAUTH2_TOKEN_URL); // can set your own timeout here (url, timeoutMilliseconds) - - // Here's a trick to get the namespace out of a Fully Qualified AAF Identity (your MechID) - String ns = FQI.reverseDomain(tc.client_id()); - System.out.printf("\nNote: The AAF Namespace of FQI (Fully Qualified Identity) %s is %s\n\n",tc.client_id(), ns); + TokenClient tc = tcf.newClient(Config.AAF_OAUTH2_TOKEN_URL); // can set your own timeout here (url, timeoutMilliseconds) + + // Here's a trick to get the namespace out of a Fully Qualified AAF Identity (your MechID) + String ns = FQI.reverseDomain(tc.client_id()); + System.out.printf("\nNote: The AAF Namespace of FQI (Fully Qualified Identity) %s is %s\n\n",tc.client_id(), ns); - // Now, we can get a Token. Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in - // Note: getToken checks if Token is expired, if so, then refreshes before handing back. - Result rtt = tc.getToken(ns,"org.onap.test"); // get multiple scopes - - // Note: you can clear a Token's Disk/Memory presence by - // 1) removing the Token from the "token/outgoing" directory on the O/S - // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set - // tc.clearToken("org.onap.aaf","org.onap.test"); - - // Result Object can be queried for success - if(rtt.isOK()) { - TimedToken token = rtt.value; - print(token); // Take a look at what's in a Token - - // Use this Token in your client calls with "Tokenized Client" (TzClient) - // These should NOT be used cross thread. - // Get Hello Service URL... roll your own in your own world. - final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL,Defaults.HELLO_URL); + // Now, we can get a Token. Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in + // Note: getToken checks if Token is expired, if so, then refreshes before handing back. + Result rtt = tc.getToken(ns,"org.onap.test"); // get multiple scopes + + // Note: you can clear a Token's Disk/Memory presence by + // 1) removing the Token from the "token/outgoing" directory on the O/S + // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set + // tc.clearToken("org.onap.aaf","org.onap.test"); + + // Result Object can be queried for success + if(rtt.isOK()) { + TimedToken token = rtt.value; + print(token); // Take a look at what's in a Token + + // Use this Token in your client calls with "Tokenized Client" (TzClient) + // These should NOT be used cross thread. + // Get Hello Service URL... roll your own in your own world. + final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL,Defaults.HELLO_URL); - TzClient helloClient = tcf.newTzClient(endServicesURL); - helloClient.setToken(tc.client_id(), token); - - // This client call style, "best" call with "Retryable" inner class covers finding an available Service - // (when Multi-services exist) for the best service, based (currently) on distance. - // - // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method - // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" - String rv = helloClient.best(new Retryable() { - @Override - public String code(Rcli client) throws CadiException, ConnectException, APIException { - Future future = client.read("hello","text/plain"); - // The "future" calling method allows you to do other processing, such as call more than one backend - // client before picking up the result - // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then - if(future.get(CALL_TIMEOUT)) { - // Client Returned expected value - return future.value; - } else { - throw new APIException(future.code() + future.body()); - } - } - }); - - // You want to do something with returned value. Here, we say "hello" - System.out.printf("\nPositive Response from Hello: %s\n",rv); - - - ////////////////////////////////////////////////////////////////////// - // Scenario 2: - // As a Service, read Introspection information as proof of Authenticated Authorization - ////////////////////////////////////////////////////////////////////// - // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( - // i.e. if(isUserInRole("ns.perm|instance|action")) {... - // - // Here, however, is a way to introspect via Java - // - // now, call Introspect (making sure right URLs are set in properties) - // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) - TokenClient tci = tcf.newClient(Config.AAF_OAUTH2_INTROSPECT_URL); - Result is = tci.introspect(token.getAccessToken()); - if(is.isOK()) { - // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure - print(is.value); // do something with Introspect Object - } else { - access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", - token.getAccessToken(),rtt.code,rtt.error); - } - } else { - access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); - } - - } catch (CadiException | LocatorException | APIException | IOException e) { - e.printStackTrace(); - } - } - - ///////////////////////////////////////////////////////////// - // Examples of Object Access - ///////////////////////////////////////////////////////////// - private static void print(Token t) { - GregorianCalendar exp_date = new GregorianCalendar(); - exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); - System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", - t.getAccessToken(), - t.getTokenType(), - t.getExpiresIn(), - Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), - t.getScope(), - t.getRefreshToken()); - } - - private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { - System.out.println("Empty Introspect"); - return; - } - Date exp = new Date(ti.getExp()*1000); // seconds - System.out.printf("Introspect\n" - + "\tAccessToken:\t%s\n" - + "\tClient-id:\t%s\n" - + "\tClient Type:\t%s\n" - + "\tActive: \t%s\n" - + "\tUserName:\t%s\n" - + "\tExpires: \t%d (%s)\n" - + "\tScope:\t\t%s\n" - + "\tContent:\t%s\n", - ti.getAccessToken(), - ti.getClientId(), - ti.getClientType(), - ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), - ti.getUsername(), - ti.getExp(), - Chrono.timeStamp(exp), - ti.getScope(), - ti.getContent()==null?"":ti.getContent()); - - System.out.println(); - } + TzClient helloClient = tcf.newTzClient(endServicesURL); + helloClient.setToken(tc.client_id(), token); + + // This client call style, "best" call with "Retryable" inner class covers finding an available Service + // (when Multi-services exist) for the best service, based (currently) on distance. + // + // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method + // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" + String rv = helloClient.best(new Retryable() { + @Override + public String code(Rcli client) throws CadiException, ConnectException, APIException { + Future future = client.read("hello","text/plain"); + // The "future" calling method allows you to do other processing, such as call more than one backend + // client before picking up the result + // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then + if(future.get(CALL_TIMEOUT)) { + // Client Returned expected value + return future.value; + } else { + throw new APIException(future.code() + future.body()); + } + } + }); + + // You want to do something with returned value. Here, we say "hello" + System.out.printf("\nPositive Response from Hello: %s\n",rv); + + + ////////////////////////////////////////////////////////////////////// + // Scenario 2: + // As a Service, read Introspection information as proof of Authenticated Authorization + ////////////////////////////////////////////////////////////////////// + // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( + // i.e. if(isUserInRole("ns.perm|instance|action")) {... + // + // Here, however, is a way to introspect via Java + // + // now, call Introspect (making sure right URLs are set in properties) + // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) + TokenClient tci = tcf.newClient(Config.AAF_OAUTH2_INTROSPECT_URL); + Result is = tci.introspect(token.getAccessToken()); + if(is.isOK()) { + // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure + print(is.value); // do something with Introspect Object + } else { + access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", + token.getAccessToken(),rtt.code,rtt.error); + } + } else { + access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); + } + + } catch (CadiException | LocatorException | APIException | IOException e) { + e.printStackTrace(); + } + } + + ///////////////////////////////////////////////////////////// + // Examples of Object Access + ///////////////////////////////////////////////////////////// + private static void print(Token t) { + GregorianCalendar exp_date = new GregorianCalendar(); + exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); + System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", + t.getAccessToken(), + t.getTokenType(), + t.getExpiresIn(), + Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), + t.getScope(), + t.getRefreshToken()); + } + + private static void print(Introspect ti) { + if(ti==null || ti.getClientId()==null) { + System.out.println("Empty Introspect"); + return; + } + Date exp = new Date(ti.getExp()*1000); // seconds + System.out.printf("Introspect\n" + + "\tAccessToken:\t%s\n" + + "\tClient-id:\t%s\n" + + "\tClient Type:\t%s\n" + + "\tActive: \t%s\n" + + "\tUserName:\t%s\n" + + "\tExpires: \t%d (%s)\n" + + "\tScope:\t\t%s\n" + + "\tContent:\t%s\n", + ti.getAccessToken(), + ti.getClientId(), + ti.getClientType(), + ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), + ti.getUsername(), + ti.getExp(), + Chrono.timeStamp(exp), + ti.getScope(), + ti.getContent()==null?"":ti.getContent()); + + System.out.println(); + } } diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java index 6cabc654..27f9198a 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java @@ -35,185 +35,185 @@ import org.onap.aaf.misc.env.APIException; public class SimpleRestClientExample { - public final static void main(final String args[]) throws URISyntaxException, LocatorException { - try { - // Note: Expect ClientFactory to be long-lived... do NOT create more than once. - ClientFactory cf = new ClientFactory(args); - - - String urlString = cf.getAccess().getProperty("myurl", null); - if(urlString==null) { - System.out.println("Note: In your startup, add \"myurl=https://:8130\" to command line\n\t" - + "OR\n\t" - + " add -Dmyurl=https://:8130 to VM Args\n\t" - + "where \"aaf hello machine\" is an aaf Installation you know about."); - } else { - - SimpleRESTClient restClient = cf.simpleRESTClient(urlString,"org.osaaf.aaf"); - - ///////////////////////////////////////////////////////////// - // - // Creating Content for CREATE/UPDATE - // - ///////////////////////////////////////////////////////////// - // Create an object that can be reusable IN THIS THREAD ONLY... Not Thread-safe on purpose - Input input = new SimpleRESTClient.Input(); - - // Note: alternate use is to set the input object to an already created String - // Input input = new SimpleRESTClient.Input(aString); - - PrintWriter pw = input.writer(); - pw.print("{\"something\": ["); - for(int i=0;i<4;++i) { - if(i>0) { - pw.print(','); - } - pw.print("{\"myint\":"); - pw.print(i); - pw.print('}'); - } - pw.println("]}"); - - // You can check or log the content - String content = input.toString(); - System.out.println(content); - - // Good form for Writers is that you should close it... - pw.close(); - - ///////////////////////////////////////////////////////////// - // - // CREATE/POST - // - ///////////////////////////////////////////////////////////// - System.out.println("-------- START REST CREATE/UPDATE --------"); - try { - restClient.create("resthello/rest_id", input); - // No Error code, it worked. - System.out.println("No Error Code, Create worked..."); - } catch (RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - } finally { - System.out.println("-------- END REST CREATE/UPDATE --------"); - } - - - ///////////////////////////////////////////////////////////// - // - // READ/GET - // - ///////////////////////////////////////////////////////////// - - // Make some calls. Note that RESTException is thrown if Call does not complete. - // RESTException has HTTP Code and any Message sent from Server - System.out.println("-------- START REST READ/GET --------"); - boolean expectException = false; - try { - - // Call with no Queries - String rv = restClient.get("resthello/rest_id"); - System.out.println(rv); - - // Same call with "read" style - rv = restClient.read("resthello/rest_id"); - System.out.println(rv); - - - // Call with Queries - rv = restClient.get("resthello/rest_id?perm=org.osaaf.people|*|read"); - System.out.println(rv); - - // Call setting ID from principal coming from Trans - // Pretend Transaction - HRequest req = new HRequest("demo@people.osaaf.org"); // Pretend Trans has Jonathan as Identity - - // Call with RESTException, which allows obtaining HTTPCode and any Error message sent - rv = restClient.endUser(req.userPrincipal()).get("resthello/rest_id?perm=org.osaaf.people|*|read"); - System.out.println(rv); - - // Expect Exception here. - System.out.println("-------- START Expecting Exception starting here --------"); - expectException = true; - restClient.get("notAnAPI"); - } catch(RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - System.out.println(e.getMessage()); - System.out.println(e.getLocalizedMessage()); - System.out.println(e); - } finally { - if(expectException) { - System.out.println("-------- END Expecting Exception starting here --------"); - } - System.out.println("-------- END REST READ/GET --------"); - } - - ///////////////////////////////////////////////////////////// - // - // UPDATE/PUT - // - ///////////////////////////////////////////////////////////// - - - // If you use "input" object again as a writer, you can clear it on the same thread, and go again - input.clear(); - // Here we just set to a String, instead of Writing - input.set("{\"something\" : []}"); - - System.out.println("-------- END REST UPDATE/PUT --------"); - try { - String rv = restClient.update("resthello/rest_id", input); - // No Error code, it worked. REST Update will return the updated Data - System.out.println("Update worked"); - System.out.println(rv); - } catch (RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - } finally { - System.out.println("-------- END REST UPDATE/PUT --------"); - } - - ///////////////////////////////////////////////////////////// - // - // DELETE - // - ///////////////////////////////////////////////////////////// - - System.out.println("-------- START REST DELETE --------"); - try { - restClient.delete("resthello/rest_id"); - // No Error code, it worked. REST Update will return the updated Data - System.out.println("Delete worked"); - } catch (RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - } finally { - System.out.println("-------- END REST DELETE --------"); - } - } - } catch (CadiException | APIException e) { - e.printStackTrace(); - } - } - - private static class HRequest { - - public HRequest(String fqi) { - name = fqi; - } - protected final String name; - - // fake out HttpServletRequest, only for get Principal - public Principal userPrincipal() { - return new Principal() { - - @Override - public String getName() { - return name; - } - - }; - } - } + public final static void main(final String args[]) throws URISyntaxException, LocatorException { + try { + // Note: Expect ClientFactory to be long-lived... do NOT create more than once. + ClientFactory cf = new ClientFactory(args); + + + String urlString = cf.getAccess().getProperty("myurl", null); + if(urlString==null) { + System.out.println("Note: In your startup, add \"myurl=https://:8130\" to command line\n\t" + + "OR\n\t" + + " add -Dmyurl=https://:8130 to VM Args\n\t" + + "where \"aaf hello machine\" is an aaf Installation you know about."); + } else { + + SimpleRESTClient restClient = cf.simpleRESTClient(urlString,"org.osaaf.aaf"); + + ///////////////////////////////////////////////////////////// + // + // Creating Content for CREATE/UPDATE + // + ///////////////////////////////////////////////////////////// + // Create an object that can be reusable IN THIS THREAD ONLY... Not Thread-safe on purpose + Input input = new SimpleRESTClient.Input(); + + // Note: alternate use is to set the input object to an already created String + // Input input = new SimpleRESTClient.Input(aString); + + PrintWriter pw = input.writer(); + pw.print("{\"something\": ["); + for(int i=0;i<4;++i) { + if(i>0) { + pw.print(','); + } + pw.print("{\"myint\":"); + pw.print(i); + pw.print('}'); + } + pw.println("]}"); + + // You can check or log the content + String content = input.toString(); + System.out.println(content); + + // Good form for Writers is that you should close it... + pw.close(); + + ///////////////////////////////////////////////////////////// + // + // CREATE/POST + // + ///////////////////////////////////////////////////////////// + System.out.println("-------- START REST CREATE/UPDATE --------"); + try { + restClient.create("resthello/rest_id", input); + // No Error code, it worked. + System.out.println("No Error Code, Create worked..."); + } catch (RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + } finally { + System.out.println("-------- END REST CREATE/UPDATE --------"); + } + + + ///////////////////////////////////////////////////////////// + // + // READ/GET + // + ///////////////////////////////////////////////////////////// + + // Make some calls. Note that RESTException is thrown if Call does not complete. + // RESTException has HTTP Code and any Message sent from Server + System.out.println("-------- START REST READ/GET --------"); + boolean expectException = false; + try { + + // Call with no Queries + String rv = restClient.get("resthello/rest_id"); + System.out.println(rv); + + // Same call with "read" style + rv = restClient.read("resthello/rest_id"); + System.out.println(rv); + + + // Call with Queries + rv = restClient.get("resthello/rest_id?perm=org.osaaf.people|*|read"); + System.out.println(rv); + + // Call setting ID from principal coming from Trans + // Pretend Transaction + HRequest req = new HRequest("demo@people.osaaf.org"); // Pretend Trans has Jonathan as Identity + + // Call with RESTException, which allows obtaining HTTPCode and any Error message sent + rv = restClient.endUser(req.userPrincipal()).get("resthello/rest_id?perm=org.osaaf.people|*|read"); + System.out.println(rv); + + // Expect Exception here. + System.out.println("-------- START Expecting Exception starting here --------"); + expectException = true; + restClient.get("notAnAPI"); + } catch(RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + System.out.println(e.getMessage()); + System.out.println(e.getLocalizedMessage()); + System.out.println(e); + } finally { + if(expectException) { + System.out.println("-------- END Expecting Exception starting here --------"); + } + System.out.println("-------- END REST READ/GET --------"); + } + + ///////////////////////////////////////////////////////////// + // + // UPDATE/PUT + // + ///////////////////////////////////////////////////////////// + + + // If you use "input" object again as a writer, you can clear it on the same thread, and go again + input.clear(); + // Here we just set to a String, instead of Writing + input.set("{\"something\" : []}"); + + System.out.println("-------- END REST UPDATE/PUT --------"); + try { + String rv = restClient.update("resthello/rest_id", input); + // No Error code, it worked. REST Update will return the updated Data + System.out.println("Update worked"); + System.out.println(rv); + } catch (RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + } finally { + System.out.println("-------- END REST UPDATE/PUT --------"); + } + + ///////////////////////////////////////////////////////////// + // + // DELETE + // + ///////////////////////////////////////////////////////////// + + System.out.println("-------- START REST DELETE --------"); + try { + restClient.delete("resthello/rest_id"); + // No Error code, it worked. REST Update will return the updated Data + System.out.println("Delete worked"); + } catch (RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + } finally { + System.out.println("-------- END REST DELETE --------"); + } + } + } catch (CadiException | APIException e) { + e.printStackTrace(); + } + } + + private static class HRequest { + + public HRequest(String fqi) { + name = fqi; + } + protected final String name; + + // fake out HttpServletRequest, only for get Principal + public Principal userPrincipal() { + return new Principal() { + + @Override + public String getName() { + return name; + } + + }; + } + } } diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java index 466c02da..f11d8f89 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java @@ -36,91 +36,91 @@ import org.onap.aaf.cadi.client.Future; import org.onap.aaf.cadi.principal.TaggedPrincipal; // Uncomment if you utilized the "MiniJASPIWrap" in the Servlet setup in "main()", and want to protect your service via Permission or mapped role -// @RolesAllowed({"com.att.aaf.myPerm|myInstance|myAction"}) - public class MyServlet implements Servlet { - private ServletConfig servletConfig; - - public void init(ServletConfig config) throws ServletException { - servletConfig = config; - } - - public ServletConfig getServletConfig() { - return servletConfig; - } - - public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { - HttpServletRequest request; - try { - request = (HttpServletRequest)req; - } catch (ClassCastException e) { - throw new ServletException("Only serving HTTP today",e); - } - - res.getOutputStream().println("
    CSP Servlet Test

    You're good to go!

    " +
    -					request.getUserPrincipal());
    -			
    -			String perm = request.getParameter("PERM");
    -			if(perm!=null) {
    -				if(request.isUserInRole(perm)) {
    -					if(perm.indexOf('|')<0) { 
    -						res.getOutputStream().println("\nCongrats!, You are in Role " + perm);
    -					} else { 
    -						res.getOutputStream().println("\nCongrats!, You have Permission " + perm);
    -					}
    -				} else {
    -					if(perm.indexOf('|')<0) { 
    -						res.getOutputStream().println("\nSorry, you are NOT in Role " + perm);
    -					} else {
    -						res.getOutputStream().println("\nSorry, you do NOT have Permission " + perm);
    -					}
    -				}
    -			}
    -			
    -			// You can get the working AAFCon from Trans
    -			AAFCon aafcon = AAFCon.obtain(req);
    -			if(aafcon!=null) {
    -				try {
    -					res.getOutputStream().println("----- Perms JSON from direct call -----");
    -					final Principal up = request.getUserPrincipal();
    -					TaggedPrincipal tp;
    -					if(up instanceof TaggedPrincipal) {
    -						tp = (TaggedPrincipal)up;
    -					} else {
    -						tp = new TaggedPrincipal() {
    -							@Override
    -							public String getName() {
    -								return up.getName();
    -							}
    +//    @RolesAllowed({"com.att.aaf.myPerm|myInstance|myAction"})
    +    public class MyServlet implements Servlet {
    +        private ServletConfig servletConfig;
    +    
    +        public void init(ServletConfig config) throws ServletException {
    +            servletConfig = config;
    +        }
    +    
    +        public ServletConfig getServletConfig() {
    +            return servletConfig;
    +        }
    +    
    +        public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    +            HttpServletRequest request;
    +            try {
    +                request = (HttpServletRequest)req;
    +            } catch (ClassCastException e) {
    +                throw new ServletException("Only serving HTTP today",e);
    +            }
    +            
    +            res.getOutputStream().println("
    CSP Servlet Test

    You're good to go!

    " +
    +                    request.getUserPrincipal());
    +            
    +            String perm = request.getParameter("PERM");
    +            if(perm!=null) {
    +                if(request.isUserInRole(perm)) {
    +                    if(perm.indexOf('|')<0) { 
    +                        res.getOutputStream().println("\nCongrats!, You are in Role " + perm);
    +                    } else { 
    +                        res.getOutputStream().println("\nCongrats!, You have Permission " + perm);
    +                    }
    +                } else {
    +                    if(perm.indexOf('|')<0) { 
    +                        res.getOutputStream().println("\nSorry, you are NOT in Role " + perm);
    +                    } else {
    +                        res.getOutputStream().println("\nSorry, you do NOT have Permission " + perm);
    +                    }
    +                }
    +            }
    +            
    +            // You can get the working AAFCon from Trans
    +            AAFCon aafcon = AAFCon.obtain(req);
    +            if(aafcon!=null) {
    +                try {
    +                    res.getOutputStream().println("----- Perms JSON from direct call -----");
    +                    final Principal up = request.getUserPrincipal();
    +                    TaggedPrincipal tp;
    +                    if(up instanceof TaggedPrincipal) {
    +                        tp = (TaggedPrincipal)up;
    +                    } else {
    +                        tp = new TaggedPrincipal() {
    +                            @Override
    +                            public String getName() {
    +                                return up.getName();
    +                            }
     
    -							@Override
    -							public String tag() {
    -								return "Unknown";
    -							}
    -						};
    -					}
    -					// This call will be "as the user calling", but only if permission is set to trust.
    -//					Future future = aafcon.clientAs("2.0",tp).read("/authz/perms/user/"+request.getUserPrincipal().getName(),"application/Perms+json");
    -					Future future = aafcon.client("2.0").read("/authz/perms/user/"+request.getUserPrincipal().getName(),"application/Perms+json");
    -					if(future.get(4000 /* timeout */)) {
    -						res.getOutputStream().print(future.value);
    -					} else {
    -						System.err.println(future.code() + ", " + future.body());
    -						res.getOutputStream().print(future.code() + ", " + future.body());
    -					}
    -				} catch (Exception e) {
    -					e.printStackTrace();
    -				}
    -			} else {
    -				res.getOutputStream().println("No AAFCon instantiated");
    -			}
    -			res.getOutputStream().print("
    "); - - } - - public String getServletInfo() { - return "MyServlet"; - } - - public void destroy() { - } - } \ No newline at end of file + @Override + public String tag() { + return "Unknown"; + } + }; + } + // This call will be "as the user calling", but only if permission is set to trust. +// Future future = aafcon.clientAs("2.0",tp).read("/authz/perms/user/"+request.getUserPrincipal().getName(),"application/Perms+json"); + Future future = aafcon.client("2.0").read("/authz/perms/user/"+request.getUserPrincipal().getName(),"application/Perms+json"); + if(future.get(4000 /* timeout */)) { + res.getOutputStream().print(future.value); + } else { + System.err.println(future.code() + ", " + future.body()); + res.getOutputStream().print(future.code() + ", " + future.body()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } else { + res.getOutputStream().println("No AAFCon instantiated"); + } + res.getOutputStream().print("
    "); + + } + + public String getServletInfo() { + return "MyServlet"; + } + + public void destroy() { + } + } \ No newline at end of file diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/Config.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/Config.java index 17f9b198..a45725d7 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/Config.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/Config.java @@ -31,15 +31,15 @@ import org.onap.aaf.cadi.filter.CadiFilter; public class Config { - /** - * Method to make jetty configurations (others?) with more complex function possible - * - * @param sc - */ - public static final void addToContext(WebAppContext sc, String propFile) { - sc.addFilter(CadiFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST)); - sc.setInitParameter(org.onap.aaf.cadi.config.Config.CADI_PROP_FILES, propFile); - } - + /** + * Method to make jetty configurations (others?) with more complex function possible + * + * @param sc + */ + public static final void addToContext(WebAppContext sc, String propFile) { + sc.addFilter(CadiFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST)); + sc.setInitParameter(org.onap.aaf.cadi.config.Config.CADI_PROP_FILES, propFile); + } + } diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java index 2d1fc097..cec8a539 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java @@ -43,70 +43,70 @@ import org.onap.aaf.cadi.config.SecurityInfo; import org.onap.aaf.cadi.filter.CadiFilter; public abstract class JettyServletServer implements Servlet { - - public static Server run(PropAccess access, String context, Class servletCls, int port, String ...args) throws Exception { - // Defaults: - int blockingQueueSize = 10; + + public static Server run(PropAccess access, String context, Class servletCls, int port, String ...args) throws Exception { + // Defaults: + int blockingQueueSize = 10; int corePoolSize = 10; int maxPoolSize = 10; int keepAliveTime = 3000; - String hostname = access.getProperty(Config.HOSTNAME, null); - if(hostname==null) { - hostname = Inet4Address.getLocalHost().getHostName(); - } + String hostname = access.getProperty(Config.HOSTNAME, null); + if(hostname==null) { + hostname = Inet4Address.getLocalHost().getHostName(); + } // Add your own Properties to override defaults ArrayBlockingQueue queue = new ArrayBlockingQueue(blockingQueueSize); QueuedThreadPool pool = new QueuedThreadPool(maxPoolSize,corePoolSize,keepAliveTime,queue); - Server server = new Server(pool); + Server server = new Server(pool); - String protocol; - if(access.getProperty(Config.CADI_KEYSTORE_PASSWORD,null)==null) { - ServerConnector conn = new ServerConnector(server); - conn.setHost(hostname); - conn.setPort(port); - server.addConnector(conn); - protocol = "http"; - } else { - // Setup Security - SecurityInfo securityInfo = new SecurityInfo(access); - SslContextFactory scf = new SslContextFactory(); - scf.setSslContext(securityInfo.getSSLContext()); - scf.setWantClientAuth(true); - ServerConnector sslConnector = new ServerConnector(server,scf); - sslConnector.setHost(hostname); - sslConnector.setPort(port); - server.addConnector(sslConnector); - protocol = "https"; - } + String protocol; + if(access.getProperty(Config.CADI_KEYSTORE_PASSWORD,null)==null) { + ServerConnector conn = new ServerConnector(server); + conn.setHost(hostname); + conn.setPort(port); + server.addConnector(conn); + protocol = "http"; + } else { + // Setup Security + SecurityInfo securityInfo = new SecurityInfo(access); + SslContextFactory scf = new SslContextFactory(); + scf.setSslContext(securityInfo.getSSLContext()); + scf.setWantClientAuth(true); + ServerConnector sslConnector = new ServerConnector(server,scf); + sslConnector.setHost(hostname); + sslConnector.setPort(port); + server.addConnector(sslConnector); + protocol = "https"; + } // Setup Sample Servlet CadiFilter cf = new CadiFilter(true,access); - FilterHolder cfh = new FilterHolder(cf); - - ServletHandler shand = new ServletHandler(); - shand.addFilterWithMapping(cfh, "/*", FilterMapping.ALL); - // To use normal Servlets, just add the class here... Actually, bug in Jetty... need to add with ServletHolder - ServletHolder sh = new ServletHolder(); - sh.setServlet(servletCls.newInstance()); - shand.addServletWithMapping(sh,"/*"); - - // To use JASPI Authorization Style to protect the servlet, wrap the Servlet - // with the "MiniJSAPIWrap class, as shown here. Then add "@RolesAllowed" on your - // servlet (see sample). Use Pipe delimited Permissions, not AAF Roles in the line - // shand.addServletWithMapping(new MiniJASPIWrap(MyServlet.class),"/*"); - // call initialize after start - ContextHandler ch = new ServletContextHandler(); - ch.setContextPath(context); - ch.setHandler(shand); - server.setHandler(ch); - // Startup the Server + FilterHolder cfh = new FilterHolder(cf); + + ServletHandler shand = new ServletHandler(); + shand.addFilterWithMapping(cfh, "/*", FilterMapping.ALL); + // To use normal Servlets, just add the class here... Actually, bug in Jetty... need to add with ServletHolder + ServletHolder sh = new ServletHolder(); + sh.setServlet(servletCls.newInstance()); + shand.addServletWithMapping(sh,"/*"); + + // To use JASPI Authorization Style to protect the servlet, wrap the Servlet + // with the "MiniJSAPIWrap class, as shown here. Then add "@RolesAllowed" on your + // servlet (see sample). Use Pipe delimited Permissions, not AAF Roles in the line + // shand.addServletWithMapping(new MiniJASPIWrap(MyServlet.class),"/*"); + // call initialize after start + ContextHandler ch = new ServletContextHandler(); + ch.setContextPath(context); + ch.setHandler(shand); + server.setHandler(ch); + // Startup the Server server.setStopAtShutdown(true); server.start(); access.log(Level.INFO,"TestServlet is running at " + protocol + "://"+hostname+':'+port+context); return server; - } + } } diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyStandalone.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyStandalone.java index 049e45e8..6edd6f5b 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyStandalone.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyStandalone.java @@ -30,17 +30,17 @@ import org.onap.aaf.cadi.PropAccess; public class JettyStandalone { - public static void main(String[] args) { - PropAccess access = new PropAccess(args); - try { - Server server = JettyServletServer.run(access, "/caditest", MyServlet.class, 3456); - server.join(); - } catch (Exception e) { - access.log(Level.ERROR, e); - } finally { - access.log(Level.INFO,"Stopping Service"); - } - - } + public static void main(String[] args) { + PropAccess access = new PropAccess(args); + try { + Server server = JettyServletServer.run(access, "/caditest", MyServlet.class, 3456); + server.join(); + } catch (Exception e) { + access.log(Level.ERROR, e); + } finally { + access.log(Level.INFO,"Stopping Service"); + } + + } } diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java index 904f3cdc..29462cfb 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java @@ -48,54 +48,54 @@ import org.onap.aaf.cadi.filter.RolesAllowed; * */ public class MiniJASPIWrap extends ServletHolder { - private RolesAllowed rolesAllowed; - //private String roles; - public MiniJASPIWrap(Class servlet) { - super(servlet); - this.rolesAllowed = servlet.getAnnotation(RolesAllowed.class); - StringBuilder sb = new StringBuilder(); - boolean first = true; - if(rolesAllowed!=null) { - for(String str : rolesAllowed.value()) { - if(first)first=false; - else sb.append(','); - sb.append(str); - } - } - //roles = sb.toString(); - } + private RolesAllowed rolesAllowed; + //private String roles; + public MiniJASPIWrap(Class servlet) { + super(servlet); + this.rolesAllowed = servlet.getAnnotation(RolesAllowed.class); + StringBuilder sb = new StringBuilder(); + boolean first = true; + if(rolesAllowed!=null) { + for(String str : rolesAllowed.value()) { + if(first)first=false; + else sb.append(','); + sb.append(str); + } + } + //roles = sb.toString(); + } - /** - * handle - * - * When utilized, this class authorizes the transaction by first calling the standard J2EE API call - * "isUserInRole" with the role(s) found in the class Annotations (JASPI Style) - */ - @Override - public void handle(Request baseRequest, ServletRequest request, ServletResponse response) throws ServletException, UnavailableException, IOException { - if(rolesAllowed==null) { - super.handle(baseRequest, request, response); - } else { // Validate - try { - - HttpServletRequest hreq = (HttpServletRequest)request; - boolean proceed = false; - for(String role : rolesAllowed.value()) { - if(hreq.isUserInRole(role)) { - proceed = true; - break; - } - } - if(proceed) { - super.handle(baseRequest, request, response); - } else { - //baseRequest.getServletContext().log(hreq.getUserPrincipal().getName()+" Refused " + roles); - ((HttpServletResponse)response).sendError(403); // forbidden - } - } catch(ClassCastException e) { - throw new ServletException("JASPIWrap only supports HTTPServletRequest/HttpServletResponse"); - } - } - } + /** + * handle + * + * When utilized, this class authorizes the transaction by first calling the standard J2EE API call + * "isUserInRole" with the role(s) found in the class Annotations (JASPI Style) + */ + @Override + public void handle(Request baseRequest, ServletRequest request, ServletResponse response) throws ServletException, UnavailableException, IOException { + if(rolesAllowed==null) { + super.handle(baseRequest, request, response); + } else { // Validate + try { + + HttpServletRequest hreq = (HttpServletRequest)request; + boolean proceed = false; + for(String role : rolesAllowed.value()) { + if(hreq.isUserInRole(role)) { + proceed = true; + break; + } + } + if(proceed) { + super.handle(baseRequest, request, response); + } else { + //baseRequest.getServletContext().log(hreq.getUserPrincipal().getName()+" Refused " + roles); + ((HttpServletResponse)response).sendError(403); // forbidden + } + } catch(ClassCastException e) { + throw new ServletException("JASPIWrap only supports HTTPServletRequest/HttpServletResponse"); + } + } + } } diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java index 415283a5..1597dbd5 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java @@ -39,7 +39,7 @@ import org.onap.aaf.cadi.PropAccess; */ public class TomcatEmbedded { - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true"); Tomcat tomcat = new Tomcat(); @@ -51,8 +51,8 @@ public class TomcatEmbedded { tomcat.start(); tomcat.getServer().await(); - } - + } + private static Connector getSslConnector(PropAccess access, int port) throws IOException { Connector connector = new Connector(); connector.setPort(port); @@ -75,34 +75,34 @@ public class TomcatEmbedded { } private static void setAttr(Connector connector, Access access, String ctag, String atag) throws IOException { - String value = access.getProperty(atag, null); - if(value==null) { - access.log(Level.ERROR, atag, "is null"); - } else { - if(value.startsWith("enc:")) { - access.log(Level.INIT,atag,"=enc:************"); - value = access.decrypt(value, false); - } else { - access.log(Level.INIT,atag,"=",value); - } - connector.setAttribute(ctag, value); - } + String value = access.getProperty(atag, null); + if(value==null) { + access.log(Level.ERROR, atag, "is null"); + } else { + if(value.startsWith("enc:")) { + access.log(Level.INIT,atag,"=enc:************"); + value = access.decrypt(value, false); + } else { + access.log(Level.INIT,atag,"=",value); + } + connector.setAttribute(ctag, value); + } } - private static File getRootFolder() { - try { - File root; - String runningJarPath = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath().replaceAll("\\\\", "/"); - int lastIndexOf = runningJarPath.lastIndexOf("/target/"); - if (lastIndexOf < 0) { - root = new File(""); - } else { - root = new File(runningJarPath.substring(0, lastIndexOf)); - } - System.out.println("application resolved root folder: " + root.getAbsolutePath()); - return root; - } catch (URISyntaxException ex) { - throw new RuntimeException(ex); - } - } + private static File getRootFolder() { + try { + File root; + String runningJarPath = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath().replaceAll("\\\\", "/"); + int lastIndexOf = runningJarPath.lastIndexOf("/target/"); + if (lastIndexOf < 0) { + root = new File(""); + } else { + root = new File(runningJarPath.substring(0, lastIndexOf)); + } + System.out.println("application resolved root folder: " + root.getAbsolutePath()); + return root; + } catch (URISyntaxException ex) { + throw new RuntimeException(ex); + } + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/APIException.java b/misc/env/src/main/java/org/onap/aaf/misc/env/APIException.java index bf1d357f..4aa1451e 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/APIException.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/APIException.java @@ -35,55 +35,55 @@ package org.onap.aaf.misc.env; * */ public class APIException extends Exception { - - private Object payload = null; - - /** - * @param t - */ - public APIException(Throwable t) { - super(t); - } - - /** - * @param string - */ - public APIException(String string) { - super(string); - } + + private Object payload = null; + + /** + * @param t + */ + public APIException(Throwable t) { + super(t); + } + + /** + * @param string + */ + public APIException(String string) { + super(string); + } - /** - * @param errorMessage - * @param t - */ - public APIException(String errorMessage, Throwable t) { - super(errorMessage,t); - } + /** + * @param errorMessage + * @param t + */ + public APIException(String errorMessage, Throwable t) { + super(errorMessage,t); + } - /** - * Return payload, or null if none was set. Type is up to the calling - * System. - * - * @return Object - */ - public Object getPayload() { - return payload; - } + /** + * Return payload, or null if none was set. Type is up to the calling + * System. + * + * @return Object + */ + public Object getPayload() { + return payload; + } - /** - * Set a specific payload into this Exception, which doesn't necessarily - * inherit from Throwable. - * - * @param payload - * @return APIException - */ - public APIException setPayload(Object payload) { - this.payload = payload; - return this; - } + /** + * Set a specific payload into this Exception, which doesn't necessarily + * inherit from Throwable. + * + * @param payload + * @return APIException + */ + public APIException setPayload(Object payload) { + this.payload = payload; + return this; + } - /** - * Java expected serial ID - */ - private static final long serialVersionUID = 3505343458251445169L; + /** + * Java expected serial ID + */ + private static final long serialVersionUID = 3505343458251445169L; } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java b/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java index 78615018..d72222e8 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java @@ -54,425 +54,425 @@ import org.xml.sax.SAXException; * @param */ public class BaseDataFactory { - private static final Object LOCK = new Object(); - /** - * Generate a Schema Object for use in validation based on FileNames. - * - * WARNING: The java.xml.binding code requires YOU to figure out what order the - * files go in. If there is an import from A in B, then you must list A first. - * - * @param err - * @param filenames - * @return - * @throws APIException - */ - public static Schema genSchema(Store env, String ... filenames) throws APIException { - String schemaDir = env.get( - env.staticSlot(EnvFactory.SCHEMA_DIR), - EnvFactory.DEFAULT_SCHEMA_DIR); - File dir = new File(schemaDir); - if(!dir.exists())throw new APIException("Schema Directory " + schemaDir + " does not exist. You can set this with " + EnvFactory.SCHEMA_DIR + " property"); - FileInputStream[] fis = new FileInputStream[filenames.length]; - Source[] sources = new Source[filenames.length]; - File f; - for(int i=0; i clss) throws APIException { - // Obtain the Necessary info for QName from Requirement - XmlRootElement xre = clss.getAnnotation(XmlRootElement.class); - if(xre==null)throw new APIException(clss.getName() + " does not have an XmlRootElement annotation"); - Package pkg = clss.getPackage(); - XmlSchema xs = pkg.getAnnotation(XmlSchema.class); - if(xs==null) throw new APIException(clss.getName() + " package-info does not have an XmlSchema annotation"); - return new QName(xs.namespace(),xre.name()); - } + public static QName getQName(Class clss) throws APIException { + // Obtain the Necessary info for QName from Requirement + XmlRootElement xre = clss.getAnnotation(XmlRootElement.class); + if(xre==null)throw new APIException(clss.getName() + " does not have an XmlRootElement annotation"); + Package pkg = clss.getPackage(); + XmlSchema xs = pkg.getAnnotation(XmlSchema.class); + if(xs==null) throw new APIException(clss.getName() + " package-info does not have an XmlSchema annotation"); + return new QName(xs.namespace(),xre.name()); + } - ///////////////////////////////////////////// - // Native Type Converters - ///////////////////////////////////////////// -// /** -// * StringStringifier -// * -// * Support the Native Type String.. just return it back -// * -// * @author Jonathan -// * -// */ -// public static class StringStringifier extends NullLifeCycle implements Stringifier { -// /* (non-Javadoc) -// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) -// */ -// public String stringify(Env env, String input) throws APIException { -// return input; -// } -// }; + ///////////////////////////////////////////// + // Native Type Converters + ///////////////////////////////////////////// +// /** +// * StringStringifier +// * +// * Support the Native Type String.. just return it back +// * +// * @author Jonathan +// * +// */ +// public static class StringStringifier extends NullLifeCycle implements Stringifier { +// /* (non-Javadoc) +// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) +// */ +// public String stringify(Env env, String input) throws APIException { +// return input; +// } +// }; // -// /** -// * StringObjectifier -// * -// * Support the Native Type String.. just return it back -// * -// * @author Jonathan -// * -// */ -// public static class StringObjectifier extends NullLifeCycle implements Objectifier { -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) -// */ -// public String objectify(Env env, String input) throws APIException { -// return input; -// } +// /** +// * StringObjectifier +// * +// * Support the Native Type String.. just return it back +// * +// * @author Jonathan +// * +// */ +// public static class StringObjectifier extends NullLifeCycle implements Objectifier { +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) +// */ +// public String objectify(Env env, String input) throws APIException { +// return input; +// } // -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#newObject() -// */ -// public String newInstance() throws APIException { -// return ""; -// } -// }; -// -// /** -// * LongStringifier -// * -// * Support the Native Type Long.. use Long parse functions -// * -// * @author Jonathan -// * -// */ -// public static class LongStringifier extends NullLifeCycle implements Stringifier { -// public String stringify(Env env, Long input) throws APIException { -// return input.toString(); -// } -// } -// -// /** -// * LongObjectifier -// * -// * Support the Native Type Long.. use Long parse functions -// * -// * @author Jonathan -// * -// */ -// public static class LongObjectifier extends NullLifeCycle implements Objectifier { -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) -// */ -// public Long objectify(Env env, String input) throws APIException { -// try { -// return new Long(input); -// } catch (Exception e) { -// APIException ae = new APIException("Cannot create a \"Long\" from [" + input + ']'); -// ae.initCause(e); -// throw ae; -// } -// } +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#newObject() +// */ +// public String newInstance() throws APIException { +// return ""; +// } +// }; +// +// /** +// * LongStringifier +// * +// * Support the Native Type Long.. use Long parse functions +// * +// * @author Jonathan +// * +// */ +// public static class LongStringifier extends NullLifeCycle implements Stringifier { +// public String stringify(Env env, Long input) throws APIException { +// return input.toString(); +// } +// } +// +// /** +// * LongObjectifier +// * +// * Support the Native Type Long.. use Long parse functions +// * +// * @author Jonathan +// * +// */ +// public static class LongObjectifier extends NullLifeCycle implements Objectifier { +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) +// */ +// public Long objectify(Env env, String input) throws APIException { +// try { +// return new Long(input); +// } catch (Exception e) { +// APIException ae = new APIException("Cannot create a \"Long\" from [" + input + ']'); +// ae.initCause(e); +// throw ae; +// } +// } // -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#newObject() -// */ -// public Long newInstance() throws APIException { -// return 0L; -// } -// } +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#newObject() +// */ +// public Long newInstance() throws APIException { +// return 0L; +// } +// } // -// /** -// * IntegerStringifier -// * -// * Support the Native Integer.. use Integer parse functions -// * -// * @author Jonathan -// * -// */ -// public static class IntegerStringifier extends NullLifeCycle implements Stringifier { -// /* (non-Javadoc) -// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) -// */ -// public String stringify(Env env, Integer input) throws APIException { -// return input.toString(); -// } -// } -// -// /** -// * IntegerObjectifier -// * -// * Support the Native Integer.. use Integer parse functions -// * -// * @author Jonathan -// * -// */ -// public static class IntegerObjectifier extends NullLifeCycle implements Objectifier { -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) -// */ -// public Integer objectify(Env env, String input) throws APIException { -// try { -// return new Integer(input); -// } catch (Exception e) { -// APIException ae = new APIException("Cannot create a \"Integer\" from [" + input + ']'); -// ae.initCause(e); -// throw ae; -// } -// } +// /** +// * IntegerStringifier +// * +// * Support the Native Integer.. use Integer parse functions +// * +// * @author Jonathan +// * +// */ +// public static class IntegerStringifier extends NullLifeCycle implements Stringifier { +// /* (non-Javadoc) +// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) +// */ +// public String stringify(Env env, Integer input) throws APIException { +// return input.toString(); +// } +// } +// +// /** +// * IntegerObjectifier +// * +// * Support the Native Integer.. use Integer parse functions +// * +// * @author Jonathan +// * +// */ +// public static class IntegerObjectifier extends NullLifeCycle implements Objectifier { +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) +// */ +// public Integer objectify(Env env, String input) throws APIException { +// try { +// return new Integer(input); +// } catch (Exception e) { +// APIException ae = new APIException("Cannot create a \"Integer\" from [" + input + ']'); +// ae.initCause(e); +// throw ae; +// } +// } // -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#newObject() -// */ -// public Integer newInstance() throws APIException { -// return 0; -// } -// } +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#newObject() +// */ +// public Integer newInstance() throws APIException { +// return 0; +// } +// } // -// /** -// * ShortStringifier -// * -// * Support the Native Short.. use Short parse functions -// * -// * @author Jonathan -// * -// */ -// public static class ShortStringifier extends NullLifeCycle implements Stringifier { -// public String stringify(Env env, Short input) throws APIException { -// return input.toString(); -// } -// } -// -// /** -// * ShortObjectifier -// * -// * Support the Native Short.. use Short parse functions -// * -// * @author Jonathan -// * -// */ -// public static class ShortObjectifier extends NullLifeCycle implements Objectifier { -// public Short objectify(Env env, String input) throws APIException { -// try { -// return new Short(input); -// } catch (Exception e) { -// APIException ae = new APIException("Cannot create a \"Short\" from [" + input + ']'); -// ae.initCause(e); -// throw ae; -// } -// } +// /** +// * ShortStringifier +// * +// * Support the Native Short.. use Short parse functions +// * +// * @author Jonathan +// * +// */ +// public static class ShortStringifier extends NullLifeCycle implements Stringifier { +// public String stringify(Env env, Short input) throws APIException { +// return input.toString(); +// } +// } +// +// /** +// * ShortObjectifier +// * +// * Support the Native Short.. use Short parse functions +// * +// * @author Jonathan +// * +// */ +// public static class ShortObjectifier extends NullLifeCycle implements Objectifier { +// public Short objectify(Env env, String input) throws APIException { +// try { +// return new Short(input); +// } catch (Exception e) { +// APIException ae = new APIException("Cannot create a \"Short\" from [" + input + ']'); +// ae.initCause(e); +// throw ae; +// } +// } // -// public Short newInstance() throws APIException { -// return 0; -// } -// } -// -// /** -// * ByteStringifier -// * -// * Support the Native Byte.. use Byte parse functions -// * -// * @author Jonathan -// * -// */ -// public static class ByteStringifier extends NullLifeCycle implements Stringifier { -// /* (non-Javadoc) -// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) -// */ -// public String stringify(Env env, Byte input) throws APIException { -// return input.toString(); -// } -// } -// -// /** -// * ByteObjectifier -// * -// * Support the Native Byte.. use Byte parse functions -// * -// * @author Jonathan -// * -// */ -// public static class ByteObjectifier extends NullLifeCycle implements Objectifier { -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) -// */ -// public Byte objectify(Env env, String input) throws APIException { -// try { -// return new Byte(input); -// } catch (Exception e) { -// APIException ae = new APIException("Cannot create a \"Byte\" from [" + input + ']'); -// ae.initCause(e); -// throw ae; -// } -// } +// public Short newInstance() throws APIException { +// return 0; +// } +// } +// +// /** +// * ByteStringifier +// * +// * Support the Native Byte.. use Byte parse functions +// * +// * @author Jonathan +// * +// */ +// public static class ByteStringifier extends NullLifeCycle implements Stringifier { +// /* (non-Javadoc) +// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) +// */ +// public String stringify(Env env, Byte input) throws APIException { +// return input.toString(); +// } +// } +// +// /** +// * ByteObjectifier +// * +// * Support the Native Byte.. use Byte parse functions +// * +// * @author Jonathan +// * +// */ +// public static class ByteObjectifier extends NullLifeCycle implements Objectifier { +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) +// */ +// public Byte objectify(Env env, String input) throws APIException { +// try { +// return new Byte(input); +// } catch (Exception e) { +// APIException ae = new APIException("Cannot create a \"Byte\" from [" + input + ']'); +// ae.initCause(e); +// throw ae; +// } +// } // -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#newObject() -// */ -// public Byte newInstance() throws APIException { -// return 0; -// } -// } +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#newObject() +// */ +// public Byte newInstance() throws APIException { +// return 0; +// } +// } // -// /** -// * CharacterStringifier -// * -// * Support the Native Character.. use Character parse functions -// * -// * @author Jonathan -// * -// */ -// public static class CharacterStringifier extends NullLifeCycle implements Stringifier { -// /* (non-Javadoc) -// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) -// */ -// public String stringify(Env env, Character input) throws APIException { -// return input.toString(); -// } -// } -// -// /** -// * CharacterObjectifier -// * -// * Support the Native Character.. use Character parse functions -// * -// * @author Jonathan -// * -// */ -// public static class CharacterObjectifier extends NullLifeCycle implements Objectifier { -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) -// */ -// public Character objectify(Env env, String input) throws APIException { -// int length = input.length(); -// if(length<1 || length>1) { -// throw new APIException("String [" + input + "] does not represent a single Character"); -// } -// return input.charAt(0); -// } +// /** +// * CharacterStringifier +// * +// * Support the Native Character.. use Character parse functions +// * +// * @author Jonathan +// * +// */ +// public static class CharacterStringifier extends NullLifeCycle implements Stringifier { +// /* (non-Javadoc) +// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) +// */ +// public String stringify(Env env, Character input) throws APIException { +// return input.toString(); +// } +// } +// +// /** +// * CharacterObjectifier +// * +// * Support the Native Character.. use Character parse functions +// * +// * @author Jonathan +// * +// */ +// public static class CharacterObjectifier extends NullLifeCycle implements Objectifier { +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) +// */ +// public Character objectify(Env env, String input) throws APIException { +// int length = input.length(); +// if(length<1 || length>1) { +// throw new APIException("String [" + input + "] does not represent a single Character"); +// } +// return input.charAt(0); +// } // -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#newObject() -// */ -// public Character newInstance() throws APIException { -// return 0; -// } -// } +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#newObject() +// */ +// public Character newInstance() throws APIException { +// return 0; +// } +// } // -// /** -// * FloatStringifier -// * -// * Support the Native Float.. use Float parse functions -// * -// * @author Jonathan -// * -// */ -// public static class FloatStringifier extends NullLifeCycle implements Stringifier { -// /* (non-Javadoc) -// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) -// */ -// public String stringify(Env env, Float input) throws APIException { -// return input.toString(); -// } -// } -// -// /** -// * FloatObjectifier -// * -// * Support the Native Float.. use Float parse functions -// * -// * @author Jonathan -// * -// */ -// public static class FloatObjectifier extends NullLifeCycle implements Objectifier { -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) -// */ -// public Float objectify(Env env, String input) throws APIException { -// try { -// return new Float(input); -// } catch (Exception e) { -// APIException ae = new APIException("Cannot create a \"Float\" from [" + input + ']'); -// ae.initCause(e); -// throw ae; -// } -// } +// /** +// * FloatStringifier +// * +// * Support the Native Float.. use Float parse functions +// * +// * @author Jonathan +// * +// */ +// public static class FloatStringifier extends NullLifeCycle implements Stringifier { +// /* (non-Javadoc) +// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) +// */ +// public String stringify(Env env, Float input) throws APIException { +// return input.toString(); +// } +// } +// +// /** +// * FloatObjectifier +// * +// * Support the Native Float.. use Float parse functions +// * +// * @author Jonathan +// * +// */ +// public static class FloatObjectifier extends NullLifeCycle implements Objectifier { +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) +// */ +// public Float objectify(Env env, String input) throws APIException { +// try { +// return new Float(input); +// } catch (Exception e) { +// APIException ae = new APIException("Cannot create a \"Float\" from [" + input + ']'); +// ae.initCause(e); +// throw ae; +// } +// } // -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#newObject() -// */ -// public Float newInstance() throws APIException { -// return 0.0f; -// } -// } +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#newObject() +// */ +// public Float newInstance() throws APIException { +// return 0.0f; +// } +// } // -// /** -// * DoubleStringifier -// * -// * Support the Native Double.. use Double parse functions -// * -// * @author Jonathan -// * -// */ -// public static class DoubleStringifier extends NullLifeCycle implements Stringifier { -// /* (non-Javadoc) -// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) -// */ -// public String stringify(Env env, Double input) throws APIException { -// return input.toString(); -// } -// } -// -// /** -// * DoubleObjectifier -// * -// * Support the Native Double.. use Double parse functions -// * -// * @author Jonathan -// * -// */ -// public static class DoubleObjectifier extends NullLifeCycle implements Objectifier { -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) -// */ -// public Double objectify(Env env, String input) throws APIException { -// try { -// return new Double(input); -// } catch (Exception e) { -// APIException ae = new APIException("Cannot create a \"Double\" from [" + input + ']'); -// ae.initCause(e); -// throw ae; -// } -// } +// /** +// * DoubleStringifier +// * +// * Support the Native Double.. use Double parse functions +// * +// * @author Jonathan +// * +// */ +// public static class DoubleStringifier extends NullLifeCycle implements Stringifier { +// /* (non-Javadoc) +// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object) +// */ +// public String stringify(Env env, Double input) throws APIException { +// return input.toString(); +// } +// } +// +// /** +// * DoubleObjectifier +// * +// * Support the Native Double.. use Double parse functions +// * +// * @author Jonathan +// * +// */ +// public static class DoubleObjectifier extends NullLifeCycle implements Objectifier { +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String) +// */ +// public Double objectify(Env env, String input) throws APIException { +// try { +// return new Double(input); +// } catch (Exception e) { +// APIException ae = new APIException("Cannot create a \"Double\" from [" + input + ']'); +// ae.initCause(e); +// throw ae; +// } +// } // -// /* (non-Javadoc) -// * @see com.att.env.Objectifier#newObject() -// */ -// public Double newInstance() throws APIException { -// return 0.0; -// } -// } +// /* (non-Javadoc) +// * @see com.att.env.Objectifier#newObject() +// */ +// public Double newInstance() throws APIException { +// return 0.0; +// } +// } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Creatable.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Creatable.java index 2423ed62..c64cfff2 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Creatable.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Creatable.java @@ -34,19 +34,19 @@ package org.onap.aaf.misc.env; * @param */ public interface Creatable { - /** - * Return the timestamp (Unix long) when this object was created.

    - * This can be used to see if the object is out of date in certain - * circumstances, or perhaps has already been notified in others. - * - * @return long - */ - public abstract long created(); - - /** - * Allow LifeCycle aware process to signal this element as destroyed. - * - * @param env - */ - public abstract void destroy(Env env); + /** + * Return the timestamp (Unix long) when this object was created.

    + * This can be used to see if the object is out of date in certain + * circumstances, or perhaps has already been notified in others. + * + * @return long + */ + public abstract long created(); + + /** + * Allow LifeCycle aware process to signal this element as destroyed. + * + * @param env + */ + public abstract void destroy(Env env); } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Data.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Data.java index 155dfc71..4c64e5de 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Data.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Data.java @@ -42,7 +42,7 @@ import java.io.Writer; * the "options" available on several functions control the output of this particular call. When * blank, they will default to the DataFactory defaults. When present, they override this * particular call. - * The available options are "pretty" (for XML and JSON) and "fragment" (XML only concept), which drops + * The available options are "pretty" (for XML and JSON) and "fragment" (XML only concept), which drops * the "" header so you can create larger XML documents from the output. * * @author Jonathan @@ -50,64 +50,64 @@ import java.io.Writer; * @param */ public interface Data { - static enum TYPE {XML,JSON,JAXB,RAW,DEFAULT}; - // can & with 0xFFFF; -// public static final int XML = 0x1; -// public static final int JSON = 0x2; -// public static final int JAXB = 0x4; -// public static final int RAW = 0x1000; - - // can & with 0xF00000; - public static final int PRETTY = 0x100000; - public static final int FRAGMENT = 0x200000; + static enum TYPE {XML,JSON,JAXB,RAW,DEFAULT}; + // can & with 0xFFFF; +// public static final int XML = 0x1; +// public static final int JSON = 0x2; +// public static final int JAXB = 0x4; +// public static final int RAW = 0x1000; + + // can & with 0xF00000; + public static final int PRETTY = 0x100000; + public static final int FRAGMENT = 0x200000; - /** - * Respond with the String if it exists, or marshal the String and pass the result back. - * - * However, use the Env the Data Object was created with. - * - * @return String - * @throws APIException - */ - public String asString() throws APIException; + /** + * Respond with the String if it exists, or marshal the String and pass the result back. + * + * However, use the Env the Data Object was created with. + * + * @return String + * @throws APIException + */ + public String asString() throws APIException; - /** - * Respond with the Object of type {@literal } if it exists, or unmarshal from String - * and pass the result back.

    - * - * However, use the Env the Data Object was created with. - * - * @return T - * @throws APIException - */ - public T asObject() throws APIException; + /** + * Respond with the Object of type {@literal } if it exists, or unmarshal from String + * and pass the result back.

    + * + * However, use the Env the Data Object was created with. + * + * @return T + * @throws APIException + */ + public T asObject() throws APIException; - /** - * Set a particular option on an existing Out - * - * if int is negative, it should remove the option - * @param option - */ - public Data option(int option); + /** + * Set a particular option on an existing Out + * + * if int is negative, it should remove the option + * @param option + */ + public Data option(int option); - public Data to(OutputStream os) throws APIException, IOException; - public Data to(Writer writer) throws APIException, IOException; - - public Data load(T t) throws APIException; - public Data load(String str) throws APIException; - public Data load(InputStream is) throws APIException; - public Data load(Reader rdr) throws APIException; - - public Data in(TYPE type); - public Data out(TYPE type); - /** - * Return the Class Type supported by this DataObject - * - * @return {@literal Class} - */ - public Class getTypeClass(); + public Data to(OutputStream os) throws APIException, IOException; + public Data to(Writer writer) throws APIException, IOException; + + public Data load(T t) throws APIException; + public Data load(String str) throws APIException; + public Data load(InputStream is) throws APIException; + public Data load(Reader rdr) throws APIException; + + public Data in(TYPE type); + public Data out(TYPE type); + /** + * Return the Class Type supported by this DataObject + * + * @return {@literal Class} + */ + public Class getTypeClass(); - public void direct(InputStream input, OutputStream output) throws APIException, IOException; + public void direct(InputStream input, OutputStream output) throws APIException, IOException; } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/DataFactory.java b/misc/env/src/main/java/org/onap/aaf/misc/env/DataFactory.java index a9595a55..6735e9a6 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/DataFactory.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/DataFactory.java @@ -23,8 +23,8 @@ package org.onap.aaf.misc.env; public interface DataFactory { - public abstract Data newData(); - public abstract Data newData(Env trans); // and Env or Trans object - public abstract Class getTypeClass(); + public abstract Data newData(); + public abstract Data newData(Env trans); // and Env or Trans object + public abstract Class getTypeClass(); } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Decryptor.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Decryptor.java index bc29c318..48d55e0a 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Decryptor.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Decryptor.java @@ -23,12 +23,12 @@ package org.onap.aaf.misc.env; public interface Decryptor { - public String decrypt(String tag); - - public static final Decryptor NULL = new Decryptor() { - @Override - public String decrypt(String tag) { - return tag; - } - }; + public String decrypt(String tag); + + public static final Decryptor NULL = new Decryptor() { + @Override + public String decrypt(String tag) { + return tag; + } + }; } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Encryptor.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Encryptor.java index ad7409d0..1925f65e 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Encryptor.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Encryptor.java @@ -23,12 +23,12 @@ package org.onap.aaf.misc.env; public interface Encryptor { - public String encrypt(String data); + public String encrypt(String data); - public static final Encryptor NULL = new Encryptor() { - @Override - public String encrypt(String data) { - return data; - } - }; + public static final Encryptor NULL = new Encryptor() { + @Override + public String encrypt(String data) { + return data; + } + }; } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Env.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Env.java index e4b6aaa2..f709a434 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Env.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Env.java @@ -46,91 +46,91 @@ package org.onap.aaf.misc.env; * */ public interface Env { - /** - * Very Severe Error may cause program to abort - */ - public LogTarget fatal(); - - /** - * Severe Error, but program might continue running - */ - public LogTarget error(); + /** + * Very Severe Error may cause program to abort + */ + public LogTarget fatal(); + + /** + * Severe Error, but program might continue running + */ + public LogTarget error(); - /** - * Required Audit statements - * @return - */ - public LogTarget audit(); + /** + * Required Audit statements + * @return + */ + public LogTarget audit(); - /** - * Initialization steps... Allows a Logger to separate startup info - * @return - */ - public LogTarget init(); + /** + * Initialization steps... Allows a Logger to separate startup info + * @return + */ + public LogTarget init(); - /** - * Potentially harmful situations - * @return - */ - public LogTarget warn(); - - /** - * Course Grained highlights of program progress - * @return - */ - public LogTarget info(); - - /** - * Fine-grained informational events useful for debugging - * @return - */ - public LogTarget debug(); - - /** - * Finest grained Informational events... more detailed than Debug - * @return - */ - public LogTarget trace(); + /** + * Potentially harmful situations + * @return + */ + public LogTarget warn(); + + /** + * Course Grained highlights of program progress + * @return + */ + public LogTarget info(); + + /** + * Fine-grained informational events useful for debugging + * @return + */ + public LogTarget debug(); + + /** + * Finest grained Informational events... more detailed than Debug + * @return + */ + public LogTarget trace(); - /** - * Basic and Common Audit info... - * - * Note Apps can define, but should use Integers after 0x1F. They can combine with "&" - */ - public static final int REMOTE = 0x01; - public static final int XML = 0x02; - public static final int JSON = 0x04; - public static final int SUB = 0x08; - public static final int CHECKPOINT = 0x10; - public static final int ALWAYS = 0x20; // Mark as a line to print, even in WARN+ mode + /** + * Basic and Common Audit info... + * + * Note Apps can define, but should use Integers after 0x1F. They can combine with "&" + */ + public static final int REMOTE = 0x01; + public static final int XML = 0x02; + public static final int JSON = 0x04; + public static final int SUB = 0x08; + public static final int CHECKPOINT = 0x10; + public static final int ALWAYS = 0x20; // Mark as a line to print, even in WARN+ mode - - /** - * Start a Time Trail with differentiation by flag. This can be Defined By above flags or combined with - * app flag definitions - * - * @param string - * @param flag - * @return - */ - public TimeTaken start(String name, int flag); - - public String setProperty(String tag, String value); - public String getProperty(String tag); - public String getProperty(String tag, String deflt); - - /** - * Passwords should be encrypted on the disk. Use this method to apply decryption before - * using. The Implementation should give ways to decrypt - * - * @param tag - * @return - */ - public Decryptor decryptor(); - - public Encryptor encryptor(); + + /** + * Start a Time Trail with differentiation by flag. This can be Defined By above flags or combined with + * app flag definitions + * + * @param string + * @param flag + * @return + */ + public TimeTaken start(String name, int flag); + + public String setProperty(String tag, String value); + public String getProperty(String tag); + public String getProperty(String tag, String deflt); + + /** + * Passwords should be encrypted on the disk. Use this method to apply decryption before + * using. The Implementation should give ways to decrypt + * + * @param tag + * @return + */ + public Decryptor decryptor(); + + public Encryptor encryptor(); } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/EnvJAXB.java b/misc/env/src/main/java/org/onap/aaf/misc/env/EnvJAXB.java index a530073e..09db36f4 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/EnvJAXB.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/EnvJAXB.java @@ -25,28 +25,28 @@ import javax.xml.namespace.QName; import javax.xml.validation.Schema; public interface EnvJAXB extends EnvStore { - /** - * Obtain a DataInterface from this Environment - * - * @param - * @param classes - * @return - * @throws APIException - */ - public DataFactory newDataFactory(Class... classes) throws APIException; + /** + * Obtain a DataInterface from this Environment + * + * @param + * @param classes + * @return + * @throws APIException + */ + public DataFactory newDataFactory(Class... classes) throws APIException; - /** - * Obtain a DataInterface from this Environment, with Validating Schema - * - * @param - * @param classes - * @return - * @throws APIException - */ - public DataFactory newDataFactory(Schema schema, Class... classes) throws APIException; + /** + * Obtain a DataInterface from this Environment, with Validating Schema + * + * @param + * @param classes + * @return + * @throws APIException + */ + public DataFactory newDataFactory(Schema schema, Class... classes) throws APIException; - public DataFactory newDataFactory(QName qName, Class ... classes) throws APIException; + public DataFactory newDataFactory(QName qName, Class ... classes) throws APIException; - public DataFactory newDataFactory(Schema schema, QName qName, Class ... classes) throws APIException; - + public DataFactory newDataFactory(Schema schema, QName qName, Class ... classes) throws APIException; + } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/EnvProps.java b/misc/env/src/main/java/org/onap/aaf/misc/env/EnvProps.java index 0e645da2..b2cebb55 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/EnvProps.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/EnvProps.java @@ -24,57 +24,57 @@ package org.onap.aaf.misc.env; import java.util.Map; public interface EnvProps extends Env { - public interface EnvProperty { - public String getProperty(String input); - }; + public interface EnvProperty { + public String getProperty(String input); + }; - /** - * Obtain a Property (String) based on a Key. Implementor decides how - * that works, i.e. from a complex set of Configurations, or just - * "System" (Java standard) - * - * @param key - * @return APIException - */ - public String getProperty(String key); + /** + * Obtain a Property (String) based on a Key. Implementor decides how + * that works, i.e. from a complex set of Configurations, or just + * "System" (Java standard) + * + * @param key + * @return APIException + */ + public String getProperty(String key); - /** - * Obtain a Property (String) based on a Key. Implementor decides how - * that works, i.e. from a complex set of Configurations, or just - * "System" (Java standard) - * - * If Property Value is null, then default will be used. - * @param key - * @return APIException - */ - public String getProperty(String tag, String defaultValue); + /** + * Obtain a Property (String) based on a Key. Implementor decides how + * that works, i.e. from a complex set of Configurations, or just + * "System" (Java standard) + * + * If Property Value is null, then default will be used. + * @param key + * @return APIException + */ + public String getProperty(String tag, String defaultValue); - /** - * Set a Property (String) based on a Key accessible to all in Env. Implementor decides how - * that works, i.e. from a complex set of Configurations, or just - * "System" (Java standard) - * - * @param key - * @return APIException - */ - public String setProperty(String key, String value); - - /** - * Get the SubProperties based on key. - * - * use "false" to remove prefix, "true" to leave prefix in. - * - * @param key - * @return APIException - * Given a known property set (or in this case, properties starting with key), - * return map of all properties with appropriate key names - */ - public Map getSubProperties(String key, boolean includePrefix); + /** + * Set a Property (String) based on a Key accessible to all in Env. Implementor decides how + * that works, i.e. from a complex set of Configurations, or just + * "System" (Java standard) + * + * @param key + * @return APIException + */ + public String setProperty(String key, String value); + + /** + * Get the SubProperties based on key. + * + * use "false" to remove prefix, "true" to leave prefix in. + * + * @param key + * @return APIException + * Given a known property set (or in this case, properties starting with key), + * return map of all properties with appropriate key names + */ + public Map getSubProperties(String key, boolean includePrefix); - /** - * Get all of the properties in the Environment - * @return - */ - public Map getProperties(); + /** + * Get all of the properties in the Environment + * @return + */ + public Map getProperties(); } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/IOObjectifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/IOObjectifier.java index e3e74305..70b4adde 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/IOObjectifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/IOObjectifier.java @@ -25,30 +25,30 @@ import java.io.InputStream; import java.io.Reader; public interface IOObjectifier extends Objectifier { - /** - * Marshal to Object T from a Reader, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return T - * @throws APIException - */ - public abstract T objectify(Env env, Reader rdr) throws APIException; - - /** - * Marshal to Object T from an InputStream, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return T - * @throws APIException - */ - public abstract T objectify(Env env, InputStream is) throws APIException; + /** + * Marshal to Object T from a Reader, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return T + * @throws APIException + */ + public abstract T objectify(Env env, Reader rdr) throws APIException; + + /** + * Marshal to Object T from an InputStream, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return T + * @throws APIException + */ + public abstract T objectify(Env env, InputStream is) throws APIException; } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/IOStringifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/IOStringifier.java index 57d85472..4329fcbc 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/IOStringifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/IOStringifier.java @@ -28,47 +28,47 @@ import java.io.Writer; * Allow Extended IO interface usage without muddying up the Stringifier Interface */ public interface IOStringifier extends Stringifier { - /** - * Marshal from an Object T onto a Writer, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startTime(, Env.XML)" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return String - * @throws APIException - */ - public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException; - - /** - * Marshal from a String to an Object T, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return String - * @throws APIException - */ - public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException; + /** + * Marshal from an Object T onto a Writer, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startTime(, Env.XML)" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return String + * @throws APIException + */ + public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException; + + /** + * Marshal from a String to an Object T, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return String + * @throws APIException + */ + public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException; - /** - * Set Pretty XML, where possible - * - * @param pretty - * @throws APIException - */ - public abstract IOStringifier pretty(boolean pretty); + /** + * Set Pretty XML, where possible + * + * @param pretty + * @throws APIException + */ + public abstract IOStringifier pretty(boolean pretty); - /** - * Set Generate Fragment - * - * @param fragment - * @throws APIException - */ - public abstract IOStringifier asFragment(boolean fragment); + /** + * Set Generate Fragment + * + * @param fragment + * @throws APIException + */ + public abstract IOStringifier asFragment(boolean fragment); } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/LifeCycle.java b/misc/env/src/main/java/org/onap/aaf/misc/env/LifeCycle.java index 5124f6b5..75f3b701 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/LifeCycle.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/LifeCycle.java @@ -43,81 +43,81 @@ import org.onap.aaf.misc.env.util.RefreshableThreadObject; * */ public interface LifeCycle { - /** - * The Service using LifeCycle Elements is required to call this method at - * the appropriate startup time. This is better for services than a simple - * static call, because the exact moment of starting can be determined - * programatically. - *

    - * - * An excellent use is to establish security credentials with a backend - * after appropriate configurations have been read and available as part of - * the {@link Env} Object. - * - * @param env - * @throws APIException - */ - public abstract void servicePrestart(Env env) throws APIException; + /** + * The Service using LifeCycle Elements is required to call this method at + * the appropriate startup time. This is better for services than a simple + * static call, because the exact moment of starting can be determined + * programatically. + *

    + * + * An excellent use is to establish security credentials with a backend + * after appropriate configurations have been read and available as part of + * the {@link Env} Object. + * + * @param env + * @throws APIException + */ + public abstract void servicePrestart(Env env) throws APIException; - /** - * Many cases of implementations are not thread safe, and mechanisms must be - * derived to accomodate them by holding per Thread. - *

    - * - * {@link ThreadLocal} is a valuable resource, but start up times within the - * thread, depending on what it is, can be substantial. - *

    - * - * Use ThreadPrestart to do all that is possible before actually performing - * work, i.e. inside of a client transaction. - * - * @param env - * @throws APIException - */ - public abstract void threadPrestart(Env env) throws APIException; + /** + * Many cases of implementations are not thread safe, and mechanisms must be + * derived to accomodate them by holding per Thread. + *

    + * + * {@link ThreadLocal} is a valuable resource, but start up times within the + * thread, depending on what it is, can be substantial. + *

    + * + * Use ThreadPrestart to do all that is possible before actually performing + * work, i.e. inside of a client transaction. + * + * @param env + * @throws APIException + */ + public abstract void threadPrestart(Env env) throws APIException; - /** - * The Service will call this when (service-defined) configurations change. - *

    - * - * This mechanism allows the Service to recognize events, such as file - * changes, and pass on the event to all LifeCycle implementors. - *

    - * - * The code should take the opportunity to evaluate configuration and change - * as necessary. - *

    - * - *

    IMPORTANT:

    - * The LifeCycle implementor cannot guarantee it will not be in the middle - * of a transaction, so it would behoove the implementor to construct - * content that does not affect anything until finished, then apply to an - * appropriate atomic action (i.e. setting an Object to a field), or even - * synchronizing. - * - * If you are using Java's "ThreadLocal", consider - * {@link RefreshableThreadObject}, because it implements LifeCycle, and - * responds to the refresh command. - * - * @param env - * @throws APIException - */ - public abstract void refresh(Env env) throws APIException; + /** + * The Service will call this when (service-defined) configurations change. + *

    + * + * This mechanism allows the Service to recognize events, such as file + * changes, and pass on the event to all LifeCycle implementors. + *

    + * + * The code should take the opportunity to evaluate configuration and change + * as necessary. + *

    + * + *

    IMPORTANT:

    + * The LifeCycle implementor cannot guarantee it will not be in the middle + * of a transaction, so it would behoove the implementor to construct + * content that does not affect anything until finished, then apply to an + * appropriate atomic action (i.e. setting an Object to a field), or even + * synchronizing. + * + * If you are using Java's "ThreadLocal", consider + * {@link RefreshableThreadObject}, because it implements LifeCycle, and + * responds to the refresh command. + * + * @param env + * @throws APIException + */ + public abstract void refresh(Env env) throws APIException; - /** - * Parallel to threadPrestart, threadDestroy tells the implementor that the - * service is ending this particular thread, and to take this opportunity to - * close out any content specific to this thread that can be closed. - * - * @param env - * @throws APIException - */ - public abstract void threadDestroy(Env env) throws APIException; + /** + * Parallel to threadPrestart, threadDestroy tells the implementor that the + * service is ending this particular thread, and to take this opportunity to + * close out any content specific to this thread that can be closed. + * + * @param env + * @throws APIException + */ + public abstract void threadDestroy(Env env) throws APIException; - /** - * Parallel to servicePrestart, serviceDestroy tells the implementor that - * the service is ending, and to take this opportunity to close out any - * content under it's control that can or should be closed explicitly. - */ - public abstract void serviceDestroy(Env env) throws APIException; + /** + * Parallel to servicePrestart, serviceDestroy tells the implementor that + * the service is ending, and to take this opportunity to close out any + * content under it's control that can or should be closed explicitly. + */ + public abstract void serviceDestroy(Env env) throws APIException; } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java b/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java index 8915becf..aa74edc9 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java @@ -32,7 +32,7 @@ import org.onap.aaf.misc.env.util.Chrono; * Implement for any Logging Library of your choice, and for any logging string Format desired. * * Included are several Static Implementations for various uses: - * NULL: Does nothing with Logging Messages + * NULL: Does nothing with Logging Messages * SYSOUT: Writes messages in general form to System Out * SYSERR: Writes messages in general form to System Err * @@ -40,103 +40,103 @@ import org.onap.aaf.misc.env.util.Chrono; * */ public interface LogTarget { - public abstract void log(Object... msgs); - public abstract void log(Throwable e, Object ... msgs); - public abstract boolean isLoggable(); - public abstract void printf(String fmt, Object ... vars); - - // A Convenient LogTarget to insert when a NO-OP is desired. - public static final LogTarget NULL = new LogTarget() { - public void log(Object ... msgs) { - } - - public void log(Throwable t, Object ... msgs) { - } - - public boolean isLoggable() { - return false; - } - - @Override - public void printf(String fmt, Object ... vars) { - } - }; - - // A Convenient LogTarget to write to the Console - public static final LogTarget SYSOUT = new LogTarget() { - public void log(Object ... msgs) { - PrintStream out = System.out; - out.print(org.onap.aaf.misc.env.util.Chrono.dateFmt.format(new Date())); - out.print(": "); - for(Object str : msgs) { - if(str!=null) { - out.print(str.toString()); - out.print(' '); - } else { - out.print("null "); - } - } - out.println(); - } - - public void log(Throwable t, Object ... msgs) { - PrintStream out = System.out; - out.print(Chrono.dateFmt.format(new Date())); - out.print(": "); - for(Object str : msgs) { - out.print(str.toString()); - out.print(' '); - } - out.println(); - t.printStackTrace(out); - out.println(); - } - - public boolean isLoggable() { - return true; - } - - @Override - public void printf(String fmt, Object ... vars) { - log(String.format(fmt,vars)); - } - }; - - // A Convenient LogTarget to write to the Console - public static final LogTarget SYSERR = new LogTarget() { - public void log(Object ... msgs) { - PrintStream out = System.err; - out.print(Chrono.dateFmt.format(new Date())); - out.print(": "); - for(Object str : msgs) { - out.print(str.toString()); - out.print(' '); - } - out.println(); - out.flush(); - } - - public void log(Throwable t, Object ... msgs) { - PrintStream out = System.err; - out.print(Chrono.dateFmt.format(new Date())); - out.print(": "); - for(Object str : msgs) { - out.print(str.toString()); - out.print(' '); - } - out.println(); - t.printStackTrace(out); - } - - public boolean isLoggable() { - return true; - } - @Override - public void printf(String fmt, Object ... vars) { - log(String.format(fmt,vars)); - } - - }; + public abstract void log(Object... msgs); + public abstract void log(Throwable e, Object ... msgs); + public abstract boolean isLoggable(); + public abstract void printf(String fmt, Object ... vars); + + // A Convenient LogTarget to insert when a NO-OP is desired. + public static final LogTarget NULL = new LogTarget() { + public void log(Object ... msgs) { + } + + public void log(Throwable t, Object ... msgs) { + } + + public boolean isLoggable() { + return false; + } + + @Override + public void printf(String fmt, Object ... vars) { + } + }; + + // A Convenient LogTarget to write to the Console + public static final LogTarget SYSOUT = new LogTarget() { + public void log(Object ... msgs) { + PrintStream out = System.out; + out.print(org.onap.aaf.misc.env.util.Chrono.dateFmt.format(new Date())); + out.print(": "); + for(Object str : msgs) { + if(str!=null) { + out.print(str.toString()); + out.print(' '); + } else { + out.print("null "); + } + } + out.println(); + } + + public void log(Throwable t, Object ... msgs) { + PrintStream out = System.out; + out.print(Chrono.dateFmt.format(new Date())); + out.print(": "); + for(Object str : msgs) { + out.print(str.toString()); + out.print(' '); + } + out.println(); + t.printStackTrace(out); + out.println(); + } + + public boolean isLoggable() { + return true; + } + + @Override + public void printf(String fmt, Object ... vars) { + log(String.format(fmt,vars)); + } + }; + + // A Convenient LogTarget to write to the Console + public static final LogTarget SYSERR = new LogTarget() { + public void log(Object ... msgs) { + PrintStream out = System.err; + out.print(Chrono.dateFmt.format(new Date())); + out.print(": "); + for(Object str : msgs) { + out.print(str.toString()); + out.print(' '); + } + out.println(); + out.flush(); + } + + public void log(Throwable t, Object ... msgs) { + PrintStream out = System.err; + out.print(Chrono.dateFmt.format(new Date())); + out.print(": "); + for(Object str : msgs) { + out.print(str.toString()); + out.print(' '); + } + out.println(); + t.printStackTrace(out); + } + + public boolean isLoggable() { + return true; + } + @Override + public void printf(String fmt, Object ... vars) { + log(String.format(fmt,vars)); + } + + }; }; \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Objectifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Objectifier.java index 039855e1..30c9c1da 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Objectifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Objectifier.java @@ -32,26 +32,26 @@ package org.onap.aaf.misc.env; * the creation of an uninitialized object. */ public interface Objectifier extends LifeCycle { - /** - * Marshal to Object T from a String, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return T - * @throws APIException - */ - public abstract T objectify(Env env, String input) throws APIException; + /** + * Marshal to Object T from a String, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return T + * @throws APIException + */ + public abstract T objectify(Env env, String input) throws APIException; - /** - * Create a new object of type T. This is often more efficiently done with - * the underlying XML (or other) Library. - * @return T - * @throws APIException - */ - public abstract T newInstance() throws APIException; + /** + * Create a new object of type T. This is often more efficiently done with + * the underlying XML (or other) Library. + * @return T + * @throws APIException + */ + public abstract T newInstance() throws APIException; - + } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Slot.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Slot.java index f79d12d4..33a65752 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Slot.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Slot.java @@ -40,63 +40,63 @@ package org.onap.aaf.misc.env; * Slot's are used to store and retrieve data in the transaction's State object. */ public final class Slot { - - /* - * The name of the Slot. - */ - private final String key; - - /* - * The index of the State's local map associated with this Slot. - */ - final int slot; - - /** - * Constructs a new Slot. - * - * @param index - * The index of State's local map this Slot is associated with. - * @param name - * The name of the Slot's key. - */ - Slot(int index, String name) { - slot = index; - key = name; - } - - /** - * Debug method only to print key=slot pairs. - */ - public String toString() { - return key + '=' + slot; - } - - /** - * Returns the name of this Slot's key. - * - * @return - * The name of this Slot's key. - */ - public String getKey() { - return key; - } - - /** - * Put an Object into the slot on the State - * @param state - * @param obj - */ - public void put(Object[] state, Object obj) { - state[slot]=obj; - } + + /* + * The name of the Slot. + */ + private final String key; + + /* + * The index of the State's local map associated with this Slot. + */ + final int slot; + + /** + * Constructs a new Slot. + * + * @param index + * The index of State's local map this Slot is associated with. + * @param name + * The name of the Slot's key. + */ + Slot(int index, String name) { + slot = index; + key = name; + } + + /** + * Debug method only to print key=slot pairs. + */ + public String toString() { + return key + '=' + slot; + } + + /** + * Returns the name of this Slot's key. + * + * @return + * The name of this Slot's key. + */ + public String getKey() { + return key; + } + + /** + * Put an Object into the slot on the State + * @param state + * @param obj + */ + public void put(Object[] state, Object obj) { + state[slot]=obj; + } - /** - * Get an Object from the slot on the State - * @param state - * @param obj - */ - public Object get(Object[] state) { - return state[slot]; - } + /** + * Get an Object from the slot on the State + * @param state + * @param obj + */ + public Object get(Object[] state) { + return state[slot]; + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/StaticSlot.java b/misc/env/src/main/java/org/onap/aaf/misc/env/StaticSlot.java index 35bad1ba..0bff6a06 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/StaticSlot.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/StaticSlot.java @@ -41,45 +41,45 @@ package org.onap.aaf.misc.env; */ public final class StaticSlot { - /* - * The name of the StaticSlot. - */ - private final String key; - - /* - * The index of the Organizer's static map associated with this StaticSlot. - */ - final int slot; - - /** - * Constructs a new StaticSlot. - * - * @param index - * The index of Organizer's static map this StaticSlot is associated with. - * @param name - * The name of the StaticSlot's key. - */ - StaticSlot(int index, String name) { - slot = index; - key = name; - } - - /** - * Debug method only to print key=slot pairs. - */ - public String toString() { - return key + '=' + slot; - } - - /** - * Returns the name of this StaticSlot's key. - * - * @return - * The name of this StaticSlot's key. - */ - public String getKey() { - return key; - } + /* + * The name of the StaticSlot. + */ + private final String key; + + /* + * The index of the Organizer's static map associated with this StaticSlot. + */ + final int slot; + + /** + * Constructs a new StaticSlot. + * + * @param index + * The index of Organizer's static map this StaticSlot is associated with. + * @param name + * The name of the StaticSlot's key. + */ + StaticSlot(int index, String name) { + slot = index; + key = name; + } + + /** + * Debug method only to print key=slot pairs. + */ + public String toString() { + return key + '=' + slot; + } + + /** + * Returns the name of this StaticSlot's key. + * + * @return + * The name of this StaticSlot's key. + */ + public String getKey() { + return key; + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Store.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Store.java index 43f5f521..8c810783 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Store.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Store.java @@ -24,85 +24,85 @@ package org.onap.aaf.misc.env; import java.util.List; public interface Store { - /** - * Returns the Slot assigned to the supplied name. - * - * @param name - * The name of the Slot to acquire. - * @return - * The Slot associated with the supplied name. - */ - public abstract Slot slot(String name); + /** + * Returns the Slot assigned to the supplied name. + * + * @param name + * The name of the Slot to acquire. + * @return + * The Slot associated with the supplied name. + */ + public abstract Slot slot(String name); - /** - * Returns the existing Slot associated with the supplied name, or null if it doesn't exist. - * - * @param name - * The name of the Slot to get. - * @return - * The Slot assigned to the supplied name, or null if it doesn't exist. - * - */ - public abstract Slot existingSlot(String name); + /** + * Returns the existing Slot associated with the supplied name, or null if it doesn't exist. + * + * @param name + * The name of the Slot to get. + * @return + * The Slot assigned to the supplied name, or null if it doesn't exist. + * + */ + public abstract Slot existingSlot(String name); - /** - * Returns the names used while creating Slots in a List - * - * @return - */ - public abstract List existingSlotNames(); + /** + * Returns the names used while creating Slots in a List + * + * @return + */ + public abstract List existingSlotNames(); - /** - * Returns the StaticSlot assigned to the supplied name. - * - * @param name - * The name of the StaticSlot to acquire. - * @return - * The StaticSlot associated with the supplied name. - */ - public abstract StaticSlot staticSlot(String name); + /** + * Returns the StaticSlot assigned to the supplied name. + * + * @param name + * The name of the StaticSlot to acquire. + * @return + * The StaticSlot associated with the supplied name. + */ + public abstract StaticSlot staticSlot(String name); - /** - * Returns the names used while creating Static Slots in a List - * - * @return - */ - public abstract List existingStaticSlotNames(); - - /** - * Store the supplied value in the StaticSlot of the Organizer's static state. - * - * @param slot - * The StaticSlot used to store the object. - * @param value - * The object to store. - */ - public abstract void put(StaticSlot slot, Object value); + /** + * Returns the names used while creating Static Slots in a List + * + * @return + */ + public abstract List existingStaticSlotNames(); + + /** + * Store the supplied value in the StaticSlot of the Organizer's static state. + * + * @param slot + * The StaticSlot used to store the object. + * @param value + * The object to store. + */ + public abstract void put(StaticSlot slot, Object value); - /** - * Returns an Object from the Organizer's static state, or the Default if null - * - * @param slot - * The StaticSlot to retrieve the data from. - * @return - * The Object located in the supplied StaticSlot of the Organizer's static state. - */ - public abstract T get(StaticSlot slot, T dflt); + /** + * Returns an Object from the Organizer's static state, or the Default if null + * + * @param slot + * The StaticSlot to retrieve the data from. + * @return + * The Object located in the supplied StaticSlot of the Organizer's static state. + */ + public abstract T get(StaticSlot slot, T dflt); - /** - * Returns an Object from the Organizer's static state - * - * @param slot - * The StaticSlot to retrieve the data from. - * @return - * The Object located in the supplied StaticSlot of the Organizer's static state. - */ - public abstract T get(StaticSlot slot); + /** + * Returns an Object from the Organizer's static state + * + * @param slot + * The StaticSlot to retrieve the data from. + * @return + * The Object located in the supplied StaticSlot of the Organizer's static state. + */ + public abstract T get(StaticSlot slot); -// /** -// * Transfer (targeted) Args to Slots -// * -// * Transfer Strings with format "tag=value" into Static Slots -// */ -// public abstract void transfer(String args[], String ... tagss); +// /** +// * Transfer (targeted) Args to Slots +// * +// * Transfer Strings with format "tag=value" into Static Slots +// */ +// public abstract void transfer(String args[], String ... tagss); } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java b/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java index 685bfb6e..b8a8e03a 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java @@ -36,205 +36,205 @@ import java.util.Properties; public class StoreImpl implements Store { - /* - * The re-adjustment factor for growing the Static State array. - */ - private static final int growSize = 10; - - /* - * The index reference for Slot assignment. - */ - private int local; - - /* - * The index reference for StaticSlot assignment. - */ - private int stat; - - /* - * The name/slot map for local (transaction specific) State. - */ - private HashMap localMap; - - /* - * The name/slot map for Static State. - */ - private HashMap staticMap; - - private Object[] staticState; - - public StoreImpl() { - staticState = new Object[growSize]; - staticMap = new HashMap<>(); - localMap = new HashMap<>(); - } - - public StoreImpl(String tag) { - staticState = new Object[growSize]; - staticMap = new HashMap<>(); - localMap = new HashMap<>(); - } - - - public StoreImpl(String tag, String[] args) { - staticState = new Object[growSize]; - staticMap = new HashMap<>(); - localMap = new HashMap<>(); - - if(tag!=null) { - String tequals = tag + '='; - for(String arg : args) { - if(arg.startsWith(tequals) && !arg.equals(tequals)) { // needs to have something after = - Properties props = new Properties(); - for(String f : Split.split(File.pathSeparatorChar,arg.substring(tequals.length()))) { - moreProps(new File(f),props); - } - for(Entry es : props.entrySet()) { - put(staticSlot(es.getKey().toString()),es.getValue()); - } - } - } - } - - // Make sure properties on command line override those in Props - propsFromArgs(tag,args); - } - - public StoreImpl(String tag, Properties props) { - staticState = new Object[growSize]; - staticMap = new HashMap<>(); - localMap = new HashMap<>(); - - if(tag!=null) { - String fname = props.getProperty(tag); - if(fname!=null) { - for(String f : Split.split(File.pathSeparatorChar,fname)) { - if(!moreProps(new File(f),props)) { - System.err.println("Unable to load Properties from " + f); - } - } - } - } - - for(Entry es : props.entrySet()) { - put(staticSlot(es.getKey().toString()),es.getValue()); - } - } - - public void propsFromArgs(String tag, String[] args) { - if(tag!=null) { - for(String arg : args) { - String sarg[] = Split.split('=',arg); - if(sarg.length==2) { - if(tag.equals(sarg[0])) { - for(String fname : Split.split(File.pathSeparatorChar,sarg[1])) { - moreProps(new File(fname),null /* no target */); - } - } - put(staticSlot(sarg[0]),sarg[1]); - } - } - } - } - - private boolean moreProps(File f, Properties target) { - if(f.exists()) { - Properties props = new Properties(); - try { - FileInputStream fis = new FileInputStream(f); - try { - props.load(fis); - if(target!=null) { - target.load(fis); - } - } finally { - fis.close(); - } - } catch(IOException e) { - System.err.println(e); - } - for(Entry es : props.entrySet()) { - put(staticSlot(es.getKey().toString()),es.getValue()); - } - return true; - } else { - return false; - } - } - - public Object[] newTransState() { - return new Object[local]; - } - - /* (non-Javadoc) - * @see com.att.env.Store#slot(java.lang.String) - */ - public synchronized Slot slot(String name) { - name = name == null ? "" : name.trim(); - Slot slot = localMap.get(name); - if (slot == null) { - slot = new Slot(local++, name); - localMap.put(name, slot); - } - return slot; - } - - - /* (non-Javadoc) - * @see com.att.env.Store#existingSlot(java.lang.String) - */ - public Slot existingSlot(String name) { - return localMap.get(name); - } - - /* (non-Javadoc) - * @see com.att.env.Store#existingSlotNames() - */ - public List existingSlotNames() { - return new ArrayList<>(localMap.keySet()); - } - - /* (non-Javadoc) - * @see com.att.env.Store#staticSlot(java.lang.String) - */ - public synchronized StaticSlot staticSlot(String name) { - name = name == null ? "" : name.trim(); - StaticSlot slot = staticMap.get(name); - if (slot == null) { - if (stat%growSize == 0) { - Object[] temp = staticState; - staticState = new Object[temp.length+growSize]; - System.arraycopy(temp, 0, staticState, 0, temp.length); - } - slot = new StaticSlot(stat++, name); - staticMap.put(name, slot); - } - return slot; - } - - /* (non-Javadoc) - * @see com.att.env.Store#put(com.att.env.StaticSlot, java.lang.Object) - */ - public void put(StaticSlot slot, Object value) { - staticState[slot.slot] = value; - } - - /* (non-Javadoc) - * @see com.att.env.Store#get(com.att.env.StaticSlot T defaultObject) - */ - @SuppressWarnings("unchecked") - public T get(StaticSlot sslot,T dflt) { - T t = (T)staticState[sslot.slot]; - return t==null?dflt:t; - } - - @SuppressWarnings("unchecked") - public T get(StaticSlot sslot) { - return (T)staticState[sslot.slot]; - } - - public List existingStaticSlotNames() { - return new ArrayList<>(staticMap.keySet()); - } + /* + * The re-adjustment factor for growing the Static State array. + */ + private static final int growSize = 10; + + /* + * The index reference for Slot assignment. + */ + private int local; + + /* + * The index reference for StaticSlot assignment. + */ + private int stat; + + /* + * The name/slot map for local (transaction specific) State. + */ + private HashMap localMap; + + /* + * The name/slot map for Static State. + */ + private HashMap staticMap; + + private Object[] staticState; + + public StoreImpl() { + staticState = new Object[growSize]; + staticMap = new HashMap<>(); + localMap = new HashMap<>(); + } + + public StoreImpl(String tag) { + staticState = new Object[growSize]; + staticMap = new HashMap<>(); + localMap = new HashMap<>(); + } + + + public StoreImpl(String tag, String[] args) { + staticState = new Object[growSize]; + staticMap = new HashMap<>(); + localMap = new HashMap<>(); + + if(tag!=null) { + String tequals = tag + '='; + for(String arg : args) { + if(arg.startsWith(tequals) && !arg.equals(tequals)) { // needs to have something after = + Properties props = new Properties(); + for(String f : Split.split(File.pathSeparatorChar,arg.substring(tequals.length()))) { + moreProps(new File(f),props); + } + for(Entry es : props.entrySet()) { + put(staticSlot(es.getKey().toString()),es.getValue()); + } + } + } + } + + // Make sure properties on command line override those in Props + propsFromArgs(tag,args); + } + + public StoreImpl(String tag, Properties props) { + staticState = new Object[growSize]; + staticMap = new HashMap<>(); + localMap = new HashMap<>(); + + if(tag!=null) { + String fname = props.getProperty(tag); + if(fname!=null) { + for(String f : Split.split(File.pathSeparatorChar,fname)) { + if(!moreProps(new File(f),props)) { + System.err.println("Unable to load Properties from " + f); + } + } + } + } + + for(Entry es : props.entrySet()) { + put(staticSlot(es.getKey().toString()),es.getValue()); + } + } + + public void propsFromArgs(String tag, String[] args) { + if(tag!=null) { + for(String arg : args) { + String sarg[] = Split.split('=',arg); + if(sarg.length==2) { + if(tag.equals(sarg[0])) { + for(String fname : Split.split(File.pathSeparatorChar,sarg[1])) { + moreProps(new File(fname),null /* no target */); + } + } + put(staticSlot(sarg[0]),sarg[1]); + } + } + } + } + + private boolean moreProps(File f, Properties target) { + if(f.exists()) { + Properties props = new Properties(); + try { + FileInputStream fis = new FileInputStream(f); + try { + props.load(fis); + if(target!=null) { + target.load(fis); + } + } finally { + fis.close(); + } + } catch(IOException e) { + System.err.println(e); + } + for(Entry es : props.entrySet()) { + put(staticSlot(es.getKey().toString()),es.getValue()); + } + return true; + } else { + return false; + } + } + + public Object[] newTransState() { + return new Object[local]; + } + + /* (non-Javadoc) + * @see com.att.env.Store#slot(java.lang.String) + */ + public synchronized Slot slot(String name) { + name = name == null ? "" : name.trim(); + Slot slot = localMap.get(name); + if (slot == null) { + slot = new Slot(local++, name); + localMap.put(name, slot); + } + return slot; + } + + + /* (non-Javadoc) + * @see com.att.env.Store#existingSlot(java.lang.String) + */ + public Slot existingSlot(String name) { + return localMap.get(name); + } + + /* (non-Javadoc) + * @see com.att.env.Store#existingSlotNames() + */ + public List existingSlotNames() { + return new ArrayList<>(localMap.keySet()); + } + + /* (non-Javadoc) + * @see com.att.env.Store#staticSlot(java.lang.String) + */ + public synchronized StaticSlot staticSlot(String name) { + name = name == null ? "" : name.trim(); + StaticSlot slot = staticMap.get(name); + if (slot == null) { + if (stat%growSize == 0) { + Object[] temp = staticState; + staticState = new Object[temp.length+growSize]; + System.arraycopy(temp, 0, staticState, 0, temp.length); + } + slot = new StaticSlot(stat++, name); + staticMap.put(name, slot); + } + return slot; + } + + /* (non-Javadoc) + * @see com.att.env.Store#put(com.att.env.StaticSlot, java.lang.Object) + */ + public void put(StaticSlot slot, Object value) { + staticState[slot.slot] = value; + } + + /* (non-Javadoc) + * @see com.att.env.Store#get(com.att.env.StaticSlot T defaultObject) + */ + @SuppressWarnings("unchecked") + public T get(StaticSlot sslot,T dflt) { + T t = (T)staticState[sslot.slot]; + return t==null?dflt:t; + } + + @SuppressWarnings("unchecked") + public T get(StaticSlot sslot) { + return (T)staticState[sslot.slot]; + } + + public List existingStaticSlotNames() { + return new ArrayList<>(staticMap.keySet()); + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Stringifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Stringifier.java index c6e0dbd1..293d7c15 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Stringifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Stringifier.java @@ -28,18 +28,18 @@ package org.onap.aaf.misc.env; * Stringifier abstracts the marshaling of a String to an Object */ public interface Stringifier extends LifeCycle { - - /** - * Marshal from a String to an Object T, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return String - * @throws APIException - */ - public abstract String stringify(Env env, T input, boolean ... options) throws APIException; - + + /** + * Marshal from a String to an Object T, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return String + * @throws APIException + */ + public abstract String stringify(Env env, T input, boolean ... options) throws APIException; + } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java b/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java index 78f4a617..02018707 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java @@ -35,82 +35,82 @@ package org.onap.aaf.misc.env; * */ public abstract class TimeTaken { - public final long start; - protected long end, size; - public final int flag; - public final String name; - - /** - * The name is as it will appear when written to output (abstract method) - * - * The flag is an integer which can be System type (XML, REMOTE, etc), or End User defined for reporting purposes - * - * @param name - * @param flag - */ - public TimeTaken(String name, int flag) { - start = System.nanoTime(); - this.flag = flag; - this.name = name; - size = -1; - } + public final long start; + protected long end, size; + public final int flag; + public final String name; + + /** + * The name is as it will appear when written to output (abstract method) + * + * The flag is an integer which can be System type (XML, REMOTE, etc), or End User defined for reporting purposes + * + * @param name + * @param flag + */ + public TimeTaken(String name, int flag) { + start = System.nanoTime(); + this.flag = flag; + this.name = name; + size = -1; + } - /** - * Call this when process is done to state ending time.

    - * - * It is exceedingly prudent to wrap the process called with a try-finally:

    - * - *

    -	 *   TimeTaken tt = env.startSubTime();
    -	 *   try {
    -	 *       process.me(); // code to be timed.
    -	 *   } finally {
    -	 *   	 tt.done();
    -	 *   }
    -	 * 
    - */ - public void done() { - end = System.nanoTime(); - } - - - /** - * For sizable contents, set the size. Implementations can simply write a no-op if they don't wish to - * store the size. - * - * @param size - */ - public void size(long theSize) { - size = theSize; - } - - /** - * Give readonly access to End, which isn't final - * @return - */ - public long end() { - return end; - } - - /** - * Time is taken in NanoSeconds. This method converts to decimals of Milliseconds - * @return - */ - public float millis() { - return (end-start)/1000000f; - } - /** - * Write self to a String Builder (for making Audits) - * @param sb - */ - public abstract void output(StringBuilder sb); - - /** - * For Debugging - */ - public String toString() { - return name + ' ' + millis() + "ms " + (size>0?Long.toString(size):""); - } - -} + /** + * Call this when process is done to state ending time.

    + * + * It is exceedingly prudent to wrap the process called with a try-finally:

    + * + *

    +     *   TimeTaken tt = env.startSubTime();
    +     *   try {
    +     *       process.me(); // code to be timed.
    +     *   } finally {
    +     *        tt.done();
    +     *   }
    +     * 
    + */ + public void done() { + end = System.nanoTime(); + } + + + /** + * For sizable contents, set the size. Implementations can simply write a no-op if they don't wish to + * store the size. + * + * @param size + */ + public void size(long theSize) { + size = theSize; + } + + /** + * Give readonly access to End, which isn't final + * @return + */ + public long end() { + return end; + } + + /** + * Time is taken in NanoSeconds. This method converts to decimals of Milliseconds + * @return + */ + public float millis() { + return (end-start)/1000000f; + } + /** + * Write self to a String Builder (for making Audits) + * @param sb + */ + public abstract void output(StringBuilder sb); + + /** + * For Debugging + */ + public String toString() { + return name + ' ' + millis() + "ms " + (size>0?Long.toString(size):""); + } + +} diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/Trans.java b/misc/env/src/main/java/org/onap/aaf/misc/env/Trans.java index 24473751..bb66c0f6 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/Trans.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/Trans.java @@ -39,36 +39,36 @@ package org.onap.aaf.misc.env; * */ public interface Trans extends Env { - /** - * Add a completed entry in the Audit Trail for tracking purposes. - * - * @param text - */ - public void checkpoint(String text); + /** + * Add a completed entry in the Audit Trail for tracking purposes. + * + * @param text + */ + public void checkpoint(String text); - /** - * Add a completed entry in the Audit Trail for tracking purposes, and combine flag with "CHECKPOINT" - * - * @param text - */ - public void checkpoint(String text, int additionalFlag); + /** + * Add a completed entry in the Audit Trail for tracking purposes, and combine flag with "CHECKPOINT" + * + * @param text + */ + public void checkpoint(String text, int additionalFlag); - /** - * Output an Audit Trail onto the StringBuilder - * - * Load metrics into an array of floats from passed in Flags - * - * @param flag - * @param sb - * @return - */ - public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flag); + /** + * Output an Audit Trail onto the StringBuilder + * + * Load metrics into an array of floats from passed in Flags + * + * @param flag + * @param sb + * @return + */ + public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flag); - public Metric auditTrail(int indent, StringBuilder sb, int ... flag); + public Metric auditTrail(int indent, StringBuilder sb, int ... flag); - public class Metric { - public float[] buckets; - public float total; - public int entries; - } + public class Metric { + public float[] buckets; + public float total; + public int entries; + } } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/TransCreate.java b/misc/env/src/main/java/org/onap/aaf/misc/env/TransCreate.java index 1ed4dcd2..d311c3ed 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/TransCreate.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/TransCreate.java @@ -22,5 +22,5 @@ package org.onap.aaf.misc.env; public interface TransCreate { - public TRANS newTrans(); + public TRANS newTrans(); } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/TransStore.java b/misc/env/src/main/java/org/onap/aaf/misc/env/TransStore.java index e9c1b390..5a8f7620 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/TransStore.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/TransStore.java @@ -22,36 +22,36 @@ package org.onap.aaf.misc.env; public interface TransStore extends Trans { - /** - * Returns the Slot assigned to the supplied name. - * - * @param name - * The name of the Slot to acquire. - * @return - * The Slot associated with the supplied name. - */ - public abstract Slot slot(String name); - - /** - * Put data into the right slot - */ - public void put(Slot slot, Object value); + /** + * Returns the Slot assigned to the supplied name. + * + * @param name + * The name of the Slot to acquire. + * @return + * The Slot associated with the supplied name. + */ + public abstract Slot slot(String name); + + /** + * Put data into the right slot + */ + public void put(Slot slot, Object value); - /** - * Get data from the right slot - * - * This will do a cast to the expected type derived from Default - */ - public T get(Slot slot, T deflt); + /** + * Get data from the right slot + * + * This will do a cast to the expected type derived from Default + */ + public T get(Slot slot, T deflt); - /** - * Returns an Object from the Organizer's static state, or the Default if null - * - * @param slot - * The StaticSlot to retrieve the data from. - * @return - * The Object located in the supplied StaticSlot of the Organizer's static state. - */ - public abstract T get(StaticSlot slot, T dflt); - + /** + * Returns an Object from the Organizer's static state, or the Default if null + * + * @param slot + * The StaticSlot to retrieve the data from. + * @return + * The Object located in the supplied StaticSlot of the Organizer's static state. + */ + public abstract T get(StaticSlot slot, T dflt); + } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java index e378e2c3..b86b4fbb 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java @@ -33,182 +33,182 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.TransStore; public abstract class AbsTrans implements TransStore { - private static final float[] EMPTYF = new float[0]; - private static final Object[] EMPTYO = new Object[0]; - - protected ENV delegate; - protected List trail = new ArrayList<>(30); - private Object[] state; - - + private static final float[] EMPTYF = new float[0]; + private static final Object[] EMPTYO = new Object[0]; + + protected ENV delegate; + protected List trail = new ArrayList<>(30); + private Object[] state; + + public AbsTrans(ENV delegate) { - this.delegate = delegate; - state = delegate instanceof StoreImpl?((StoreImpl) delegate).newTransState():EMPTYO; - } - - // @Override - public LogTarget fatal() { - return delegate.fatal(); - } - -// @Override - public LogTarget error() { - return delegate.error(); - } - -// @Override - public LogTarget audit() { - return delegate.audit(); - } - -// @Override - public LogTarget init() { - return delegate.init(); - } - -// @Override - public LogTarget warn() { - return delegate.warn(); - } - -// @Override - public LogTarget info() { - return delegate.info(); - } - -// @Override - public LogTarget debug() { - return delegate.debug(); - } - -// @Override - public LogTarget trace() { - return delegate.trace(); - } - - /** - * Let the final Trans Implementation choose the exact kind of TimeTaken to use - * @param name - * @param flag - * @return - */ - protected abstract TimeTaken newTimeTaken(String name, int flag); - -// @Override - public final TimeTaken start(String name, int flag) { - TimeTaken tt = newTimeTaken(name,flag); - trail.add(tt); - return tt; - } - -// @Override - public final void checkpoint(String name) { - TimeTaken tt = newTimeTaken(name,CHECKPOINT); - tt.done(); - trail.add(tt); - } - - public final void checkpoint(String name, int additionalFlag) { - TimeTaken tt = newTimeTaken(name,CHECKPOINT|additionalFlag); - trail.add(tt); - tt.done(); - } - - @Override - public Metric auditTrail(int indent, StringBuilder sb, int ... flags) { - return auditTrail(info(),indent,sb,flags); - } - - @Override - public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flags) { - Metric metric = new Metric(); - int last = (metric.entries = trail.size()) -1; - metric.buckets = flags.length==0?EMPTYF:new float[flags.length]; - if(last>=0) { - TimeTaken first = trail.get(0); - // If first entry is sub, then it's actually the last "end" as well - // otherwise, check end - //long end = (first.flag&SUB)==SUB?first.end():trail.get(last).end(); - long end = trail.get(last).end(); - metric.total = (end - first.start) / 1000000f; - } - - if(sb==null) { - for(TimeTaken tt : trail) { - float ms = tt.millis(); - for(int i=0;i stack = new Stack(); - for(TimeTaken tt : trail) { - // Create Indentation based on SUB - while(!stack.isEmpty() && tt.end()>stack.peek()) { - --indent; - stack.pop(); - } - for(int i=0;i T get(Slot slot, T deflt) { - Object o; - try { - o = slot.get(state); - } catch(ArrayIndexOutOfBoundsException e) { - // Env State Size has changed because of dynamic Object creation... Rare event, but needs to be covered - Object[] temp = ((StoreImpl) delegate).newTransState(); - System.arraycopy(state, 0, temp, 0, state.length); - state = temp; - o=null; - } - return o==null?deflt:(T)o; - } + this.delegate = delegate; + state = delegate instanceof StoreImpl?((StoreImpl) delegate).newTransState():EMPTYO; + } + + // @Override + public LogTarget fatal() { + return delegate.fatal(); + } + +// @Override + public LogTarget error() { + return delegate.error(); + } + +// @Override + public LogTarget audit() { + return delegate.audit(); + } + +// @Override + public LogTarget init() { + return delegate.init(); + } + +// @Override + public LogTarget warn() { + return delegate.warn(); + } + +// @Override + public LogTarget info() { + return delegate.info(); + } + +// @Override + public LogTarget debug() { + return delegate.debug(); + } + +// @Override + public LogTarget trace() { + return delegate.trace(); + } + + /** + * Let the final Trans Implementation choose the exact kind of TimeTaken to use + * @param name + * @param flag + * @return + */ + protected abstract TimeTaken newTimeTaken(String name, int flag); + +// @Override + public final TimeTaken start(String name, int flag) { + TimeTaken tt = newTimeTaken(name,flag); + trail.add(tt); + return tt; + } + +// @Override + public final void checkpoint(String name) { + TimeTaken tt = newTimeTaken(name,CHECKPOINT); + tt.done(); + trail.add(tt); + } + + public final void checkpoint(String name, int additionalFlag) { + TimeTaken tt = newTimeTaken(name,CHECKPOINT|additionalFlag); + trail.add(tt); + tt.done(); + } + + @Override + public Metric auditTrail(int indent, StringBuilder sb, int ... flags) { + return auditTrail(info(),indent,sb,flags); + } + + @Override + public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flags) { + Metric metric = new Metric(); + int last = (metric.entries = trail.size()) -1; + metric.buckets = flags.length==0?EMPTYF:new float[flags.length]; + if(last>=0) { + TimeTaken first = trail.get(0); + // If first entry is sub, then it's actually the last "end" as well + // otherwise, check end + //long end = (first.flag&SUB)==SUB?first.end():trail.get(last).end(); + long end = trail.get(last).end(); + metric.total = (end - first.start) / 1000000f; + } + + if(sb==null) { + for(TimeTaken tt : trail) { + float ms = tt.millis(); + for(int i=0;i stack = new Stack(); + for(TimeTaken tt : trail) { + // Create Indentation based on SUB + while(!stack.isEmpty() && tt.end()>stack.peek()) { + --indent; + stack.pop(); + } + for(int i=0;i T get(Slot slot, T deflt) { + Object o; + try { + o = slot.get(state); + } catch(ArrayIndexOutOfBoundsException e) { + // Env State Size has changed because of dynamic Object creation... Rare event, but needs to be covered + Object[] temp = ((StoreImpl) delegate).newTransState(); + System.arraycopy(state, 0, temp, 0, state.length); + state = temp; + o=null; + } + return o==null?deflt:(T)o; + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTransJAXB.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTransJAXB.java index c20589a3..5576a1a0 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTransJAXB.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTransJAXB.java @@ -30,28 +30,28 @@ import org.onap.aaf.misc.env.EnvJAXB; import org.onap.aaf.misc.env.TransJAXB; public abstract class AbsTransJAXB extends AbsTrans implements TransJAXB { - public AbsTransJAXB(EnvJAXB env) { - super(env); - } - -// @Override - public DataFactory newDataFactory(Class... classes) throws APIException { - return delegate.newDataFactory(classes); - } - -// @Override - public DataFactory newDataFactory(Schema schema, Class... classes) throws APIException { - return delegate.newDataFactory(schema, classes); - } - -// @Override - public DataFactory newDataFactory(QName qName, Class... classes) throws APIException { - return delegate.newDataFactory(qName, classes); - } - -// @Override - public DataFactory newDataFactory(Schema schema, QName qName, Class... classes) throws APIException { - return delegate.newDataFactory(schema, qName, classes); - } + public AbsTransJAXB(EnvJAXB env) { + super(env); + } + +// @Override + public DataFactory newDataFactory(Class... classes) throws APIException { + return delegate.newDataFactory(classes); + } + +// @Override + public DataFactory newDataFactory(Schema schema, Class... classes) throws APIException { + return delegate.newDataFactory(schema, classes); + } + +// @Override + public DataFactory newDataFactory(QName qName, Class... classes) throws APIException { + return delegate.newDataFactory(qName, classes); + } + +// @Override + public DataFactory newDataFactory(Schema schema, QName qName, Class... classes) throws APIException { + return delegate.newDataFactory(schema, qName, classes); + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java index cd62a7e5..94f7d47b 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java @@ -57,296 +57,296 @@ import org.onap.aaf.misc.env.util.Split; * */ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate{ - protected LogTarget fatal=LogTarget.SYSERR; - protected LogTarget error=LogTarget.SYSERR; - protected LogTarget audit=LogTarget.SYSOUT; - protected LogTarget init=LogTarget.SYSOUT; - protected LogTarget warn=LogTarget.SYSERR; - protected LogTarget info=LogTarget.SYSOUT; - protected LogTarget debug=LogTarget.NULL; - protected LogTarget trace=LogTarget.NULL; -// protected Map props; - -// private boolean sysprops; - - public BasicEnv(String ... args) { - super(null,args); - } - - public BasicEnv(String tag, String[] args) { - super(tag, args); - } - - - /** - * Suitable for use in Applets... obtain all the values - * listed for the variable String arg "tags" - */ - public BasicEnv(Applet applet, String ... tags) { - super(null, tags); -// props = new HashMap<>(); -// String value; -// for(int i=0;i=0) { - sb.append(" size: "); - sb.append(Long.toString(size)); - } - } - } - }; - } - - // @Override - public String getProperty(String key) { - return get(staticSlot(key),null); - } - - public Properties getProperties(String ... filter) { - Properties props = new Properties(); - boolean yes; - for(String key : existingStaticSlotNames()) { - if(filter.length>0) { - yes = false; - for(String f : filter) { - if(key.startsWith(f)) { - yes = true; - break; - } - } - } else { - yes = true; - } - if(yes) { - String value = getProperty(key); - if(value!=null) { - props.put(key, value); - } - } - } - return props; - } - - // @Override - public String getProperty(String key, String defaultValue) { - return get(staticSlot(key),defaultValue); - } - - // @Override - public String setProperty(String key, String value) { - put(staticSlot(key),value==null?null:value.trim()); - return value; - } - - protected Decryptor decryptor = Decryptor.NULL; - protected Encryptor encryptor = Encryptor.NULL; - - - public Decryptor decryptor() { - return decryptor; - } - - public void set(Decryptor newDecryptor) { - decryptor = newDecryptor; - } - - public Encryptor encryptor() { - return encryptor; - } - - public void set(Encryptor newEncryptor) { - encryptor = newEncryptor; - } - - -// @SuppressWarnings("unchecked") - // @Override - public DataFactory newDataFactory(Class... classes) throws APIException { -// if(String.class.isAssignableFrom(classes[0])) -// return (DataFactory) new StringDF(this); - return new JAXBDF(this,classes); - } - -// @SuppressWarnings("unchecked") - // @Override - public DataFactory newDataFactory(Schema schema, Class... classes) throws APIException { -// if(String.class.isAssignableFrom(classes[0])) -// return (DataFactory) new StringDF(this); - return new JAXBDF(this, schema, classes); - } - -// @SuppressWarnings("unchecked") - // @Override - public DataFactory newDataFactory(QName qName, Class ... classes) throws APIException { -// if(String.class.isAssignableFrom(classes[0])) -// return (DataFactory) new StringDF(this); - return new JAXBDF(this, qName, classes); - } - - // @Override - public DataFactory newDataFactory(Schema schema, QName qName, Class ... classes) throws APIException { - return new JAXBDF(this, schema, qName, classes); - } - - // @Override - public BasicTrans newTrans() { - return new BasicTrans(this); - } - - public void loadFromSystemPropsStartsWith(String ... str) { - for(String name : System.getProperties().stringPropertyNames()) { - for(String s : str) { - if(name.startsWith(s)) { - setProperty(name, System.getProperty(name)); - } - } - } - } - - /** - * - * - */ - public void loadToSystemPropsStartsWith(String ... str) { - String value; - for(String name : existingStaticSlotNames()) { - for(String s : str) { - if(name.startsWith(s)) { - if((value = getProperty(name))!=null) - System.setProperty(name,value); - } - } - } - } - - public void loadPropFiles(String tag, ClassLoader classloader) throws IOException { - String propfiles = getProperty(tag); - if(propfiles!=null) { - for(String pf : Split.splitTrim(File.pathSeparatorChar, propfiles)) { - InputStream is = classloader==null?null:classloader.getResourceAsStream(pf); - if(is==null) { - File f = new File(pf); - if(f.exists()) { - is = new FileInputStream(f); - } - } - if(is!=null) { - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - try { - String line; - while((line=br.readLine())!=null) { - line = line.trim(); - if(!line.startsWith("#")) { - String[] tv = Split.splitTrim('=', line); - if(tv.length==2) { - setProperty(tv[0],tv[1]); - } - } - } - } finally { - try { - br.close(); - } catch (IOException e) { - error().log(e); - } - } - } - } - } - } - - /** - * Create a StaticSlot, and load it from existing Properties - * - * @param name - * @param propName - * @return - */ - public synchronized StaticSlot staticSlot(String name, final String propName) { - StaticSlot ss = staticSlot(name); - put(ss,getProperty(propName)); - return ss; - } + protected LogTarget fatal=LogTarget.SYSERR; + protected LogTarget error=LogTarget.SYSERR; + protected LogTarget audit=LogTarget.SYSOUT; + protected LogTarget init=LogTarget.SYSOUT; + protected LogTarget warn=LogTarget.SYSERR; + protected LogTarget info=LogTarget.SYSOUT; + protected LogTarget debug=LogTarget.NULL; + protected LogTarget trace=LogTarget.NULL; +// protected Map props; + +// private boolean sysprops; + + public BasicEnv(String ... args) { + super(null,args); + } + + public BasicEnv(String tag, String[] args) { + super(tag, args); + } + + + /** + * Suitable for use in Applets... obtain all the values + * listed for the variable String arg "tags" + */ + public BasicEnv(Applet applet, String ... tags) { + super(null, tags); +// props = new HashMap<>(); +// String value; +// for(int i=0;i=0) { + sb.append(" size: "); + sb.append(Long.toString(size)); + } + } + } + }; + } + + // @Override + public String getProperty(String key) { + return get(staticSlot(key),null); + } + + public Properties getProperties(String ... filter) { + Properties props = new Properties(); + boolean yes; + for(String key : existingStaticSlotNames()) { + if(filter.length>0) { + yes = false; + for(String f : filter) { + if(key.startsWith(f)) { + yes = true; + break; + } + } + } else { + yes = true; + } + if(yes) { + String value = getProperty(key); + if(value!=null) { + props.put(key, value); + } + } + } + return props; + } + + // @Override + public String getProperty(String key, String defaultValue) { + return get(staticSlot(key),defaultValue); + } + + // @Override + public String setProperty(String key, String value) { + put(staticSlot(key),value==null?null:value.trim()); + return value; + } + + protected Decryptor decryptor = Decryptor.NULL; + protected Encryptor encryptor = Encryptor.NULL; + + + public Decryptor decryptor() { + return decryptor; + } + + public void set(Decryptor newDecryptor) { + decryptor = newDecryptor; + } + + public Encryptor encryptor() { + return encryptor; + } + + public void set(Encryptor newEncryptor) { + encryptor = newEncryptor; + } + + +// @SuppressWarnings("unchecked") + // @Override + public DataFactory newDataFactory(Class... classes) throws APIException { +// if(String.class.isAssignableFrom(classes[0])) +// return (DataFactory) new StringDF(this); + return new JAXBDF(this,classes); + } + +// @SuppressWarnings("unchecked") + // @Override + public DataFactory newDataFactory(Schema schema, Class... classes) throws APIException { +// if(String.class.isAssignableFrom(classes[0])) +// return (DataFactory) new StringDF(this); + return new JAXBDF(this, schema, classes); + } + +// @SuppressWarnings("unchecked") + // @Override + public DataFactory newDataFactory(QName qName, Class ... classes) throws APIException { +// if(String.class.isAssignableFrom(classes[0])) +// return (DataFactory) new StringDF(this); + return new JAXBDF(this, qName, classes); + } + + // @Override + public DataFactory newDataFactory(Schema schema, QName qName, Class ... classes) throws APIException { + return new JAXBDF(this, schema, qName, classes); + } + + // @Override + public BasicTrans newTrans() { + return new BasicTrans(this); + } + + public void loadFromSystemPropsStartsWith(String ... str) { + for(String name : System.getProperties().stringPropertyNames()) { + for(String s : str) { + if(name.startsWith(s)) { + setProperty(name, System.getProperty(name)); + } + } + } + } + + /** + * + * + */ + public void loadToSystemPropsStartsWith(String ... str) { + String value; + for(String name : existingStaticSlotNames()) { + for(String s : str) { + if(name.startsWith(s)) { + if((value = getProperty(name))!=null) + System.setProperty(name,value); + } + } + } + } + + public void loadPropFiles(String tag, ClassLoader classloader) throws IOException { + String propfiles = getProperty(tag); + if(propfiles!=null) { + for(String pf : Split.splitTrim(File.pathSeparatorChar, propfiles)) { + InputStream is = classloader==null?null:classloader.getResourceAsStream(pf); + if(is==null) { + File f = new File(pf); + if(f.exists()) { + is = new FileInputStream(f); + } + } + if(is!=null) { + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + try { + String line; + while((line=br.readLine())!=null) { + line = line.trim(); + if(!line.startsWith("#")) { + String[] tv = Split.splitTrim('=', line); + if(tv.length==2) { + setProperty(tv[0],tv[1]); + } + } + } + } finally { + try { + br.close(); + } catch (IOException e) { + error().log(e); + } + } + } + } + } + } + + /** + * Create a StaticSlot, and load it from existing Properties + * + * @param name + * @param propName + * @return + */ + public synchronized StaticSlot staticSlot(String name, final String propName) { + StaticSlot ss = staticSlot(name); + put(ss,getProperty(propName)); + return ss; + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicTrans.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicTrans.java index 05e62024..dbda57b5 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicTrans.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicTrans.java @@ -30,52 +30,52 @@ import org.onap.aaf.misc.env.TimeTaken; public class BasicTrans extends AbsTransJAXB { - - public BasicTrans(EnvJAXB env) { - super(env); - } + + public BasicTrans(EnvJAXB env) { + super(env); + } - @Override - protected TimeTaken newTimeTaken(String name, int flag) { - /** - * Note: could have created a different format for Time Taken, but using BasicEnv's instead - */ - return delegate.start(name, flag); - } - - public Slot slot(String name) { - return delegate.slot(name); - } + @Override + protected TimeTaken newTimeTaken(String name, int flag) { + /** + * Note: could have created a different format for Time Taken, but using BasicEnv's instead + */ + return delegate.start(name, flag); + } + + public Slot slot(String name) { + return delegate.slot(name); + } - public T get(StaticSlot slot) { - return delegate.get(slot); - } + public T get(StaticSlot slot) { + return delegate.get(slot); + } - public T get(StaticSlot slot, T dflt) { - return delegate.get(slot,dflt); - } + public T get(StaticSlot slot, T dflt) { + return delegate.get(slot,dflt); + } - public String setProperty(String tag, String value) { - delegate.setProperty(tag, value); - return value; - } + public String setProperty(String tag, String value) { + delegate.setProperty(tag, value); + return value; + } - public String getProperty(String tag) { - return delegate.getProperty(tag); - } + public String getProperty(String tag) { + return delegate.getProperty(tag); + } - public String getProperty(String tag, String deflt) { - return delegate.getProperty(tag, deflt); - } + public String getProperty(String tag, String deflt) { + return delegate.getProperty(tag, deflt); + } - @Override - public Decryptor decryptor() { - return delegate.decryptor(); - } + @Override + public Decryptor decryptor() { + return delegate.decryptor(); + } - @Override - public Encryptor encryptor() { - return delegate.encryptor(); - } + @Override + public Encryptor encryptor() { + return delegate.encryptor(); + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/EnvFactory.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/EnvFactory.java index 9bf4fdc5..aa0b947a 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/EnvFactory.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/EnvFactory.java @@ -33,36 +33,36 @@ import org.onap.aaf.misc.env.TransJAXB; */ public class EnvFactory { - public static final String SCHEMA_DIR = "env-schema_dir"; - public static final String DEFAULT_SCHEMA_DIR = "src/main/xsd"; - static BasicEnv singleton; + public static final String SCHEMA_DIR = "env-schema_dir"; + public static final String DEFAULT_SCHEMA_DIR = "src/main/xsd"; + static BasicEnv singleton; - static { - singleton = new BasicEnv(); - } - public static BasicEnv singleton() { - return singleton; - } - - public static void setSingleton(BasicEnv be) { - singleton = be; - } - - public static TransJAXB newTrans() { - return new BasicTrans(singleton); - } + static { + singleton = new BasicEnv(); + } + public static BasicEnv singleton() { + return singleton; + } + + public static void setSingleton(BasicEnv be) { + singleton = be; + } + + public static TransJAXB newTrans() { + return new BasicTrans(singleton); + } - public static TransJAXB newTrans(EnvJAXB env) { - return new BasicTrans(env); - } - - public static TransCreate transCreator() { - return new TransCreate() { - // @Override - public BasicTrans newTrans() { - return singleton.newTrans(); - } - }; - } + public static TransJAXB newTrans(EnvJAXB env) { + return new BasicTrans(env); + } + + public static TransCreate transCreator() { + return new TransCreate() { + // @Override + public BasicTrans newTrans() { + return singleton.newTrans(); + } + }; + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java index ac3e8b45..c8adfc78 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java @@ -36,55 +36,55 @@ import org.onap.aaf.misc.env.LogTarget; * */ public class JavaUtilLogTarget implements LogTarget { - private Level level; - private Logger log; + private Level level; + private Logger log; - public JavaUtilLogTarget(Logger logger, Level theLevel) { - log = logger; - level = theLevel; - } + public JavaUtilLogTarget(Logger logger, Level theLevel) { + log = logger; + level = theLevel; + } - public boolean isLoggable() { - return log.isLoggable(level); - } + public boolean isLoggable() { + return log.isLoggable(level); + } - public void log(Object ... msgs) { - if(log.isLoggable(level)) { - StringBuilder sb = new StringBuilder(); - String msg; - for(int i=0;i0) { - int sbl = sb.length(); - if(sbl>0) { - char last = sb.charAt(sbl-1); - if(" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' '); - } - sb.append(msg); - } - } - log.log(level, sb.toString()); - } - } + public void log(Object ... msgs) { + if(log.isLoggable(level)) { + StringBuilder sb = new StringBuilder(); + String msg; + for(int i=0;i0) { + int sbl = sb.length(); + if(sbl>0) { + char last = sb.charAt(sbl-1); + if(" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' '); + } + sb.append(msg); + } + } + log.log(level, sb.toString()); + } + } - public void log(Throwable e, Object ... msgs) { - String str = e.getLocalizedMessage(); - if(str==null) { - str = e.getMessage(); - } - if(str==null) { - str = e.getClass().getName(); - } - log.log(level,str,msgs); - } + public void log(Throwable e, Object ... msgs) { + String str = e.getLocalizedMessage(); + if(str==null) { + str = e.getMessage(); + } + if(str==null) { + str = e.getClass().getName(); + } + log.log(level,str,msgs); + } - /* (non-Javadoc) - * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[]) - */ - @Override - public void printf(String fmt, Object ... vars) { - if(log.isLoggable(level)) { - log.log(level,String.format(fmt,vars)); - } - } -} + /* (non-Javadoc) + * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[]) + */ + @Override + public void printf(String fmt, Object ... vars) { + if(log.isLoggable(level)) { + log.log(level,String.format(fmt,vars)); + } + } +} diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java index a5f118c9..81d9c1b2 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java @@ -37,73 +37,73 @@ import org.onap.aaf.misc.env.util.StringBuilderWriter; * */ public class Log4JLogTarget implements LogTarget { - private Level level; - private Logger log; + private Level level; + private Logger log; - public Log4JLogTarget(String loggerName, Level level) throws APIException { - this.level = level; - if (loggerName != null && loggerName.length() > 0) { - log = Logger.getLogger(loggerName); - } else { - log = Logger.getRootLogger(); - } - } + public Log4JLogTarget(String loggerName, Level level) throws APIException { + this.level = level; + if (loggerName != null && loggerName.length() > 0) { + log = Logger.getLogger(loggerName); + } else { + log = Logger.getRootLogger(); + } + } - // @Override - public boolean isLoggable() { - return log.isEnabledFor(level); - } + // @Override + public boolean isLoggable() { + return log.isEnabledFor(level); + } - // @Override - public void log(Object... msgs) { - log(null, msgs); - } + // @Override + public void log(Object... msgs) { + log(null, msgs); + } - // @Override - public void log(Throwable e, Object... msgs) { - if (log.isEnabledFor(level)) { - StringBuilder sb = new StringBuilder(); - - String msg; - if (e != null) { - e.printStackTrace(new PrintWriter(new StringBuilderWriter(sb))); - } - for (int i = 0; i < msgs.length; ++i) { - if(msgs[i]!=null) { - msg = msgs[i].toString(); - if (msg != null && msg.length() > 0) { - int sbl = sb.length(); - if (sbl > 0) { - char last = sb.charAt(sbl - 1); - if (" (.".indexOf(last) < 0 - && "().".indexOf(msg.charAt(0)) < 0) - sb.append(' '); - } - sb.append(msg); - } - } - } - log.log(level, sb.toString()); - } - } + // @Override + public void log(Throwable e, Object... msgs) { + if (log.isEnabledFor(level)) { + StringBuilder sb = new StringBuilder(); + + String msg; + if (e != null) { + e.printStackTrace(new PrintWriter(new StringBuilderWriter(sb))); + } + for (int i = 0; i < msgs.length; ++i) { + if(msgs[i]!=null) { + msg = msgs[i].toString(); + if (msg != null && msg.length() > 0) { + int sbl = sb.length(); + if (sbl > 0) { + char last = sb.charAt(sbl - 1); + if (" (.".indexOf(last) < 0 + && "().".indexOf(msg.charAt(0)) < 0) + sb.append(' '); + } + sb.append(msg); + } + } + } + log.log(level, sb.toString()); + } + } - /* (non-Javadoc) - * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[]) - */ - @Override - public void printf(String fmt, Object ... vars) { - if(log.isEnabledFor(level)) { - log.log(level,String.format(fmt,vars)); - } - } + /* (non-Javadoc) + * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[]) + */ + @Override + public void printf(String fmt, Object ... vars) { + if(log.isEnabledFor(level)) { + log.log(level,String.format(fmt,vars)); + } + } - public static void setLog4JEnv(String loggerName, BasicEnv env) throws APIException { - env.fatal = new Log4JLogTarget(loggerName,Level.FATAL); - env.error = new Log4JLogTarget(loggerName,Level.ERROR); - env.warn = env.audit = env.init = new Log4JLogTarget(loggerName,Level.WARN); - env.info = new Log4JLogTarget(loggerName,Level.INFO); - env.debug = new Log4JLogTarget(loggerName,Level.DEBUG); - env.trace = new Log4JLogTarget(loggerName,Level.TRACE); - } - + public static void setLog4JEnv(String loggerName, BasicEnv env) throws APIException { + env.fatal = new Log4JLogTarget(loggerName,Level.FATAL); + env.error = new Log4JLogTarget(loggerName,Level.ERROR); + env.warn = env.audit = env.init = new Log4JLogTarget(loggerName,Level.WARN); + env.info = new Log4JLogTarget(loggerName,Level.INFO); + env.debug = new Log4JLogTarget(loggerName,Level.DEBUG); + env.trace = new Log4JLogTarget(loggerName,Level.TRACE); + } + } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/NullLifeCycle.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/NullLifeCycle.java index 7e41f5df..3184f8c0 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/NullLifeCycle.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/NullLifeCycle.java @@ -51,9 +51,9 @@ import org.onap.aaf.misc.env.LifeCycle; * */ public class NullLifeCycle implements LifeCycle { - public void servicePrestart(Env env) throws APIException {} - public void threadPrestart(Env env) throws APIException {} - public void refresh(Env env) throws APIException {} - public void threadDestroy(Env env) throws APIException {} - public void serviceDestroy(Env env) throws APIException {} + public void servicePrestart(Env env) throws APIException {} + public void threadPrestart(Env env) throws APIException {} + public void refresh(Env env) throws APIException {} + public void threadDestroy(Env env) throws APIException {} + public void serviceDestroy(Env env) throws APIException {} } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java index e32532bc..dc7ee192 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java @@ -42,268 +42,268 @@ import org.onap.aaf.misc.env.old.IOStringifier; import org.onap.aaf.misc.env.old.OldDataFactory; public class JAXBDF extends BaseDataFactory implements OldDataFactory,IOObjectifier, IOStringifier { - // Package on purpose - EnvJAXB primaryEnv; - JAXBumar jumar; - JAXBmar jmar; - - public JAXBDF(EnvJAXB env, Class ... classes) throws APIException { - try { - primaryEnv = env; - jumar = new JAXBumar(classes); - jmar = new JAXBmar(classes) ; - } catch (JAXBException e) { - throw new APIException(e); - } - } - - public JAXBDF(EnvJAXB env, Schema schema, Class ... classes) throws APIException { - try { - primaryEnv = env; - jumar = new JAXBumar(schema, classes); - jmar = new JAXBmar(classes); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - public JAXBDF(EnvJAXB env, QName qname, Class ... classes) throws APIException { - try { - primaryEnv = env; - jumar = new JAXBumar(classes); - jmar = new JAXBmar(qname, classes); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - public JAXBDF(EnvJAXB env, Schema schema, QName qname, Class ... classes) throws APIException { - try { - primaryEnv = env; - jumar = new JAXBumar(schema, classes); - jmar = new JAXBmar(qname, classes); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - // @Override - public T newInstance() throws APIException { - try { - return jumar.newInstance(); - } catch (Exception e) { - throw new APIException(e); - } - } - - // @Override - public IOStringifier pretty(boolean pretty) { - jmar.pretty(pretty); - return this; - } - - // @Override - public IOStringifier asFragment(boolean fragment) { - jmar.asFragment(fragment); - return this; - } - - // @Override - public void servicePrestart(Env env) throws APIException { - } - - // @Override - public void threadPrestart(Env env) throws APIException { - } - - // @Override - public void refresh(Env env) throws APIException { - } - - // @Override - public void threadDestroy(Env env) throws APIException { - } - - // @Override - public void serviceDestroy(Env env) throws APIException { - } - - @SuppressWarnings("unchecked") - // @Override - public Data newData() { - return new JAXBData(primaryEnv, this, new JAXBStringifier(jmar), new JAXBObjectifier(jumar),"",(Class)jmar.getMarshalClass()); - } - - @SuppressWarnings("unchecked") - // @Override - public Data newData(Env env) { - return new JAXBData(env, this,new JAXBStringifier(jmar), new JAXBObjectifier(jumar),"",(Class)jmar.getMarshalClass()); - } - - // @Override - public Data newData(T type) { - return new JAXBData(primaryEnv, this, new JAXBStringifier(jmar), new JAXBObjectifier(jumar), type); - } - - // @Override - public Data newDataFromStream(Env env, InputStream input) throws APIException { - //TODO Write an unvalidated String using STAX checking for end of Doc? - // perhaps key evaluation as well. - try { - T t = jumar.unmarshal(env.debug(), input); - return new JAXBData(primaryEnv, this, new JAXBStringifier(jmar), new JAXBObjectifier(jumar),t); - } catch(JAXBException e) { - throw new APIException(e); - } - } - - @SuppressWarnings("unchecked") - // @Override - public Data newDataFromString(String string) { - return new JAXBData(primaryEnv, this,new JAXBStringifier(jmar), new JAXBObjectifier(jumar), string,(Class)jmar.getMarshalClass()); - } - - /////////// Old DataFactory Interface - // @Override - public String stringify(T type) throws APIException { - try { - StringWriter sw = new StringWriter(); - jmar.marshal(primaryEnv.debug(), type, sw); - return sw.toString(); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - // @Override - public void stringify(T type, Writer writer) throws APIException { - try { - jmar.marshal(primaryEnv.debug(), type, writer); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - // @Override - public void stringify(T type, OutputStream os) throws APIException { - try { - jmar.marshal(primaryEnv.debug(), type, os); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - /////////// New DataFactory Interface - // @Override - public String stringify(Env env, T input, boolean ... options) throws APIException { - try { - StringWriter sw = new StringWriter(); - TimeTaken tt = env.start("JAXB Stringify", Env.XML); - try { - jmar.marshal(env.debug(), input, sw, options); - } finally { - tt.done(); - } - String str = sw.toString(); - tt.size(str.getBytes().length); - return str; - } catch (JAXBException e) { - throw new APIException(e); - } - } - - // @Override - public void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException { - TimeTaken tt = env.start("JAXB Stringify", Env.XML); - try { - jmar.marshal(env.debug(), input, writer, options); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - // @Override - public void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException { - TimeTaken tt = env.start("JAXB Stringify", Env.XML); - try { - jmar.marshal(env.debug(), input, os, options); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - // @Override - public T objectify(Env env, Reader rdr) throws APIException { - TimeTaken tt = env.start("JAXB Objectify", Env.XML); - try { - return jumar.unmarshal(env.debug(), rdr); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - // @Override - public T objectify(Reader rdr) throws APIException { - try { - return jumar.unmarshal(primaryEnv.debug(), rdr); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - // @Override - public T objectify(Env env, InputStream is) throws APIException { - TimeTaken tt = env.start("JAXB Objectify", Env.XML); - try { - return jumar.unmarshal(env.debug(), is); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - // @Override - public T objectify(InputStream is) throws APIException { - try { - return jumar.unmarshal(primaryEnv.debug(), is); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - // @Override - public T objectify(Env env, String input) throws APIException { - TimeTaken tt = env.start("JAXB Objectify", Env.XML); - tt.size(input.getBytes().length); - try { - return jumar.unmarshal(env.debug(), input); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - // @Override - public T objectify(String text) throws APIException { - try { - return jumar.unmarshal(primaryEnv.debug(), text); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - @SuppressWarnings("unchecked") - // @Override - public Class getTypeClass() { - return (Class)jmar.getMarshalClass(); - } + // Package on purpose + EnvJAXB primaryEnv; + JAXBumar jumar; + JAXBmar jmar; + + public JAXBDF(EnvJAXB env, Class ... classes) throws APIException { + try { + primaryEnv = env; + jumar = new JAXBumar(classes); + jmar = new JAXBmar(classes) ; + } catch (JAXBException e) { + throw new APIException(e); + } + } + + public JAXBDF(EnvJAXB env, Schema schema, Class ... classes) throws APIException { + try { + primaryEnv = env; + jumar = new JAXBumar(schema, classes); + jmar = new JAXBmar(classes); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + public JAXBDF(EnvJAXB env, QName qname, Class ... classes) throws APIException { + try { + primaryEnv = env; + jumar = new JAXBumar(classes); + jmar = new JAXBmar(qname, classes); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + public JAXBDF(EnvJAXB env, Schema schema, QName qname, Class ... classes) throws APIException { + try { + primaryEnv = env; + jumar = new JAXBumar(schema, classes); + jmar = new JAXBmar(qname, classes); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + // @Override + public T newInstance() throws APIException { + try { + return jumar.newInstance(); + } catch (Exception e) { + throw new APIException(e); + } + } + + // @Override + public IOStringifier pretty(boolean pretty) { + jmar.pretty(pretty); + return this; + } + + // @Override + public IOStringifier asFragment(boolean fragment) { + jmar.asFragment(fragment); + return this; + } + + // @Override + public void servicePrestart(Env env) throws APIException { + } + + // @Override + public void threadPrestart(Env env) throws APIException { + } + + // @Override + public void refresh(Env env) throws APIException { + } + + // @Override + public void threadDestroy(Env env) throws APIException { + } + + // @Override + public void serviceDestroy(Env env) throws APIException { + } + + @SuppressWarnings("unchecked") + // @Override + public Data newData() { + return new JAXBData(primaryEnv, this, new JAXBStringifier(jmar), new JAXBObjectifier(jumar),"",(Class)jmar.getMarshalClass()); + } + + @SuppressWarnings("unchecked") + // @Override + public Data newData(Env env) { + return new JAXBData(env, this,new JAXBStringifier(jmar), new JAXBObjectifier(jumar),"",(Class)jmar.getMarshalClass()); + } + + // @Override + public Data newData(T type) { + return new JAXBData(primaryEnv, this, new JAXBStringifier(jmar), new JAXBObjectifier(jumar), type); + } + + // @Override + public Data newDataFromStream(Env env, InputStream input) throws APIException { + //TODO Write an unvalidated String using STAX checking for end of Doc? + // perhaps key evaluation as well. + try { + T t = jumar.unmarshal(env.debug(), input); + return new JAXBData(primaryEnv, this, new JAXBStringifier(jmar), new JAXBObjectifier(jumar),t); + } catch(JAXBException e) { + throw new APIException(e); + } + } + + @SuppressWarnings("unchecked") + // @Override + public Data newDataFromString(String string) { + return new JAXBData(primaryEnv, this,new JAXBStringifier(jmar), new JAXBObjectifier(jumar), string,(Class)jmar.getMarshalClass()); + } + + /////////// Old DataFactory Interface + // @Override + public String stringify(T type) throws APIException { + try { + StringWriter sw = new StringWriter(); + jmar.marshal(primaryEnv.debug(), type, sw); + return sw.toString(); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + // @Override + public void stringify(T type, Writer writer) throws APIException { + try { + jmar.marshal(primaryEnv.debug(), type, writer); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + // @Override + public void stringify(T type, OutputStream os) throws APIException { + try { + jmar.marshal(primaryEnv.debug(), type, os); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + /////////// New DataFactory Interface + // @Override + public String stringify(Env env, T input, boolean ... options) throws APIException { + try { + StringWriter sw = new StringWriter(); + TimeTaken tt = env.start("JAXB Stringify", Env.XML); + try { + jmar.marshal(env.debug(), input, sw, options); + } finally { + tt.done(); + } + String str = sw.toString(); + tt.size(str.getBytes().length); + return str; + } catch (JAXBException e) { + throw new APIException(e); + } + } + + // @Override + public void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException { + TimeTaken tt = env.start("JAXB Stringify", Env.XML); + try { + jmar.marshal(env.debug(), input, writer, options); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + // @Override + public void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException { + TimeTaken tt = env.start("JAXB Stringify", Env.XML); + try { + jmar.marshal(env.debug(), input, os, options); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + // @Override + public T objectify(Env env, Reader rdr) throws APIException { + TimeTaken tt = env.start("JAXB Objectify", Env.XML); + try { + return jumar.unmarshal(env.debug(), rdr); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + // @Override + public T objectify(Reader rdr) throws APIException { + try { + return jumar.unmarshal(primaryEnv.debug(), rdr); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + // @Override + public T objectify(Env env, InputStream is) throws APIException { + TimeTaken tt = env.start("JAXB Objectify", Env.XML); + try { + return jumar.unmarshal(env.debug(), is); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + // @Override + public T objectify(InputStream is) throws APIException { + try { + return jumar.unmarshal(primaryEnv.debug(), is); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + // @Override + public T objectify(Env env, String input) throws APIException { + TimeTaken tt = env.start("JAXB Objectify", Env.XML); + tt.size(input.getBytes().length); + try { + return jumar.unmarshal(env.debug(), input); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + // @Override + public T objectify(String text) throws APIException { + try { + return jumar.unmarshal(primaryEnv.debug(), text); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + @SuppressWarnings("unchecked") + // @Override + public Class getTypeClass() { + return (Class)jmar.getMarshalClass(); + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java index 84502ade..38977a35 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java @@ -55,267 +55,267 @@ import org.onap.aaf.misc.env.old.Stringifier; * @param */ public final class JAXBData implements Data{ - private Stringifier stringifier; - private Objectifier objectifier; - private String dataAsString; - private T dataAsObject; - private Class tclass; - private JAXBDF df; - private Env creatingEnv; - private boolean options[] = new boolean[] {false, false}; - - /** - * Construct a Data Object with an appropriate Stringifier, Objectifier and Class to support - * - * @param env - * @param strfr - * @param objfr - * @param text - * @param typeClass - */ - JAXBData(Env env, JAXBDF df, Stringifier strfr, Objectifier objfr, String text, Class typeClass) { - dataAsString = text; - dataAsObject = null; - stringifier = strfr; - objectifier = objfr; - tclass = typeClass; - creatingEnv = env; - this.df = df; - } - - - /** - * Construct a Data Object with an appropriate Stringifier, Objectifier and Object (which will - * yield it's class) - * - * @param env - * @param strfr - * @param objfr - * @param object - */ - @SuppressWarnings("unchecked") - JAXBData(Env env, JAXBDF df, Stringifier strfr, Objectifier objfr, T object) { - dataAsString = null; - dataAsObject = object; - stringifier = strfr; - objectifier = objfr; - tclass = (Class) object.getClass(); - creatingEnv = env; - this.df = df; - } + private Stringifier stringifier; + private Objectifier objectifier; + private String dataAsString; + private T dataAsObject; + private Class tclass; + private JAXBDF df; + private Env creatingEnv; + private boolean options[] = new boolean[] {false, false}; + + /** + * Construct a Data Object with an appropriate Stringifier, Objectifier and Class to support + * + * @param env + * @param strfr + * @param objfr + * @param text + * @param typeClass + */ + JAXBData(Env env, JAXBDF df, Stringifier strfr, Objectifier objfr, String text, Class typeClass) { + dataAsString = text; + dataAsObject = null; + stringifier = strfr; + objectifier = objfr; + tclass = typeClass; + creatingEnv = env; + this.df = df; + } + + + /** + * Construct a Data Object with an appropriate Stringifier, Objectifier and Object (which will + * yield it's class) + * + * @param env + * @param strfr + * @param objfr + * @param object + */ + @SuppressWarnings("unchecked") + JAXBData(Env env, JAXBDF df, Stringifier strfr, Objectifier objfr, T object) { + dataAsString = null; + dataAsObject = object; + stringifier = strfr; + objectifier = objfr; + tclass = (Class) object.getClass(); + creatingEnv = env; + this.df = df; + } - /** - * Respond with the String if it exists, or marshal the String and pass the result back.

    - * - * Explicitly use a specific Env for logging purposes - * - * @param env - * @return String - * @throws APIException - */ - public String asString(EnvJAXB env) throws APIException { - if(dataAsString!=null) { - return dataAsString; - } else { - return dataAsString = stringifier.stringify(env, dataAsObject); - } - } + /** + * Respond with the String if it exists, or marshal the String and pass the result back.

    + * + * Explicitly use a specific Env for logging purposes + * + * @param env + * @return String + * @throws APIException + */ + public String asString(EnvJAXB env) throws APIException { + if(dataAsString!=null) { + return dataAsString; + } else { + return dataAsString = stringifier.stringify(env, dataAsObject); + } + } - /** - * Respond with the String if it exists, or marshal the String and pass the result back. - * - * However, use the Env the Data Object was created with. - * - * @return String - * @throws APIException - */ - // @Override - public String asString() throws APIException { - if(dataAsString!=null) { - return dataAsString; - } else { - return dataAsString = stringifier.stringify(creatingEnv, dataAsObject,options); - } - } - - public Data to(OutputStream os) throws APIException, IOException { - if(dataAsString!=null) { - os.write(dataAsString.getBytes()); - } else if (stringifier instanceof IOStringifier){ - ((IOStringifier)stringifier).stringify(creatingEnv, dataAsObject, os, options); - } else { - dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options); - os.write(dataAsString.getBytes()); - } - return this; - } + /** + * Respond with the String if it exists, or marshal the String and pass the result back. + * + * However, use the Env the Data Object was created with. + * + * @return String + * @throws APIException + */ + // @Override + public String asString() throws APIException { + if(dataAsString!=null) { + return dataAsString; + } else { + return dataAsString = stringifier.stringify(creatingEnv, dataAsObject,options); + } + } + + public Data to(OutputStream os) throws APIException, IOException { + if(dataAsString!=null) { + os.write(dataAsString.getBytes()); + } else if (stringifier instanceof IOStringifier){ + ((IOStringifier)stringifier).stringify(creatingEnv, dataAsObject, os, options); + } else { + dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options); + os.write(dataAsString.getBytes()); + } + return this; + } - // @Override - public JAXBData to(Writer writer) throws APIException, IOException { - if(dataAsString!=null) { - writer.write(dataAsString); - } else if (stringifier instanceof IOStringifier){ - ((IOStringifier)stringifier).stringify(creatingEnv, dataAsObject, writer, options); - } else { - dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options); - writer.write(dataAsString); - } - return this; - } + // @Override + public JAXBData to(Writer writer) throws APIException, IOException { + if(dataAsString!=null) { + writer.write(dataAsString); + } else if (stringifier instanceof IOStringifier){ + ((IOStringifier)stringifier).stringify(creatingEnv, dataAsObject, writer, options); + } else { + dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options); + writer.write(dataAsString); + } + return this; + } - public InputStream getInputStream() throws APIException { - if(dataAsString==null) { - dataAsString = stringifier.stringify(creatingEnv,dataAsObject,options); - } - return new ByteArrayInputStream(dataAsString.getBytes()); - } - - /** - * Respond with the Object of type {@literal } if it exists, or unmarshal from String - * and pass the result back.

    - * - * Explicitly use a specific Env for logging purposes - * - * @param env - * @return T - * @throws APIException - */ + public InputStream getInputStream() throws APIException { + if(dataAsString==null) { + dataAsString = stringifier.stringify(creatingEnv,dataAsObject,options); + } + return new ByteArrayInputStream(dataAsString.getBytes()); + } + + /** + * Respond with the Object of type {@literal } if it exists, or unmarshal from String + * and pass the result back.

    + * + * Explicitly use a specific Env for logging purposes + * + * @param env + * @return T + * @throws APIException + */ - public T asObject(EnvJAXB env) throws APIException { - if(dataAsObject !=null) { - return dataAsObject; - } else { - // Some Java compilers need two statements here - dataAsObject = objectifier.objectify(env, dataAsString); - return dataAsObject; - } - } + public T asObject(EnvJAXB env) throws APIException { + if(dataAsObject !=null) { + return dataAsObject; + } else { + // Some Java compilers need two statements here + dataAsObject = objectifier.objectify(env, dataAsString); + return dataAsObject; + } + } - /** - * Respond with the Object of type {@literal } if it exists, or unmarshal from String - * and pass the result back.

    - * - * However, use the Env the Data Object was created with. - * - * @return T - * @throws APIException - */ - // @Override - public T asObject() throws APIException { - if(dataAsObject !=null) { - return dataAsObject; - } else { - // Some Java compilers need two statements here - dataAsObject = objectifier.objectify(creatingEnv, dataAsString); - return dataAsObject; - } - } - + /** + * Respond with the Object of type {@literal } if it exists, or unmarshal from String + * and pass the result back.

    + * + * However, use the Env the Data Object was created with. + * + * @return T + * @throws APIException + */ + // @Override + public T asObject() throws APIException { + if(dataAsObject !=null) { + return dataAsObject; + } else { + // Some Java compilers need two statements here + dataAsObject = objectifier.objectify(creatingEnv, dataAsString); + return dataAsObject; + } + } + - /** - * Return the Class Type supported by this DataObject - * - * @return {@literal Class} - */ - // @Override - public Class getTypeClass() { - return tclass; - } - - - /** - * For Debugging Convenience, we marshal to String if possible. - * - * Behavior is essentially the same as asString(), except asString() throws - * an APIException.

    - * Since toString() must not throw exceptions, the function just catches and prints an - * error, which is probably not the behavior desired.

    - * - * Therefore, use "asString()" where possible in actual Transactional code. - * - * @see java.lang.Object#toString() - */ - // @Override - public String toString() { - if(dataAsString!=null) { - return dataAsString; - } else { - try { - return dataAsString = stringifier.stringify(creatingEnv, dataAsObject); - } catch (APIException e) { - return "ERROR - Can't Stringify from Object " + e.getLocalizedMessage(); - } - } - } + /** + * Return the Class Type supported by this DataObject + * + * @return {@literal Class} + */ + // @Override + public Class getTypeClass() { + return tclass; + } + + + /** + * For Debugging Convenience, we marshal to String if possible. + * + * Behavior is essentially the same as asString(), except asString() throws + * an APIException.

    + * Since toString() must not throw exceptions, the function just catches and prints an + * error, which is probably not the behavior desired.

    + * + * Therefore, use "asString()" where possible in actual Transactional code. + * + * @see java.lang.Object#toString() + */ + // @Override + public String toString() { + if(dataAsString!=null) { + return dataAsString; + } else { + try { + return dataAsString = stringifier.stringify(creatingEnv, dataAsObject); + } catch (APIException e) { + return "ERROR - Can't Stringify from Object " + e.getLocalizedMessage(); + } + } + } - public Data load(T t) throws APIException { - dataAsObject = t; - dataAsString = null; - return this; - } + public Data load(T t) throws APIException { + dataAsObject = t; + dataAsString = null; + return this; + } - public Data load(String str) throws APIException { - dataAsObject = null; - dataAsString = str; - return this; - } + public Data load(String str) throws APIException { + dataAsObject = null; + dataAsString = str; + return this; + } - public Data load(InputStream is) throws APIException { - try { - dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),is); - dataAsString = null; - } catch (JAXBException e) { - throw new APIException(e); - } - return this; - } + public Data load(InputStream is) throws APIException { + try { + dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),is); + dataAsString = null; + } catch (JAXBException e) { + throw new APIException(e); + } + return this; + } - public Data load(Reader rdr) throws APIException { - try { - dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),rdr); - dataAsString = null; - } catch (JAXBException e) { - throw new APIException(e); - } - return this; - } + public Data load(Reader rdr) throws APIException { + try { + dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),rdr); + dataAsString = null; + } catch (JAXBException e) { + throw new APIException(e); + } + return this; + } - // @Override - public void direct(InputStream input, OutputStream output) throws APIException, IOException { - byte b[] = new byte[128]; - int count; - do { - count = input.read(b); - if(count>0)output.write(b, 0, count); - } while(count>=0); - } + // @Override + public void direct(InputStream input, OutputStream output) throws APIException, IOException { + byte b[] = new byte[128]; + int count; + do { + count = input.read(b); + if(count>0)output.write(b, 0, count); + } while(count>=0); + } - // @Override - public Data out(TYPE type) { - // it's going to be XML regardless... - return this; - } + // @Override + public Data out(TYPE type) { + // it's going to be XML regardless... + return this; + } - // @Override - public Data in(TYPE type) { - // Not Supported... will still be XML - return this; - } + // @Override + public Data in(TYPE type) { + // Not Supported... will still be XML + return this; + } - // @Override - public Data option(int option) { - options[0] = (option&Data.PRETTY)==Data.PRETTY; - options[1] = (option&Data.FRAGMENT)==Data.FRAGMENT; - return this; - } - + // @Override + public Data option(int option) { + options[0] = (option&Data.PRETTY)==Data.PRETTY; + options[1] = (option&Data.FRAGMENT)==Data.FRAGMENT; + return this; + } + } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBObjectifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBObjectifier.java index 432a449a..7075c7ef 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBObjectifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBObjectifier.java @@ -36,100 +36,100 @@ import org.onap.aaf.misc.env.old.IOObjectifier; * Allow Extended IO interface usage without muddying up the Stringifier Interface */ public class JAXBObjectifier implements IOObjectifier { - private JAXBumar jumar; - - public JAXBObjectifier(Schema schema, Class... classes) throws APIException { - try { - jumar = new JAXBumar(schema, classes); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - public JAXBObjectifier(Class... classes) throws APIException { - try { - jumar = new JAXBumar(classes); - } catch (JAXBException e) { - throw new APIException(e); - } - } - + private JAXBumar jumar; + + public JAXBObjectifier(Schema schema, Class... classes) throws APIException { + try { + jumar = new JAXBumar(schema, classes); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + public JAXBObjectifier(Class... classes) throws APIException { + try { + jumar = new JAXBumar(classes); + } catch (JAXBException e) { + throw new APIException(e); + } + } + // package on purpose - JAXBObjectifier(JAXBumar jumar) { - this.jumar = jumar; - } - - @SuppressWarnings("unchecked") - // @Override - public T objectify(Env env, String input) throws APIException { - TimeTaken tt = env.start("JAXB Unmarshal", Env.XML); - try { - tt.size(input.length()); - return (T)jumar.unmarshal(env.debug(), input); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - @SuppressWarnings("unchecked") - // @Override - public T objectify(Env env, Reader rdr) throws APIException { - //TODO create a Reader that Counts? - TimeTaken tt = env.start("JAXB Unmarshal", Env.XML); - try { - return (T)jumar.unmarshal(env.debug(), rdr); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - - @SuppressWarnings("unchecked") - // @Override - public T objectify(Env env, InputStream is) throws APIException { - //TODO create a Reader that Counts? - TimeTaken tt = env.start("JAXB Unmarshal", Env.XML); - try { - return (T)jumar.unmarshal(env.debug(), is); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - - public void servicePrestart(Env env) throws APIException { - } - - public void threadPrestart(Env env) throws APIException { - } - - // // @Override - public void refresh(Env env) throws APIException { - } - - // // @Override - public void threadDestroy(Env env) throws APIException { - } - - // // @Override - public void serviceDestroy(Env env) throws APIException { - } - - - @SuppressWarnings("unchecked") - public T newInstance() throws APIException { - try { - return (T)jumar.newInstance(); - } catch (Exception e) { - throw new APIException(e); - } - } + JAXBObjectifier(JAXBumar jumar) { + this.jumar = jumar; + } + + @SuppressWarnings("unchecked") + // @Override + public T objectify(Env env, String input) throws APIException { + TimeTaken tt = env.start("JAXB Unmarshal", Env.XML); + try { + tt.size(input.length()); + return (T)jumar.unmarshal(env.debug(), input); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + @SuppressWarnings("unchecked") + // @Override + public T objectify(Env env, Reader rdr) throws APIException { + //TODO create a Reader that Counts? + TimeTaken tt = env.start("JAXB Unmarshal", Env.XML); + try { + return (T)jumar.unmarshal(env.debug(), rdr); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + + @SuppressWarnings("unchecked") + // @Override + public T objectify(Env env, InputStream is) throws APIException { + //TODO create a Reader that Counts? + TimeTaken tt = env.start("JAXB Unmarshal", Env.XML); + try { + return (T)jumar.unmarshal(env.debug(), is); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + + public void servicePrestart(Env env) throws APIException { + } + + public void threadPrestart(Env env) throws APIException { + } + + // // @Override + public void refresh(Env env) throws APIException { + } + + // // @Override + public void threadDestroy(Env env) throws APIException { + } + + // // @Override + public void serviceDestroy(Env env) throws APIException { + } + + + @SuppressWarnings("unchecked") + public T newInstance() throws APIException { + try { + return (T)jumar.newInstance(); + } catch (Exception e) { + throw new APIException(e); + } + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBStringifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBStringifier.java index d1b0cdad..8600efa2 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBStringifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBStringifier.java @@ -34,104 +34,104 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.old.IOStringifier; public class JAXBStringifier implements IOStringifier { - private JAXBmar jmar; - - public JAXBStringifier(Class... classes) throws APIException { - try { - jmar = new JAXBmar(classes); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - public JAXBStringifier(QName qname, Class... classes) - throws APIException { - try { - jmar = new JAXBmar(qname, classes); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - // package on purpose - JAXBStringifier(JAXBmar jmar) { - this.jmar = jmar; - } - - // // @Override - public void stringify(Env env, T input, Writer writer, boolean ... options) - throws APIException { - TimeTaken tt = env.start("JAXB Marshal", Env.XML); - try { - jmar.marshal(env.debug(), input, writer, options); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - // @Override - public void stringify(Env env, T input, OutputStream os, boolean ... options) - throws APIException { - // TODO create an OutputStream that Counts? - TimeTaken tt = env.start("JAXB Marshal", Env.XML); - try { - jmar.marshal(env.debug(), input, os, options); - } catch (JAXBException e) { - throw new APIException(e); - } finally { - tt.done(); - } - } - - // @Override - public String stringify(Env env, T input, boolean ... options) throws APIException { - TimeTaken tt = env.start("JAXB Marshal", Env.XML); - StringWriter sw = new StringWriter(); - try { - jmar.marshal(env.debug(), input, sw, options); - String rv = sw.toString(); - tt.size(rv.length()); - return rv; - } catch (JAXBException e) { - tt.size(0); - throw new APIException(e); - } finally { - tt.done(); - } - } - - // // @Override - public void servicePrestart(Env env) throws APIException { - } - - // // @Override - public void threadPrestart(Env env) throws APIException { - } - - // // @Override - public void refresh(Env env) throws APIException { - } - - // // @Override - public void threadDestroy(Env env) throws APIException { - } - - // // @Override - public void serviceDestroy(Env env) throws APIException { - } - - // @Override - public JAXBStringifier pretty(boolean pretty) { - jmar.pretty(pretty); - return this; - } - - // @Override - public JAXBStringifier asFragment(boolean fragment) { - jmar.asFragment(fragment); - return this; - } + private JAXBmar jmar; + + public JAXBStringifier(Class... classes) throws APIException { + try { + jmar = new JAXBmar(classes); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + public JAXBStringifier(QName qname, Class... classes) + throws APIException { + try { + jmar = new JAXBmar(qname, classes); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + // package on purpose + JAXBStringifier(JAXBmar jmar) { + this.jmar = jmar; + } + + // // @Override + public void stringify(Env env, T input, Writer writer, boolean ... options) + throws APIException { + TimeTaken tt = env.start("JAXB Marshal", Env.XML); + try { + jmar.marshal(env.debug(), input, writer, options); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + // @Override + public void stringify(Env env, T input, OutputStream os, boolean ... options) + throws APIException { + // TODO create an OutputStream that Counts? + TimeTaken tt = env.start("JAXB Marshal", Env.XML); + try { + jmar.marshal(env.debug(), input, os, options); + } catch (JAXBException e) { + throw new APIException(e); + } finally { + tt.done(); + } + } + + // @Override + public String stringify(Env env, T input, boolean ... options) throws APIException { + TimeTaken tt = env.start("JAXB Marshal", Env.XML); + StringWriter sw = new StringWriter(); + try { + jmar.marshal(env.debug(), input, sw, options); + String rv = sw.toString(); + tt.size(rv.length()); + return rv; + } catch (JAXBException e) { + tt.size(0); + throw new APIException(e); + } finally { + tt.done(); + } + } + + // // @Override + public void servicePrestart(Env env) throws APIException { + } + + // // @Override + public void threadPrestart(Env env) throws APIException { + } + + // // @Override + public void refresh(Env env) throws APIException { + } + + // // @Override + public void threadDestroy(Env env) throws APIException { + } + + // // @Override + public void serviceDestroy(Env env) throws APIException { + } + + // @Override + public JAXBStringifier pretty(boolean pretty) { + jmar.pretty(pretty); + return this; + } + + // @Override + public JAXBStringifier asFragment(boolean fragment) { + jmar.asFragment(fragment); + return this; + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java index 4a01d8b1..46c40ebb 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java @@ -63,191 +63,191 @@ import org.onap.aaf.misc.env.util.Pool.Pooled; * */ public class JAXBmar { - // Need to store off possible JAXBContexts based on Class, which will be stored in Creator - private static Map[],Pool> pools = new HashMap<>(); - - // Handle Marshaller class setting of properties only when needed - private class PMarshaller { - private Marshaller m; - private boolean p; - private boolean f; - - public PMarshaller(Marshaller marshaller) throws JAXBException { - m = marshaller; - m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = false); - m.setProperty(Marshaller.JAXB_FRAGMENT, f = false); - } - - public Marshaller get(boolean pretty, boolean fragment) throws JAXBException { - if(pretty != p) { - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = pretty); - } - if(fragment != f) { - m.setProperty(Marshaller.JAXB_FRAGMENT, f = fragment); - } - return m; - } - } - - private class Creator implements Pool.Creator { - private JAXBContext jc; - private String name; - public Creator(Class[] classes) throws JAXBException { - jc = JAXBContext.newInstance(classes); - name = "JAXBmar: " + classes[0].getName(); - } - - // @Override - public PMarshaller create() throws APIException { - try { - return new PMarshaller(jc.createMarshaller()); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - public String toString() { - return name; - } - - // @Override - public void reuse(PMarshaller pm) { - // Nothing to do - } - - // @Override - public void destroy(PMarshaller pm) { - // Nothing to do - } - - // @Override - public boolean isValid(PMarshaller t) { - return true; - } - } - - //TODO isn't UTF-8 a standard string somewhere for encoding? - private boolean fragment= false; - private boolean pretty=false; - private QName qname; - - private Pool mpool; // specific Pool associated with constructed Classes - private Class cls; - - private Pool getPool(Class ... classes) throws JAXBException { - Pool mp; - synchronized(pools) { - mp = pools.get(classes); - if(mp==null) { - pools.put(classes,mp = new Pool(new Creator(classes))); - } - } - return mp; - } - - public JAXBmar(Class... classes) throws JAXBException { - cls = classes[0]; - mpool = getPool(classes); - qname = null; - } - - public JAXBmar(QName theQname, Class... classes) throws JAXBException { - cls = classes[0]; - mpool = getPool(classes); - qname = theQname; - } - - @SuppressWarnings("unchecked") - public O marshal(LogTarget lt,O o, Writer writer, boolean ... options) throws JAXBException, APIException { - boolean pretty, fragment; - pretty = options.length>0?options[0]:this.pretty; - fragment = options.length>1?options[1]:this.fragment; - Pooled m = mpool.get(lt); - try { - if(qname==null) { - m.content.get(pretty,fragment).marshal(o, writer); - } else { - m.content.get(pretty,fragment).marshal( - new JAXBElement(qname, (Class)cls, o ), - writer); - } - return o; - } finally { - m.done(); - } - } - - @SuppressWarnings("unchecked") - public O marshal(LogTarget lt, O o, OutputStream os, boolean ... options) throws JAXBException, APIException { - boolean pretty, fragment; - pretty = options.length>0?options[0]:this.pretty; - fragment = options.length>1?options[1]:this.fragment; - Pooled m = mpool.get(lt); - try { - if(qname==null) { - m.content.get(pretty,fragment).marshal(o, os); - } else { - m.content.get(pretty,fragment).marshal( - new JAXBElement(qname, (Class)cls, o ),os); - } - return o; - } finally { - m.done(); - } - } - - public O marshal(LogTarget lt, O o, Writer writer, Class clss) throws JAXBException, APIException { - Pooled m = mpool.get(lt); - try { - if(qname==null) { - m.content.get(pretty,fragment).marshal(o, writer); - } else { - m.content.get(pretty,fragment).marshal( - new JAXBElement(qname, clss, o),writer); - } - return o; - } finally { - m.done(); - } - - } - - public O marshal(LogTarget lt, O o, OutputStream os, Class clss) throws JAXBException, APIException { - Pooled m = mpool.get(lt); - try { - if(qname==null) { - m.content.get(pretty,fragment).marshal(o, os); - } else { - m.content.get(pretty,fragment).marshal( - new JAXBElement(qname, clss, o ),os); - } - return o; - } finally { - m.done(); - } - } - - /** - * @return - */ - public Class getMarshalClass() { - return cls; - } - - public String stringify(LogTarget lt, O o) throws JAXBException, APIException { - StringWriter sw = new StringWriter(); - marshal(lt,o,sw); - return sw.toString(); - } - - public JAXBmar pretty(boolean pretty) { - this.pretty = pretty; - return this; - } - - public JAXBmar asFragment(boolean fragment) { - this.fragment = fragment; - return this; - } + // Need to store off possible JAXBContexts based on Class, which will be stored in Creator + private static Map[],Pool> pools = new HashMap<>(); + + // Handle Marshaller class setting of properties only when needed + private class PMarshaller { + private Marshaller m; + private boolean p; + private boolean f; + + public PMarshaller(Marshaller marshaller) throws JAXBException { + m = marshaller; + m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = false); + m.setProperty(Marshaller.JAXB_FRAGMENT, f = false); + } + + public Marshaller get(boolean pretty, boolean fragment) throws JAXBException { + if(pretty != p) { + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = pretty); + } + if(fragment != f) { + m.setProperty(Marshaller.JAXB_FRAGMENT, f = fragment); + } + return m; + } + } + + private class Creator implements Pool.Creator { + private JAXBContext jc; + private String name; + public Creator(Class[] classes) throws JAXBException { + jc = JAXBContext.newInstance(classes); + name = "JAXBmar: " + classes[0].getName(); + } + + // @Override + public PMarshaller create() throws APIException { + try { + return new PMarshaller(jc.createMarshaller()); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + public String toString() { + return name; + } + + // @Override + public void reuse(PMarshaller pm) { + // Nothing to do + } + + // @Override + public void destroy(PMarshaller pm) { + // Nothing to do + } + + // @Override + public boolean isValid(PMarshaller t) { + return true; + } + } + + //TODO isn't UTF-8 a standard string somewhere for encoding? + private boolean fragment= false; + private boolean pretty=false; + private QName qname; + + private Pool mpool; // specific Pool associated with constructed Classes + private Class cls; + + private Pool getPool(Class ... classes) throws JAXBException { + Pool mp; + synchronized(pools) { + mp = pools.get(classes); + if(mp==null) { + pools.put(classes,mp = new Pool(new Creator(classes))); + } + } + return mp; + } + + public JAXBmar(Class... classes) throws JAXBException { + cls = classes[0]; + mpool = getPool(classes); + qname = null; + } + + public JAXBmar(QName theQname, Class... classes) throws JAXBException { + cls = classes[0]; + mpool = getPool(classes); + qname = theQname; + } + + @SuppressWarnings("unchecked") + public O marshal(LogTarget lt,O o, Writer writer, boolean ... options) throws JAXBException, APIException { + boolean pretty, fragment; + pretty = options.length>0?options[0]:this.pretty; + fragment = options.length>1?options[1]:this.fragment; + Pooled m = mpool.get(lt); + try { + if(qname==null) { + m.content.get(pretty,fragment).marshal(o, writer); + } else { + m.content.get(pretty,fragment).marshal( + new JAXBElement(qname, (Class)cls, o ), + writer); + } + return o; + } finally { + m.done(); + } + } + + @SuppressWarnings("unchecked") + public O marshal(LogTarget lt, O o, OutputStream os, boolean ... options) throws JAXBException, APIException { + boolean pretty, fragment; + pretty = options.length>0?options[0]:this.pretty; + fragment = options.length>1?options[1]:this.fragment; + Pooled m = mpool.get(lt); + try { + if(qname==null) { + m.content.get(pretty,fragment).marshal(o, os); + } else { + m.content.get(pretty,fragment).marshal( + new JAXBElement(qname, (Class)cls, o ),os); + } + return o; + } finally { + m.done(); + } + } + + public O marshal(LogTarget lt, O o, Writer writer, Class clss) throws JAXBException, APIException { + Pooled m = mpool.get(lt); + try { + if(qname==null) { + m.content.get(pretty,fragment).marshal(o, writer); + } else { + m.content.get(pretty,fragment).marshal( + new JAXBElement(qname, clss, o),writer); + } + return o; + } finally { + m.done(); + } + + } + + public O marshal(LogTarget lt, O o, OutputStream os, Class clss) throws JAXBException, APIException { + Pooled m = mpool.get(lt); + try { + if(qname==null) { + m.content.get(pretty,fragment).marshal(o, os); + } else { + m.content.get(pretty,fragment).marshal( + new JAXBElement(qname, clss, o ),os); + } + return o; + } finally { + m.done(); + } + } + + /** + * @return + */ + public Class getMarshalClass() { + return cls; + } + + public String stringify(LogTarget lt, O o) throws JAXBException, APIException { + StringWriter sw = new StringWriter(); + marshal(lt,o,sw); + return sw.toString(); + } + + public JAXBmar pretty(boolean pretty) { + this.pretty = pretty; + return this; + } + + public JAXBmar asFragment(boolean fragment) { + this.fragment = fragment; + return this; + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java index 0c078a98..fe3f0145 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java @@ -67,177 +67,177 @@ import org.w3c.dom.Node; * */ public class JAXBumar { - // Need to store off possible JAXBContexts based on Class, which will be stored in Creator - private static Map[],Pool> pools = new HashMap<>(); - - private Class cls; - private Schema schema; - private Pool mpool;; - - // Handle Marshaller class setting of properties only when needed - private class SUnmarshaller { - private Unmarshaller u; - private Schema s; - - public SUnmarshaller(Unmarshaller unmarshaller) throws JAXBException { - u = unmarshaller; - s = null; - } - - public Unmarshaller get(Schema schema) throws JAXBException { - if(s != schema) { - u.setSchema(s = schema); - } - return u; - } - } - - private class Creator implements Pool.Creator { - private JAXBContext jc; - private String name; - - public Creator(Class[] classes) throws JAXBException { - jc = JAXBContext.newInstance(classes); - name = "JAXBumar: " + classes[0].getName(); - } - - // @Override - public SUnmarshaller create() throws APIException { - try { - return new SUnmarshaller(jc.createUnmarshaller()); - } catch (JAXBException e) { - throw new APIException(e); - } - } - - public String toString() { - return name; - } - - // @Override - public void destroy(SUnmarshaller sui) { - // Nothing to do - } - - // @Override - public boolean isValid(SUnmarshaller t) { - return true; - } - - // @Override - public void reuse(SUnmarshaller t) { - // Nothing to do here - } - - } - - private Pool getPool(Class ... classes) throws JAXBException { - Pool mp; - synchronized(pools) { - mp = pools.get(classes); - if(mp==null) { - pools.put(classes,mp = new Pool(new Creator(classes))); - } - } - return mp; - } - - public JAXBumar(Class ... classes) throws JAXBException { - cls = classes[0]; - mpool = getPool(classes); - schema = null; - } - - /** - * Constructs a new JAXBumar with schema validation enabled. - * - * @param schema - * @param theClass - * @throws JAXBException - */ - public JAXBumar(Schema schema, Class ... classes) throws JAXBException { - cls = classes[0]; - mpool = getPool(classes); - this.schema = schema; - } - - @SuppressWarnings("unchecked") - public O unmarshal(LogTarget env, Node node) throws JAXBException, APIException { - Pooled s = mpool.get(env); - try { - return s.content.get(schema).unmarshal(node,(Class)cls).getValue(); - } finally { - s.done(); - } - - } - - @SuppressWarnings("unchecked") - public O unmarshal(LogTarget env, String xml) throws JAXBException, APIException { - if(xml==null) throw new JAXBException("Null Input for String unmarshal"); - Pooled s = mpool.get(env); - try { - return (O)s.content.get(schema).unmarshal( - new StreamSource(new StringReader(xml)) - ,(Class)cls).getValue(); - } finally { - s.done(); - } - } - - @SuppressWarnings("unchecked") - public O unmarshal(LogTarget env, File xmlFile) throws JAXBException, APIException { - Pooled s = mpool.get(env); - try { - return (O)s.content.get(schema).unmarshal(xmlFile); - } finally { - s.done(); - } - - } - - @SuppressWarnings("unchecked") - public O unmarshal(LogTarget env,InputStream is) throws JAXBException, APIException { - Pooled s = mpool.get(env); - try { - return (O)s.content.get(schema).unmarshal(is); - } finally { - s.done(); - } - } - - @SuppressWarnings("unchecked") - public O unmarshal(LogTarget env, Reader rdr) throws JAXBException, APIException { - Pooled s = mpool.get(env); - try { - return (O)s.content.get(schema).unmarshal(rdr); - } finally { - s.done(); - } - } - - @SuppressWarnings("unchecked") - public O unmarshal(LogTarget env, XMLStreamReader xsr) throws JAXBException, APIException { - Pooled s = mpool.get(env); - try { - return (O)s.content.get(schema).unmarshal(xsr,(Class)cls).getValue(); - } finally { - s.done(); - } - } - - @SuppressWarnings("unchecked") - public O unmarshal(LogTarget env, XMLEventReader xer) throws JAXBException, APIException { - Pooled s = mpool.get(env); - try { - return (O)s.content.get(schema).unmarshal(xer,(Class)cls).getValue(); - } finally { - s.done(); - } - } - - @SuppressWarnings("unchecked") - public O newInstance() throws InstantiationException, IllegalAccessException{ - return ((Class)cls).newInstance(); - } + // Need to store off possible JAXBContexts based on Class, which will be stored in Creator + private static Map[],Pool> pools = new HashMap<>(); + + private Class cls; + private Schema schema; + private Pool mpool;; + + // Handle Marshaller class setting of properties only when needed + private class SUnmarshaller { + private Unmarshaller u; + private Schema s; + + public SUnmarshaller(Unmarshaller unmarshaller) throws JAXBException { + u = unmarshaller; + s = null; + } + + public Unmarshaller get(Schema schema) throws JAXBException { + if(s != schema) { + u.setSchema(s = schema); + } + return u; + } + } + + private class Creator implements Pool.Creator { + private JAXBContext jc; + private String name; + + public Creator(Class[] classes) throws JAXBException { + jc = JAXBContext.newInstance(classes); + name = "JAXBumar: " + classes[0].getName(); + } + + // @Override + public SUnmarshaller create() throws APIException { + try { + return new SUnmarshaller(jc.createUnmarshaller()); + } catch (JAXBException e) { + throw new APIException(e); + } + } + + public String toString() { + return name; + } + + // @Override + public void destroy(SUnmarshaller sui) { + // Nothing to do + } + + // @Override + public boolean isValid(SUnmarshaller t) { + return true; + } + + // @Override + public void reuse(SUnmarshaller t) { + // Nothing to do here + } + + } + + private Pool getPool(Class ... classes) throws JAXBException { + Pool mp; + synchronized(pools) { + mp = pools.get(classes); + if(mp==null) { + pools.put(classes,mp = new Pool(new Creator(classes))); + } + } + return mp; + } + + public JAXBumar(Class ... classes) throws JAXBException { + cls = classes[0]; + mpool = getPool(classes); + schema = null; + } + + /** + * Constructs a new JAXBumar with schema validation enabled. + * + * @param schema + * @param theClass + * @throws JAXBException + */ + public JAXBumar(Schema schema, Class ... classes) throws JAXBException { + cls = classes[0]; + mpool = getPool(classes); + this.schema = schema; + } + + @SuppressWarnings("unchecked") + public O unmarshal(LogTarget env, Node node) throws JAXBException, APIException { + Pooled s = mpool.get(env); + try { + return s.content.get(schema).unmarshal(node,(Class)cls).getValue(); + } finally { + s.done(); + } + + } + + @SuppressWarnings("unchecked") + public O unmarshal(LogTarget env, String xml) throws JAXBException, APIException { + if(xml==null) throw new JAXBException("Null Input for String unmarshal"); + Pooled s = mpool.get(env); + try { + return (O)s.content.get(schema).unmarshal( + new StreamSource(new StringReader(xml)) + ,(Class)cls).getValue(); + } finally { + s.done(); + } + } + + @SuppressWarnings("unchecked") + public O unmarshal(LogTarget env, File xmlFile) throws JAXBException, APIException { + Pooled s = mpool.get(env); + try { + return (O)s.content.get(schema).unmarshal(xmlFile); + } finally { + s.done(); + } + + } + + @SuppressWarnings("unchecked") + public O unmarshal(LogTarget env,InputStream is) throws JAXBException, APIException { + Pooled s = mpool.get(env); + try { + return (O)s.content.get(schema).unmarshal(is); + } finally { + s.done(); + } + } + + @SuppressWarnings("unchecked") + public O unmarshal(LogTarget env, Reader rdr) throws JAXBException, APIException { + Pooled s = mpool.get(env); + try { + return (O)s.content.get(schema).unmarshal(rdr); + } finally { + s.done(); + } + } + + @SuppressWarnings("unchecked") + public O unmarshal(LogTarget env, XMLStreamReader xsr) throws JAXBException, APIException { + Pooled s = mpool.get(env); + try { + return (O)s.content.get(schema).unmarshal(xsr,(Class)cls).getValue(); + } finally { + s.done(); + } + } + + @SuppressWarnings("unchecked") + public O unmarshal(LogTarget env, XMLEventReader xer) throws JAXBException, APIException { + Pooled s = mpool.get(env); + try { + return (O)s.content.get(schema).unmarshal(xer,(Class)cls).getValue(); + } finally { + s.done(); + } + } + + @SuppressWarnings("unchecked") + public O newInstance() throws InstantiationException, IllegalAccessException{ + return ((Class)cls).newInstance(); + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOObjectifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOObjectifier.java index ba1b981a..03e47911 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOObjectifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOObjectifier.java @@ -28,30 +28,30 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.Env; public interface IOObjectifier extends Objectifier { - /** - * Marshal to Object T from a Reader, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return T - * @throws APIException - */ - public abstract T objectify(Env env, Reader rdr) throws APIException; - - /** - * Marshal to Object T from an InputStream, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return T - * @throws APIException - */ - public abstract T objectify(Env env, InputStream is) throws APIException; + /** + * Marshal to Object T from a Reader, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return T + * @throws APIException + */ + public abstract T objectify(Env env, Reader rdr) throws APIException; + + /** + * Marshal to Object T from an InputStream, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return T + * @throws APIException + */ + public abstract T objectify(Env env, InputStream is) throws APIException; } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOStringifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOStringifier.java index 137e401f..ca03a1b8 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOStringifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/old/IOStringifier.java @@ -31,47 +31,47 @@ import org.onap.aaf.misc.env.Env; * Allow Extended IO interface usage without muddying up the Stringifier Interface */ public interface IOStringifier extends Stringifier { - /** - * Marshal from an Object T onto a Writer, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startTime(, Env.XML)" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return String - * @throws APIException - */ - public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException; - - /** - * Marshal from a String to an Object T, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return String - * @throws APIException - */ - public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException; + /** + * Marshal from an Object T onto a Writer, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startTime(, Env.XML)" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return String + * @throws APIException + */ + public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException; + + /** + * Marshal from a String to an Object T, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return String + * @throws APIException + */ + public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException; - /** - * Set Pretty XML, where possible - * - * @param pretty - * @throws APIException - */ - public abstract IOStringifier pretty(boolean pretty); + /** + * Set Pretty XML, where possible + * + * @param pretty + * @throws APIException + */ + public abstract IOStringifier pretty(boolean pretty); - /** - * Set Generate Fragment - * - * @param fragment - * @throws APIException - */ - public abstract IOStringifier asFragment(boolean fragment); + /** + * Set Generate Fragment + * + * @param fragment + * @throws APIException + */ + public abstract IOStringifier asFragment(boolean fragment); } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/old/Objectifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/old/Objectifier.java index 1fd3cdaf..1f58077e 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/old/Objectifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/old/Objectifier.java @@ -35,26 +35,26 @@ import org.onap.aaf.misc.env.LifeCycle; * the creation of an uninitialized object. */ public interface Objectifier extends LifeCycle { - /** - * Marshal to Object T from a String, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return T - * @throws APIException - */ - public abstract T objectify(Env env, String input) throws APIException; + /** + * Marshal to Object T from a String, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return T + * @throws APIException + */ + public abstract T objectify(Env env, String input) throws APIException; - /** - * Create a new object of type T. This is often more efficiently done with - * the underlying XML (or other) Library. - * @return T - * @throws APIException - */ - public abstract T newInstance() throws APIException; + /** + * Create a new object of type T. This is often more efficiently done with + * the underlying XML (or other) Library. + * @return T + * @throws APIException + */ + public abstract T newInstance() throws APIException; - + } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/old/OldDataFactory.java b/misc/env/src/main/java/org/onap/aaf/misc/env/old/OldDataFactory.java index 724e9f48..463bc15a 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/old/OldDataFactory.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/old/OldDataFactory.java @@ -32,16 +32,16 @@ import org.onap.aaf.misc.env.DataFactory; import org.onap.aaf.misc.env.Env; public interface OldDataFactory extends DataFactory { - public abstract String stringify(T type) throws APIException; - public abstract void stringify(T type, OutputStream os) throws APIException; - public abstract void stringify(T type, Writer writer) throws APIException; - public abstract T objectify(InputStream is) throws APIException; - public abstract T objectify(Reader rdr) throws APIException; - public abstract T objectify(String text) throws APIException; - public abstract T newInstance() throws APIException; - public abstract Data newData(T type); - public abstract Data newDataFromStream(Env env, InputStream input) throws APIException; - public abstract Data newDataFromString(String string); - + public abstract String stringify(T type) throws APIException; + public abstract void stringify(T type, OutputStream os) throws APIException; + public abstract void stringify(T type, Writer writer) throws APIException; + public abstract T objectify(InputStream is) throws APIException; + public abstract T objectify(Reader rdr) throws APIException; + public abstract T objectify(String text) throws APIException; + public abstract T newInstance() throws APIException; + public abstract Data newData(T type); + public abstract Data newDataFromStream(Env env, InputStream input) throws APIException; + public abstract Data newDataFromString(String string); + } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/old/Stringifier.java b/misc/env/src/main/java/org/onap/aaf/misc/env/old/Stringifier.java index eaea7f6a..01689f38 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/old/Stringifier.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/old/Stringifier.java @@ -31,18 +31,18 @@ import org.onap.aaf.misc.env.LifeCycle; * Stringifier abstracts the marshaling of a String to an Object */ public interface Stringifier extends LifeCycle { - - /** - * Marshal from a String to an Object T, using contents from Env as necessary.

    - * - * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark - * XML time, since this is often a costly process. - * - * @param env - * @param input - * @return String - * @throws APIException - */ - public abstract String stringify(Env env, T input, boolean ... options) throws APIException; - + + /** + * Marshal from a String to an Object T, using contents from Env as necessary.

    + * + * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark + * XML time, since this is often a costly process. + * + * @param env + * @param input + * @return String + * @throws APIException + */ + public abstract String stringify(Env env, T input, boolean ... options) throws APIException; + } \ No newline at end of file diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java index ebae19b4..ae78918c 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java @@ -38,273 +38,273 @@ import javax.xml.datatype.XMLGregorianCalendar; public class Chrono { private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; - public final static DateFormat dateFmt, dateOnlyFmt, niceDateFmt, utcFmt,iso8601Fmt; - // Give general access to XML DataType Factory, since it's pretty common - public static final DatatypeFactory xmlDatatypeFactory; - - static { - try { - xmlDatatypeFactory = DatatypeFactory.newInstance(); - } catch (DatatypeConfigurationException e) { - throw new RuntimeException(e); - } - dateOnlyFmt = new SimpleDateFormat("yyyy-MM-dd"); - niceDateFmt = new SimpleDateFormat("yyyy/MM/dd HH:mm zzz"); - dateFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - utcFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - iso8601Fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); - utcFmt.setTimeZone(TimeZone.getTimeZone("UTC")); - } - - - public static class Formatter8601 extends Formatter { - - @Override - public String format(LogRecord r) { - StringBuilder sb = new StringBuilder(); - sb.append(dateFmt.format(new Date(r.getMillis()))); - sb.append(' '); - sb.append(r.getThreadID()); - sb.append(' '); - sb.append(r.getLevel()); - sb.append(": "); - sb.append(r.getMessage()); - sb.append('\n'); - return sb.toString(); - } - - } - - /** - * timeStamp - * - * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with "now" - * @return - */ - public static XMLGregorianCalendar timeStamp() { - return xmlDatatypeFactory.newXMLGregorianCalendar(new GregorianCalendar()); - } - - /** - * timestamp - * - * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with passed in Date - * @param date - * @return - */ - public static XMLGregorianCalendar timeStamp(Date date) { - GregorianCalendar gc = new GregorianCalendar(); - gc.setTime(date); - return xmlDatatypeFactory.newXMLGregorianCalendar(gc); - } - - public static XMLGregorianCalendar timeStamp(GregorianCalendar gc) { - return xmlDatatypeFactory.newXMLGregorianCalendar(gc); - } - - public static String utcStamp() { - return utcFmt.format(new Date()); - } - - public static String utcStamp(Date date) { - if(date==null)return ""; - return utcFmt.format(date); - } - - public static String utcStamp(GregorianCalendar gc) { - if(gc==null)return ""; - return utcFmt.format(gc.getTime()); - } - - public static String utcStamp(XMLGregorianCalendar xgc) { - if(xgc==null)return ""; - return utcFmt.format(xgc.toGregorianCalendar().getTime()); - } - - public static String dateStamp() { - return dateFmt.format(new Date()); - } - - public static String dateStamp(GregorianCalendar gc) { - if(gc == null)return ""; - return dateFmt.format(gc.getTime()); - } - - public static String dateStamp(Date date) { - if(date == null)return ""; - return dateFmt.format(date); - } - - public static String dateStamp(XMLGregorianCalendar xgc) { - if(xgc==null)return ""; - return dateFmt.format(xgc.toGregorianCalendar().getTime()); - } - - /** - * JAXB compatible dataTime Stamp - * - * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. - * - * @return - */ - public static String dateTime() { - return dateTime(new GregorianCalendar()); - } - - /** - * JAXB compatible dataTime Stamp - * - * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. - * - * @return - */ - public static String dateTime(Date date) { - GregorianCalendar gc = new GregorianCalendar(); - gc.setTime(date); - return dateTime(gc); - } - - /** - * JAXB compatible dataTime Stamp - * - * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. - * - * @return - */ - public static String dateTime(GregorianCalendar gc) { - if(gc == null)return ""; - TimeZone tz = gc.getTimeZone(); - int tz1 = (tz.getRawOffset()+tz.getDSTSavings())/0x8CA0; - int tz1abs = Math.abs(tz1); - return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d", - gc.get(GregorianCalendar.YEAR), - gc.get(GregorianCalendar.MONTH)+1, - gc.get(GregorianCalendar.DAY_OF_MONTH), - gc.get(GregorianCalendar.HOUR), - gc.get(GregorianCalendar.MINUTE), - gc.get(GregorianCalendar.SECOND), - gc.get(GregorianCalendar.MILLISECOND), - tz1==tz1abs?'+':'-', - tz1abs/100, - ((tz1abs-(tz1abs/100)*100)*6)/10 // Get the "10s", then convert to mins (without losing int place) - ); - } - - /** - * JAXB compatible dataTime Stamp - * - * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. - * - * @return - */ - public static String dateTime(XMLGregorianCalendar xgc) { - return xgc==null?"":dateTime(xgc.toGregorianCalendar()); - } - - public static String dateOnlyStamp() { - return dateOnlyFmt.format(new Date()); - } - - public static String dateOnlyStamp(GregorianCalendar gc) { - return gc == null?"":dateOnlyFmt.format(gc.getTime()); - } - - public static String dateOnlyStamp(Date date) { - return date == null?"":dateOnlyFmt.format(date); - } - - public static String dateOnlyStamp(XMLGregorianCalendar xgc) { - return xgc==null?"":dateOnlyFmt.format(xgc.toGregorianCalendar().getTime()); - } - - public static String niceDateStamp() { - return niceDateFmt.format(new Date()); - } - - public static String niceDateStamp(Date date) { - return date==null?"":niceDateFmt.format(date); - } - - public static String niceDateStamp(GregorianCalendar gc) { - return gc==null?"":niceDateFmt.format(gc.getTime()); - } - - public static String niceDateStamp(XMLGregorianCalendar xgc) { - return xgc==null?"":niceDateFmt.format(xgc.toGregorianCalendar().getTime()); - } - - - ////////////////////// HELPFUL Strings - public static final String BAD_DIR_CHARS_REGEX = "[/:\\;.]"; - public static final String SPLIT_DIR_REGEX = "/"; - - public static long firstMomentOfDay(long utc) { - GregorianCalendar begin = new GregorianCalendar(); - begin.setTimeInMillis(utc); - return firstMomentOfDay(begin).getTimeInMillis(); - } - - public static long lastMomentOfDay(long utc) { - GregorianCalendar end = new GregorianCalendar(); - end.setTimeInMillis(utc); - return lastMomentOfDay(end).getTimeInMillis(); - } - - public static GregorianCalendar firstMomentOfDay(GregorianCalendar begin) { - if(begin==null)begin = new GregorianCalendar(); - begin.set(GregorianCalendar.HOUR, 0); - begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM); - begin.set(GregorianCalendar.MINUTE, 0); - begin.set(GregorianCalendar.SECOND, 0); - begin.set(GregorianCalendar.MILLISECOND, 0); - return begin; - } - - public static GregorianCalendar lastMomentOfDay(GregorianCalendar end) { - if(end==null)end = new GregorianCalendar(); - end.set(GregorianCalendar.HOUR, 11); - end.set(GregorianCalendar.MINUTE, 59); - end.set(GregorianCalendar.SECOND, 59); - end.set(GregorianCalendar.MILLISECOND, 999); - end.set(GregorianCalendar.AM_PM, GregorianCalendar.PM); - return end; - } - - // UUID needs to be converted from UUID Epoch - public static final Date uuidToDate(UUID id) { - return new Date((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000); - } - - public static final long uuidToUnix(UUID id) { - return (id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000; - } - - public static float millisFromNanos(long start, long end) { - return (end - start) / 1000000f; - } - - - private static long sequence = new SecureRandom().nextInt(); - private static synchronized long sequence() { - return ++sequence; - } - - public static final UUID dateToUUID(Date origTime) { - return dateToUUID(origTime.getTime()); - } - - public static final UUID dateToUUID(long origTime) { - /* - * From Cassandra : http://wiki.apache.org/cassandra/FAQ - Magic number obtained from #cassandra's thobbs, who - claims to have stolen it from a Python library. - */ + public final static DateFormat dateFmt, dateOnlyFmt, niceDateFmt, utcFmt,iso8601Fmt; + // Give general access to XML DataType Factory, since it's pretty common + public static final DatatypeFactory xmlDatatypeFactory; + + static { + try { + xmlDatatypeFactory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + throw new RuntimeException(e); + } + dateOnlyFmt = new SimpleDateFormat("yyyy-MM-dd"); + niceDateFmt = new SimpleDateFormat("yyyy/MM/dd HH:mm zzz"); + dateFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + utcFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + iso8601Fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); + utcFmt.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + + public static class Formatter8601 extends Formatter { + + @Override + public String format(LogRecord r) { + StringBuilder sb = new StringBuilder(); + sb.append(dateFmt.format(new Date(r.getMillis()))); + sb.append(' '); + sb.append(r.getThreadID()); + sb.append(' '); + sb.append(r.getLevel()); + sb.append(": "); + sb.append(r.getMessage()); + sb.append('\n'); + return sb.toString(); + } + + } + + /** + * timeStamp + * + * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with "now" + * @return + */ + public static XMLGregorianCalendar timeStamp() { + return xmlDatatypeFactory.newXMLGregorianCalendar(new GregorianCalendar()); + } + + /** + * timestamp + * + * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with passed in Date + * @param date + * @return + */ + public static XMLGregorianCalendar timeStamp(Date date) { + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(date); + return xmlDatatypeFactory.newXMLGregorianCalendar(gc); + } + + public static XMLGregorianCalendar timeStamp(GregorianCalendar gc) { + return xmlDatatypeFactory.newXMLGregorianCalendar(gc); + } + + public static String utcStamp() { + return utcFmt.format(new Date()); + } + + public static String utcStamp(Date date) { + if(date==null)return ""; + return utcFmt.format(date); + } + + public static String utcStamp(GregorianCalendar gc) { + if(gc==null)return ""; + return utcFmt.format(gc.getTime()); + } + + public static String utcStamp(XMLGregorianCalendar xgc) { + if(xgc==null)return ""; + return utcFmt.format(xgc.toGregorianCalendar().getTime()); + } + + public static String dateStamp() { + return dateFmt.format(new Date()); + } + + public static String dateStamp(GregorianCalendar gc) { + if(gc == null)return ""; + return dateFmt.format(gc.getTime()); + } + + public static String dateStamp(Date date) { + if(date == null)return ""; + return dateFmt.format(date); + } + + public static String dateStamp(XMLGregorianCalendar xgc) { + if(xgc==null)return ""; + return dateFmt.format(xgc.toGregorianCalendar().getTime()); + } + + /** + * JAXB compatible dataTime Stamp + * + * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. + * + * @return + */ + public static String dateTime() { + return dateTime(new GregorianCalendar()); + } + + /** + * JAXB compatible dataTime Stamp + * + * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. + * + * @return + */ + public static String dateTime(Date date) { + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(date); + return dateTime(gc); + } + + /** + * JAXB compatible dataTime Stamp + * + * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. + * + * @return + */ + public static String dateTime(GregorianCalendar gc) { + if(gc == null)return ""; + TimeZone tz = gc.getTimeZone(); + int tz1 = (tz.getRawOffset()+tz.getDSTSavings())/0x8CA0; + int tz1abs = Math.abs(tz1); + return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d", + gc.get(GregorianCalendar.YEAR), + gc.get(GregorianCalendar.MONTH)+1, + gc.get(GregorianCalendar.DAY_OF_MONTH), + gc.get(GregorianCalendar.HOUR), + gc.get(GregorianCalendar.MINUTE), + gc.get(GregorianCalendar.SECOND), + gc.get(GregorianCalendar.MILLISECOND), + tz1==tz1abs?'+':'-', + tz1abs/100, + ((tz1abs-(tz1abs/100)*100)*6)/10 // Get the "10s", then convert to mins (without losing int place) + ); + } + + /** + * JAXB compatible dataTime Stamp + * + * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it. + * + * @return + */ + public static String dateTime(XMLGregorianCalendar xgc) { + return xgc==null?"":dateTime(xgc.toGregorianCalendar()); + } + + public static String dateOnlyStamp() { + return dateOnlyFmt.format(new Date()); + } + + public static String dateOnlyStamp(GregorianCalendar gc) { + return gc == null?"":dateOnlyFmt.format(gc.getTime()); + } + + public static String dateOnlyStamp(Date date) { + return date == null?"":dateOnlyFmt.format(date); + } + + public static String dateOnlyStamp(XMLGregorianCalendar xgc) { + return xgc==null?"":dateOnlyFmt.format(xgc.toGregorianCalendar().getTime()); + } + + public static String niceDateStamp() { + return niceDateFmt.format(new Date()); + } + + public static String niceDateStamp(Date date) { + return date==null?"":niceDateFmt.format(date); + } + + public static String niceDateStamp(GregorianCalendar gc) { + return gc==null?"":niceDateFmt.format(gc.getTime()); + } + + public static String niceDateStamp(XMLGregorianCalendar xgc) { + return xgc==null?"":niceDateFmt.format(xgc.toGregorianCalendar().getTime()); + } + + + ////////////////////// HELPFUL Strings + public static final String BAD_DIR_CHARS_REGEX = "[/:\\;.]"; + public static final String SPLIT_DIR_REGEX = "/"; + + public static long firstMomentOfDay(long utc) { + GregorianCalendar begin = new GregorianCalendar(); + begin.setTimeInMillis(utc); + return firstMomentOfDay(begin).getTimeInMillis(); + } + + public static long lastMomentOfDay(long utc) { + GregorianCalendar end = new GregorianCalendar(); + end.setTimeInMillis(utc); + return lastMomentOfDay(end).getTimeInMillis(); + } + + public static GregorianCalendar firstMomentOfDay(GregorianCalendar begin) { + if(begin==null)begin = new GregorianCalendar(); + begin.set(GregorianCalendar.HOUR, 0); + begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM); + begin.set(GregorianCalendar.MINUTE, 0); + begin.set(GregorianCalendar.SECOND, 0); + begin.set(GregorianCalendar.MILLISECOND, 0); + return begin; + } + + public static GregorianCalendar lastMomentOfDay(GregorianCalendar end) { + if(end==null)end = new GregorianCalendar(); + end.set(GregorianCalendar.HOUR, 11); + end.set(GregorianCalendar.MINUTE, 59); + end.set(GregorianCalendar.SECOND, 59); + end.set(GregorianCalendar.MILLISECOND, 999); + end.set(GregorianCalendar.AM_PM, GregorianCalendar.PM); + return end; + } + + // UUID needs to be converted from UUID Epoch + public static final Date uuidToDate(UUID id) { + return new Date((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000); + } + + public static final long uuidToUnix(UUID id) { + return (id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000; + } + + public static float millisFromNanos(long start, long end) { + return (end - start) / 1000000f; + } + + + private static long sequence = new SecureRandom().nextInt(); + private static synchronized long sequence() { + return ++sequence; + } + + public static final UUID dateToUUID(Date origTime) { + return dateToUUID(origTime.getTime()); + } + + public static final UUID dateToUUID(long origTime) { + /* + * From Cassandra : http://wiki.apache.org/cassandra/FAQ + Magic number obtained from #cassandra's thobbs, who + claims to have stolen it from a Python library. + */ long time = origTime * 10000 + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH; long timeLow = time & 0xffffffffL; long timeMid = time & 0xffff00000000L; long timeHi = time & 0xfff000000000000L; long upperLong = (timeLow << 32) | (timeMid >> 16) | (1 << 12) | (timeHi >> 48) ; return new java.util.UUID(upperLong, (0xC000000000000000L | sequence())); - } + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java index 9c4c4316..97d9de99 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java @@ -26,15 +26,15 @@ import java.io.OutputStream; public class DoubleOutputStream extends OutputStream { private OutputStream[] oss; - private boolean[] close; + private boolean[] close; - /** + /** * Create a Double Stream Writer * Some Streams should not be closed by this object (i.e. System.out), therefore, mark them with booleans */ public DoubleOutputStream(OutputStream a, boolean closeA, OutputStream b, boolean closeB) { - oss = new OutputStream[] {a,b}; - close = new boolean[] {closeA,closeB}; + oss = new OutputStream[] {a,b}; + close = new boolean[] {closeA,closeB}; } /** @@ -43,9 +43,9 @@ public class DoubleOutputStream extends OutputStream { */ @Override public void write(int c) throws IOException { - for(OutputStream os : oss) { - os.write(c); - } + for(OutputStream os : oss) { + os.write(c); + } } /** @@ -58,39 +58,39 @@ public class DoubleOutputStream extends OutputStream { */ @Override public void write(byte bbuf[], int off, int len) throws IOException { - for(OutputStream os : oss) { - os.write(bbuf,off,len); - } + for(OutputStream os : oss) { + os.write(bbuf,off,len); + } } @Override - public void write(byte[] b) throws IOException { - for(OutputStream os : oss) { - os.write(b); - } - } + public void write(byte[] b) throws IOException { + for(OutputStream os : oss) { + os.write(b); + } + } - /* (non-Javadoc) - * @see java.io.OutputStream#close() - */ - @Override - public void close() throws IOException { - for(int i=0;i */ public class Pool { - /** - * This is a constant which specified the default maximum number of unused - * objects to be held at any given time. - */ - private static final int MAX_RANGE = 6; // safety + /** + * This is a constant which specified the default maximum number of unused + * objects to be held at any given time. + */ + private static final int MAX_RANGE = 6; // safety - /** - * only Simple List needed. - * - * NOTE TO MAINTAINERS: THIS OBJECT DOES IT'S OWN SYNCHRONIZATION. All - * changes that touch list must account for correctly synchronizing list. - */ - private LinkedList> list; + /** + * only Simple List needed. + * + * NOTE TO MAINTAINERS: THIS OBJECT DOES IT'S OWN SYNCHRONIZATION. All + * changes that touch list must account for correctly synchronizing list. + */ + private LinkedList> list; - /** - * keep track of how many elements exist, to avoid asking list. - */ - private int count; + /** + * keep track of how many elements exist, to avoid asking list. + */ + private int count; - /** - * Spares are those Object that are primed and ready to go. - */ - private int spares; + /** + * Spares are those Object that are primed and ready to go. + */ + private int spares; - /** - * Actual MAX number of spares allowed to hang around. Can be set to - * something besides the default MAX_RANGE. - */ - private int max_range = MAX_RANGE; + /** + * Actual MAX number of spares allowed to hang around. Can be set to + * something besides the default MAX_RANGE. + */ + private int max_range = MAX_RANGE; - /** - * The Creator for this particular pool. It must work for type T. - */ - private Creator creator; + /** + * The Creator for this particular pool. It must work for type T. + */ + private Creator creator; - /** - * Create a new Pool, given the implementation of Creator, which must be - * able to create/destroy T objects at will. - * - * @param creator - */ - public Pool(Creator creator) { - count = spares = 0; - this.creator = creator; - list = new LinkedList<>(); - } + /** + * Create a new Pool, given the implementation of Creator, which must be + * able to create/destroy T objects at will. + * + * @param creator + */ + public Pool(Creator creator) { + count = spares = 0; + this.creator = creator; + list = new LinkedList<>(); + } - /** - * Preallocate a certain number of T Objects. Useful for services so that - * the first transactions don't get hit with all the Object creation costs - * - * @param lt - * @param prime - * @throws APIException - */ - public void prime(LogTarget lt, int prime) throws APIException { - for (int i = 0; i < prime; ++i) { - Pooled pt = new Pooled(creator.create(), this, lt); - synchronized (list) { - list.addFirst(pt); - ++count; - } - } + /** + * Preallocate a certain number of T Objects. Useful for services so that + * the first transactions don't get hit with all the Object creation costs + * + * @param lt + * @param prime + * @throws APIException + */ + public void prime(LogTarget lt, int prime) throws APIException { + for (int i = 0; i < prime; ++i) { + Pooled pt = new Pooled(creator.create(), this, lt); + synchronized (list) { + list.addFirst(pt); + ++count; + } + } - } + } - /** - * Destroy and remove all remaining objects. This is valuable for closing - * down all Allocated objects cleanly for exiting. It is also a good method - * for removing objects when, for instance, all Objects are invalid because - * of broken connections, etc. - */ - public void drain() { - synchronized (list) { - for (int i = 0; i < list.size(); ++i) { - Pooled pt = list.remove(); - creator.destroy(pt.content); - pt.logTarget.log("Pool drained ", creator.toString()); - } - count = spares = 0; - } + /** + * Destroy and remove all remaining objects. This is valuable for closing + * down all Allocated objects cleanly for exiting. It is also a good method + * for removing objects when, for instance, all Objects are invalid because + * of broken connections, etc. + */ + public void drain() { + synchronized (list) { + for (int i = 0; i < list.size(); ++i) { + Pooled pt = list.remove(); + creator.destroy(pt.content); + pt.logTarget.log("Pool drained ", creator.toString()); + } + count = spares = 0; + } - } + } - /** - * This is the essential function for Pool. Get an Object "T" inside a - * "Pooled" object. If there is a spare Object, then use it. If not, then - * create and pass back. - * - * This one uses a Null LogTarget - * - * IMPORTANT: When the use of this object is done (and the object is still - * in a valid state), then "done()" should be called immediately to allow - * the object to be reused. That is the point of the Pool... - * - * If the Object is in an invalid state, then "toss()" should be used so the - * Pool doesn't pass on invalid objects to others. - * - * @param lt - * @return - * @throws APIException - */ - public Pooled get() throws APIException { - Pooled pt; - synchronized (list) { - if (list.isEmpty()) { - pt = null; - } else { - pt = list.removeLast(); - --count; - creator.reuse(pt.content); - } - } - if (pt == null) { - if (spares < max_range) - ++spares; - pt = new Pooled(creator.create(), this, LogTarget.NULL); - } else { - if (spares > 1) - --spares; - } - return pt; - } + /** + * This is the essential function for Pool. Get an Object "T" inside a + * "Pooled" object. If there is a spare Object, then use it. If not, then + * create and pass back. + * + * This one uses a Null LogTarget + * + * IMPORTANT: When the use of this object is done (and the object is still + * in a valid state), then "done()" should be called immediately to allow + * the object to be reused. That is the point of the Pool... + * + * If the Object is in an invalid state, then "toss()" should be used so the + * Pool doesn't pass on invalid objects to others. + * + * @param lt + * @return + * @throws APIException + */ + public Pooled get() throws APIException { + Pooled pt; + synchronized (list) { + if (list.isEmpty()) { + pt = null; + } else { + pt = list.removeLast(); + --count; + creator.reuse(pt.content); + } + } + if (pt == null) { + if (spares < max_range) + ++spares; + pt = new Pooled(creator.create(), this, LogTarget.NULL); + } else { + if (spares > 1) + --spares; + } + return pt; + } - /** - * This is the essential function for Pool. Get an Object "T" inside a - * "Pooled" object. If there is a spare Object, then use it. If not, then - * create and pass back. - * - * If you don't have access to a LogTarget from Env, use LogTarget.NULL - * - * IMPORTANT: When the use of this object is done (and the object is still - * in a valid state), then "done()" should be called immediately to allow - * the object to be reused. That is the point of the Pool... - * - * If the Object is in an invalid state, then "toss()" should be used so the - * Pool doesn't pass on invalid objects to others. - * - * @param lt - * @return - * @throws APIException - */ - public Pooled get(LogTarget lt) throws APIException { - Pooled pt; - synchronized (list) { - if (list.isEmpty()) { - pt = null; - } else { - pt = list.remove(); - --count; - creator.reuse(pt.content); - } - } - if (pt == null) { - if (spares < max_range) - ++spares; - pt = new Pooled(creator.create(), this, lt); - lt.log("Pool created ", creator.toString()); - } else { - if (spares > 1) - --spares; - } - return pt; - } + /** + * This is the essential function for Pool. Get an Object "T" inside a + * "Pooled" object. If there is a spare Object, then use it. If not, then + * create and pass back. + * + * If you don't have access to a LogTarget from Env, use LogTarget.NULL + * + * IMPORTANT: When the use of this object is done (and the object is still + * in a valid state), then "done()" should be called immediately to allow + * the object to be reused. That is the point of the Pool... + * + * If the Object is in an invalid state, then "toss()" should be used so the + * Pool doesn't pass on invalid objects to others. + * + * @param lt + * @return + * @throws APIException + */ + public Pooled get(LogTarget lt) throws APIException { + Pooled pt; + synchronized (list) { + if (list.isEmpty()) { + pt = null; + } else { + pt = list.remove(); + --count; + creator.reuse(pt.content); + } + } + if (pt == null) { + if (spares < max_range) + ++spares; + pt = new Pooled(creator.create(), this, lt); + lt.log("Pool created ", creator.toString()); + } else { + if (spares > 1) + --spares; + } + return pt; + } - /** - * This function will validate whether the Objects are still in a usable - * state. If not, they are tossed from the Pool. This is valuable to have - * when Remote Connections go down, and there is a question on whether the - * Pooled Objects are still functional. - * - * @return - */ - public boolean validate() { - boolean rv = true; - synchronized (list) { - for (Pooled t : list) { - if (!creator.isValid(t.content)) { - rv = false; - t.toss(); - list.remove(t); - } - } - } - return rv; - } + /** + * This function will validate whether the Objects are still in a usable + * state. If not, they are tossed from the Pool. This is valuable to have + * when Remote Connections go down, and there is a question on whether the + * Pooled Objects are still functional. + * + * @return + */ + public boolean validate() { + boolean rv = true; + synchronized (list) { + for (Pooled t : list) { + if (!creator.isValid(t.content)) { + rv = false; + t.toss(); + list.remove(t); + } + } + } + return rv; + } - /** - * This is an internal method, used only by the Internal Pooled class. - * - * The Pooled class "offers" it's Object back after use. It is an - * "offer", because Pool will simply destroy and remove the object if it has - * more than enough spares. - * - * @param lt - * @param used - * @return - */ - // Used only by Pooled - private boolean offer(LogTarget lt, Pooled used) { - if (count < spares) { - synchronized (list) { - list.addFirst(used); - ++count; - } - lt.log("Pool recovered ", creator.toString()); - } else { - lt.log("Pool destroyed ", creator.toString()); - creator.destroy(used.content); - } - return false; - } + /** + * This is an internal method, used only by the Internal Pooled class. + * + * The Pooled class "offers" it's Object back after use. It is an + * "offer", because Pool will simply destroy and remove the object if it has + * more than enough spares. + * + * @param lt + * @param used + * @return + */ + // Used only by Pooled + private boolean offer(LogTarget lt, Pooled used) { + if (count < spares) { + synchronized (list) { + list.addFirst(used); + ++count; + } + lt.log("Pool recovered ", creator.toString()); + } else { + lt.log("Pool destroyed ", creator.toString()); + creator.destroy(used.content); + } + return false; + } - /** - * The Creator Interface give the Pool the ability to Create, Destroy and - * Validate the Objects it is maintaining. Thus, it is a specially written - * Implementation for each type. - * - * @author Jonathan - * - * @param - */ - public interface Creator { - public T create() throws APIException; + /** + * The Creator Interface give the Pool the ability to Create, Destroy and + * Validate the Objects it is maintaining. Thus, it is a specially written + * Implementation for each type. + * + * @author Jonathan + * + * @param + */ + public interface Creator { + public T create() throws APIException; - public void destroy(T t); + public void destroy(T t); - public boolean isValid(T t); + public boolean isValid(T t); - public void reuse(T t); - } + public void reuse(T t); + } - /** - * The "Pooled" class is the transient class that wraps the actual Object - * T for API use/ It gives the ability to return ("done()", or "toss()") the - * Object to the Pool when processing is finished. - * - * For Safety, i.e. to avoid memory leaks and invalid Object States, there - * is a "finalize" method. It is strictly for when coder forgets to return - * the object, or perhaps hasn't covered the case during Exceptions or - * Runtime Exceptions with finally (preferred). This should not be - * considered normal procedure, as finalize() is called at an undetermined - * time during garbage collection, and is thus rather useless for a Pool. - * However, we don't want Coding Mistakes to put the whole program in an - * invalid state, so if something happened such that "done()" or "toss()" - * were not called, the resource is still cleaned up as well as possible. - * - * @author Jonathan - * - * @param - */ - public static class Pooled { - public final T content; - private Pool pool; - protected LogTarget logTarget; + /** + * The "Pooled" class is the transient class that wraps the actual Object + * T for API use/ It gives the ability to return ("done()", or "toss()") the + * Object to the Pool when processing is finished. + * + * For Safety, i.e. to avoid memory leaks and invalid Object States, there + * is a "finalize" method. It is strictly for when coder forgets to return + * the object, or perhaps hasn't covered the case during Exceptions or + * Runtime Exceptions with finally (preferred). This should not be + * considered normal procedure, as finalize() is called at an undetermined + * time during garbage collection, and is thus rather useless for a Pool. + * However, we don't want Coding Mistakes to put the whole program in an + * invalid state, so if something happened such that "done()" or "toss()" + * were not called, the resource is still cleaned up as well as possible. + * + * @author Jonathan + * + * @param + */ + public static class Pooled { + public final T content; + private Pool pool; + protected LogTarget logTarget; - /** - * Create the Wrapping Object Pooled. - * - * @param t - * @param pool - * @param logTarget - */ - public Pooled(T t, Pool pool, LogTarget logTarget) { - content = t; - this.pool = pool; - this.logTarget = logTarget; - } + /** + * Create the Wrapping Object Pooled. + * + * @param t + * @param pool + * @param logTarget + */ + public Pooled(T t, Pool pool, LogTarget logTarget) { + content = t; + this.pool = pool; + this.logTarget = logTarget; + } - /** - * This is the key API for the Pool, as calling "done()" offers this - * object back to the Pool for reuse. - * - * Do not use the Pooled object again after calling "done()". - */ - public void done() { - if (pool != null) { - pool.offer(logTarget, this); - } - } + /** + * This is the key API for the Pool, as calling "done()" offers this + * object back to the Pool for reuse. + * + * Do not use the Pooled object again after calling "done()". + */ + public void done() { + if (pool != null) { + pool.offer(logTarget, this); + } + } - /** - * The user of the Object may discover that the Object t is no longer in - * a valid state. Don't put Garbage back in the Refrigerator... Toss it, - * if it's no longer valid. - * - * toss() is also used for draining the Pool, etc. - * - * toss() will attempt to destroy the Object by using the Creator - * Interface. - * - */ - public void toss() { - if (pool != null) { - pool.creator.destroy(content); - } - // Don't allow finalize to put it back in. - pool = null; - } + /** + * The user of the Object may discover that the Object t is no longer in + * a valid state. Don't put Garbage back in the Refrigerator... Toss it, + * if it's no longer valid. + * + * toss() is also used for draining the Pool, etc. + * + * toss() will attempt to destroy the Object by using the Creator + * Interface. + * + */ + public void toss() { + if (pool != null) { + pool.creator.destroy(content); + } + // Don't allow finalize to put it back in. + pool = null; + } - /** - * Just in case someone neglected to offer back object... Do not rely on - * this, as there is no specific time when finalize is called, which - * rather defeats the purpose of a Pool. - */ - @Override - protected void finalize() throws Throwable { - if (pool != null) { - done(); - pool = null; - } - } - } + /** + * Just in case someone neglected to offer back object... Do not rely on + * this, as there is no specific time when finalize is called, which + * rather defeats the purpose of a Pool. + */ + @Override + protected void finalize() throws Throwable { + if (pool != null) { + done(); + pool = null; + } + } + } - /** - * Get the maximum number of spare objects allowed at any moment - * - * @return - */ - public int getMaxRange() { - return max_range; - } + /** + * Get the maximum number of spare objects allowed at any moment + * + * @return + */ + public int getMaxRange() { + return max_range; + } - /** - * Set a Max Range for numbers of spare objects waiting to be used. - * - * No negative numbers are allowed - * - * @return - */ - public void setMaxRange(int max_range) { - // Do not allow negative numbers - this.max_range = Math.max(0, max_range); - } + /** + * Set a Max Range for numbers of spare objects waiting to be used. + * + * No negative numbers are allowed + * + * @return + */ + public void setMaxRange(int max_range) { + // Do not allow negative numbers + this.max_range = Math.max(0, max_range); + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java index 6892a4b5..759a8c8b 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java @@ -54,71 +54,71 @@ import org.onap.aaf.misc.env.LifeCycle; * @param */ public class RefreshableThreadObject> { - private Map objs; - private long refreshed; - private Constructor cnst; - - /** - * The passed in class must implement the constructor - *

    -	 *   public MyClass(Env env) {
    -	 *     ...
    -	 *   }
    -	 * 
    - * @param clss - * @throws APIException - */ - public RefreshableThreadObject(Class clss) throws APIException { - objs = new ConcurrentHashMap<>(); - try { - cnst = clss.getConstructor(new Class[]{Env.class} ); - } catch (Exception e) { - throw new APIException(e); - } - } - - /** - * Get the "T" class from the current thread - * - * @param env - * @return T - * @throws APIException - */ - public T get(Env env) throws APIException { - Thread t = Thread.currentThread(); - T obj = objs.get(t); - if(obj==null || refreshed>obj.created()) { - try { - obj = cnst.newInstance(new Object[]{env}); - } catch (InvocationTargetException e) { - throw new APIException(e.getTargetException()); - } catch (Exception e) { - throw new APIException(e); - } - T destroyMe = objs.put(t,obj); - if(destroyMe!=null) { - destroyMe.destroy(env); - } - } - return obj; - } - - /** - * Mark the timestamp of refreshed. - * - * @param env - */ - public void refresh(Env env) { - refreshed = System.currentTimeMillis(); - } - - /** - * Remove the object from the Thread instances - * @param env - */ - public void remove(Env env) { - T obj = objs.remove(Thread.currentThread()); - if(obj!=null) - obj.destroy(env); - } + private Map objs; + private long refreshed; + private Constructor cnst; + + /** + * The passed in class must implement the constructor + *
    +     *   public MyClass(Env env) {
    +     *     ...
    +     *   }
    +     * 
    + * @param clss + * @throws APIException + */ + public RefreshableThreadObject(Class clss) throws APIException { + objs = new ConcurrentHashMap<>(); + try { + cnst = clss.getConstructor(new Class[]{Env.class} ); + } catch (Exception e) { + throw new APIException(e); + } + } + + /** + * Get the "T" class from the current thread + * + * @param env + * @return T + * @throws APIException + */ + public T get(Env env) throws APIException { + Thread t = Thread.currentThread(); + T obj = objs.get(t); + if(obj==null || refreshed>obj.created()) { + try { + obj = cnst.newInstance(new Object[]{env}); + } catch (InvocationTargetException e) { + throw new APIException(e.getTargetException()); + } catch (Exception e) { + throw new APIException(e); + } + T destroyMe = objs.put(t,obj); + if(destroyMe!=null) { + destroyMe.destroy(env); + } + } + return obj; + } + + /** + * Mark the timestamp of refreshed. + * + * @param env + */ + public void refresh(Env env) { + refreshed = System.currentTimeMillis(); + } + + /** + * Remove the object from the Thread instances + * @param env + */ + public void remove(Env env) { + T obj = objs.remove(Thread.currentThread()); + if(obj!=null) + obj.destroy(env); + } } diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java index efb68120..4069c329 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java @@ -30,73 +30,73 @@ package org.onap.aaf.misc.env.util; */ public class Split { - private static final String[] BLANK = new String[0]; - - public static String[] split(char c, String value) { - if(value==null) { - return BLANK; - } + private static final String[] BLANK = new String[0]; + + public static String[] split(char c, String value) { + if(value==null) { + return BLANK; + } - // Count items to preallocate Array (memory alloc is more expensive than counting twice) - int count,idx; - for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count); - String[] rv = new String[count]; - if(count==1) { - rv[0]=value; - } else { - int last=0; - count=-1; - for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) { - rv[++count]=value.substring(last,idx); - last = ++idx; - } - rv[++count]=value.substring(last); - } - return rv; - } + // Count items to preallocate Array (memory alloc is more expensive than counting twice) + int count,idx; + for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count); + String[] rv = new String[count]; + if(count==1) { + rv[0]=value; + } else { + int last=0; + count=-1; + for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) { + rv[++count]=value.substring(last,idx); + last = ++idx; + } + rv[++count]=value.substring(last); + } + return rv; + } - public static String[] splitTrim(char c, String value) { - if(value==null) { - return BLANK; - } - // Count items to preallocate Array (memory alloc is more expensive than counting twice) - int count,idx; - for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count); - String[] rv = new String[count]; - if(count==1) { - rv[0]=value.trim(); - } else { - int last=0; - count=-1; - for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) { - rv[++count]=value.substring(last,idx).trim(); - last = ++idx; - } - rv[++count]=value.substring(last).trim(); - } - return rv; - } + public static String[] splitTrim(char c, String value) { + if(value==null) { + return BLANK; + } + // Count items to preallocate Array (memory alloc is more expensive than counting twice) + int count,idx; + for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count); + String[] rv = new String[count]; + if(count==1) { + rv[0]=value.trim(); + } else { + int last=0; + count=-1; + for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) { + rv[++count]=value.substring(last,idx).trim(); + last = ++idx; + } + rv[++count]=value.substring(last).trim(); + } + return rv; + } - public static String[] splitTrim(char c, String value, int size) { - if(value==null) { - return BLANK; - } + public static String[] splitTrim(char c, String value, int size) { + if(value==null) { + return BLANK; + } - int idx; - String[] rv = new String[size]; - if(size==1) { - rv[0]=value.trim(); - } else { - int last=0; - int count=-1; - size-=2; - for(idx=value.indexOf(c);idx>=0 && count=0 && countinitialSize is negative */ public StringBuilderOutputStream(int initialSize) { - if (initialSize < 0) { - throw new IllegalArgumentException("Negative buffer size"); - } - buf = new StringBuilder(initialSize); + if (initialSize < 0) { + throw new IllegalArgumentException("Negative buffer size"); + } + buf = new StringBuilder(initialSize); } /** * Write a single character. */ public void write(int c) { - buf.append((byte) c); + buf.append((byte) c); } /** @@ -88,15 +88,15 @@ public class StringBuilderOutputStream extends OutputStream { } @Override - public void write(byte[] b) throws IOException { - buf.append(new String(b)); - } + public void write(byte[] b) throws IOException { + buf.append(new String(b)); + } - /** + /** * Write a string. */ public void write(String str) { - buf.append(str); + buf.append(str); } /** @@ -107,23 +107,23 @@ public class StringBuilderOutputStream extends OutputStream { * @param len Number of characters to write */ public void write(String str, int off, int len) { - buf.append(str,off,len); + buf.append(str,off,len); } public StringBuilderOutputStream append(CharSequence csq) { - if (csq == null) { - write("null"); - } else { - for(int i = 0;iinitialSize is negative */ public StringBuilderWriter(int initialSize) { - if (initialSize < 0) { - throw new IllegalArgumentException("Negative buffer size"); - } - buf = new StringBuilder(initialSize); + if (initialSize < 0) { + throw new IllegalArgumentException("Negative buffer size"); + } + buf = new StringBuilder(initialSize); } /** * Write a single character. */ public void write(int c) { - buf.append((char) c); + buf.append((char) c); } /** @@ -90,7 +90,7 @@ public class StringBuilderWriter extends Writer { * Write a string. */ public void write(String str) { - buf.append(str); + buf.append(str); } /** @@ -101,23 +101,23 @@ public class StringBuilderWriter extends Writer { * @param len Number of characters to write */ public void write(String str, int off, int len) { - char[] chars = new char[len]; - str.getChars(off, off+len, chars, 0); - buf.append(chars); + char[] chars = new char[len]; + str.getChars(off, off+len, chars, 0); + buf.append(chars); } public StringBuilderWriter append(CharSequence csq) { - if (csq == null) { - write("null"); - } else { - buf.append(csq); - } - return this; + if (csq == null) { + write("null"); + } else { + buf.append(csq); + } + return this; } public StringBuilderWriter append(CharSequence csq, int start, int end) { - CharSequence cs = (csq == null ? "null" : csq); - return append(cs.subSequence(start, end)); + CharSequence cs = (csq == null ? "null" : csq); + return append(cs.subSequence(start, end)); } /** @@ -137,15 +137,15 @@ public class StringBuilderWriter extends Writer { * @since 1.5 */ public StringBuilderWriter append(char c) { - buf.append(c); - return this; + buf.append(c); + return this; } /** * Return the buffer's current value as a string. */ public String toString() { - return buf.toString(); + return buf.toString(); } /** @@ -154,19 +154,19 @@ public class StringBuilderWriter extends Writer { * @return StringBuffer holding the current buffer value. */ public StringBuilder getBuffer() { - return buf; + return buf; } public void reset() { - buf.setLength(0); + buf.setLength(0); } - @Override - public void flush() throws IOException { - } + @Override + public void flush() throws IOException { + } - @Override - public void close() throws IOException { - } + @Override + public void close() throws IOException { + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_APIExceptionTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_APIExceptionTest.java index b0c60878..c1d7f6b1 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_APIExceptionTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_APIExceptionTest.java @@ -27,45 +27,45 @@ import org.junit.Test; public class JU_APIExceptionTest { - private static final String EXCEPTION_MESSAGE = "New API Exception for test"; + private static final String EXCEPTION_MESSAGE = "New API Exception for test"; - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testNewAPIExceptionWithMessage() { - APIException exception = new APIException(EXCEPTION_MESSAGE); + @Test + public void testNewAPIExceptionWithMessage() { + APIException exception = new APIException(EXCEPTION_MESSAGE); - assertEquals(exception.getMessage(), EXCEPTION_MESSAGE); - } + assertEquals(exception.getMessage(), EXCEPTION_MESSAGE); + } - @Test - public void testNewAPIExceptionCreatedWithMessageAndThrowable() { - Throwable throwable = new Throwable(); - APIException exception = new APIException(EXCEPTION_MESSAGE, throwable); + @Test + public void testNewAPIExceptionCreatedWithMessageAndThrowable() { + Throwable throwable = new Throwable(); + APIException exception = new APIException(EXCEPTION_MESSAGE, throwable); - assertEquals(exception.getMessage(), EXCEPTION_MESSAGE); - assertEquals(exception.getCause(), throwable); - } + assertEquals(exception.getMessage(), EXCEPTION_MESSAGE); + assertEquals(exception.getCause(), throwable); + } - @Test - public void testNewAPIExceptionCreatedWithThrowable() { - Throwable throwable = new Throwable(); - APIException exception = new APIException(throwable); + @Test + public void testNewAPIExceptionCreatedWithThrowable() { + Throwable throwable = new Throwable(); + APIException exception = new APIException(throwable); - assertEquals(exception.getCause(), throwable); - } + assertEquals(exception.getCause(), throwable); + } - @Test - public void testPayloadSetter() { - Throwable throwable = new Throwable(); - Object payload = new Object(); + @Test + public void testPayloadSetter() { + Throwable throwable = new Throwable(); + Object payload = new Object(); - APIException exception = new APIException(throwable); + APIException exception = new APIException(throwable); - exception.setPayload(payload); + exception.setPayload(payload); - assertEquals(exception.getPayload(), payload); - } + assertEquals(exception.getPayload(), payload); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BasicTransTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BasicTransTest.java index 6a090167..0525bd66 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BasicTransTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BasicTransTest.java @@ -33,77 +33,77 @@ import org.onap.aaf.misc.env.impl.BasicTrans; @RunWith(MockitoJUnitRunner.class) public class JU_BasicTransTest { - BasicTrans trans = null; - - @Mock - private EnvJAXB env; - - @Mock - private TimeTaken timeTaken; - - @Before - public void setUp() throws Exception { - trans = new BasicTrans(env); - } - - @Test - public void testSlot() { - Slot slot = new Slot(1, "XML"); - when(env.slot("XML")).thenReturn(slot); - - Slot outputSlot = trans.slot("XML"); - Object[] state = new Object[2]; - - slot.put(state, "JSON"); - - assertEquals(slot.get(state), "JSON"); - assertEquals(slot.getKey(), outputSlot.getKey()); - assertEquals(slot.toString(), outputSlot.toString()); - } - - @Test - public void testGetStaticSlot() { - StaticSlot staticSlot = new StaticSlot(1, "XML"); - when(env.get(staticSlot)).thenReturn(staticSlot.toString()); - - assertEquals(staticSlot.toString(), trans.get(staticSlot)); - } - - @Test - public void testGetStaticSlotWithT() { - StaticSlot staticSlot = new StaticSlot(1, "XML"); - when(env.get(staticSlot, "XML")).thenReturn(staticSlot.getKey()); - - assertEquals(staticSlot.getKey(), trans.get(staticSlot, "XML")); - } - - @Test - public void testSetProperty() { - String tag = "tag"; - String value = "value"; - String defltValue = "diffValue"; - when(env.setProperty(tag, value)).thenReturn(value); - when(env.getProperty(tag)).thenReturn(value); - when(env.getProperty(tag, defltValue)).thenReturn(defltValue); - - assertEquals(value, trans.setProperty(tag, value)); - assertEquals(value, trans.getProperty(tag)); - assertEquals(defltValue, trans.getProperty(tag, defltValue)); - } - - @Test - public void testDecryptor() { - when(env.decryptor()).thenReturn(Decryptor.NULL); - - assertEquals(Decryptor.NULL, trans.decryptor()); - assertEquals("tag", trans.decryptor().decrypt("tag")); - } - - @Test - public void testEncryptor() { - when(env.encryptor()).thenReturn(Encryptor.NULL); - - assertEquals(Encryptor.NULL, trans.encryptor()); - assertEquals("tag", trans.encryptor().encrypt("tag")); - } + BasicTrans trans = null; + + @Mock + private EnvJAXB env; + + @Mock + private TimeTaken timeTaken; + + @Before + public void setUp() throws Exception { + trans = new BasicTrans(env); + } + + @Test + public void testSlot() { + Slot slot = new Slot(1, "XML"); + when(env.slot("XML")).thenReturn(slot); + + Slot outputSlot = trans.slot("XML"); + Object[] state = new Object[2]; + + slot.put(state, "JSON"); + + assertEquals(slot.get(state), "JSON"); + assertEquals(slot.getKey(), outputSlot.getKey()); + assertEquals(slot.toString(), outputSlot.toString()); + } + + @Test + public void testGetStaticSlot() { + StaticSlot staticSlot = new StaticSlot(1, "XML"); + when(env.get(staticSlot)).thenReturn(staticSlot.toString()); + + assertEquals(staticSlot.toString(), trans.get(staticSlot)); + } + + @Test + public void testGetStaticSlotWithT() { + StaticSlot staticSlot = new StaticSlot(1, "XML"); + when(env.get(staticSlot, "XML")).thenReturn(staticSlot.getKey()); + + assertEquals(staticSlot.getKey(), trans.get(staticSlot, "XML")); + } + + @Test + public void testSetProperty() { + String tag = "tag"; + String value = "value"; + String defltValue = "diffValue"; + when(env.setProperty(tag, value)).thenReturn(value); + when(env.getProperty(tag)).thenReturn(value); + when(env.getProperty(tag, defltValue)).thenReturn(defltValue); + + assertEquals(value, trans.setProperty(tag, value)); + assertEquals(value, trans.getProperty(tag)); + assertEquals(defltValue, trans.getProperty(tag, defltValue)); + } + + @Test + public void testDecryptor() { + when(env.decryptor()).thenReturn(Decryptor.NULL); + + assertEquals(Decryptor.NULL, trans.decryptor()); + assertEquals("tag", trans.decryptor().decrypt("tag")); + } + + @Test + public void testEncryptor() { + when(env.encryptor()).thenReturn(Encryptor.NULL); + + assertEquals(Encryptor.NULL, trans.encryptor()); + assertEquals("tag", trans.encryptor().encrypt("tag")); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java index 474f646c..caaca1d1 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java @@ -34,54 +34,54 @@ import org.mockito.Mock; public class JU_LogTargetTest { - @Mock - Throwable t; + @Mock + Throwable t; - @Before - public void setup() { - t = mock(Throwable.class); - } + @Before + public void setup() { + t = mock(Throwable.class); + } - @Test - public void testLogTargetNull() { - LogTarget nullTarget = LogTarget.NULL; + @Test + public void testLogTargetNull() { + LogTarget nullTarget = LogTarget.NULL; - // Expect methods doing nothing as no implemenation provided. - nullTarget.log(new Throwable(), null, null); - nullTarget.log("String", null); - nullTarget.printf(null, null, null); + // Expect methods doing nothing as no implemenation provided. + nullTarget.log(new Throwable(), null, null); + nullTarget.log("String", null); + nullTarget.printf(null, null, null); - assertFalse(nullTarget.isLoggable()); - } + assertFalse(nullTarget.isLoggable()); + } - @Test - public void testLogTargetSysOut() { - LogTarget outTarget = LogTarget.SYSOUT; + @Test + public void testLogTargetSysOut() { + LogTarget outTarget = LogTarget.SYSOUT; - outTarget.printf("format", new Date()); - outTarget.log("null", null, null); + outTarget.printf("format", new Date()); + outTarget.log("null", null, null); - outTarget.log(t); - outTarget.log(t, "First String Object"); + outTarget.log(t); + outTarget.log(t, "First String Object"); - assertTrue(outTarget.isLoggable()); + assertTrue(outTarget.isLoggable()); - verify(t, times(2)).printStackTrace(System.out); - } + verify(t, times(2)).printStackTrace(System.out); + } - @Test - public void testLogTargetSysErr() { - LogTarget errTarget = LogTarget.SYSERR; + @Test + public void testLogTargetSysErr() { + LogTarget errTarget = LogTarget.SYSERR; - errTarget.printf("format", new Date()); - errTarget.log("null", "null"); + errTarget.printf("format", new Date()); + errTarget.log("null", "null"); - errTarget.log(t); - errTarget.log(t, "First String Object"); + errTarget.log(t); + errTarget.log(t, "First String Object"); - assertTrue(errTarget.isLoggable()); + assertTrue(errTarget.isLoggable()); - verify(t, times(2)).printStackTrace(System.err); - } + verify(t, times(2)).printStackTrace(System.err); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_BasicEnvTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_BasicEnvTest.java index 65dc7c50..b15972ef 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_BasicEnvTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_BasicEnvTest.java @@ -40,141 +40,141 @@ import org.onap.aaf.misc.env.TimeTaken; public class JU_BasicEnvTest { - @Mock - Decryptor decrypt; + @Mock + Decryptor decrypt; - @Mock - Encryptor encrypt; + @Mock + Encryptor encrypt; - @Before - public void setup() { - decrypt = mock(Decryptor.class); - encrypt = mock(Encryptor.class); - } + @Before + public void setup() { + decrypt = mock(Decryptor.class); + encrypt = mock(Encryptor.class); + } - @Test - public void testLogTarget() { - Properties prop = new Properties(); - BasicEnv env = new BasicEnv(prop); + @Test + public void testLogTarget() { + Properties prop = new Properties(); + BasicEnv env = new BasicEnv(prop); - assertEquals(env.fatal(), LogTarget.SYSERR); - assertEquals(env.error(), LogTarget.SYSERR); - assertEquals(env.audit(), LogTarget.SYSOUT); - assertEquals(env.warn(), LogTarget.SYSERR); - assertEquals(env.init(), LogTarget.SYSOUT); - assertEquals(env.info(), LogTarget.SYSOUT); - assertEquals(env.debug(), LogTarget.NULL); - assertEquals(env.trace(), LogTarget.NULL); + assertEquals(env.fatal(), LogTarget.SYSERR); + assertEquals(env.error(), LogTarget.SYSERR); + assertEquals(env.audit(), LogTarget.SYSOUT); + assertEquals(env.warn(), LogTarget.SYSERR); + assertEquals(env.init(), LogTarget.SYSOUT); + assertEquals(env.info(), LogTarget.SYSOUT); + assertEquals(env.debug(), LogTarget.NULL); + assertEquals(env.trace(), LogTarget.NULL); - env.debug(LogTarget.SYSOUT); - assertEquals(env.debug(), LogTarget.SYSOUT); + env.debug(LogTarget.SYSOUT); + assertEquals(env.debug(), LogTarget.SYSOUT); - assertNull(env.getProperty("key")); - assertEquals("default", env.getProperty("key", "default")); + assertNull(env.getProperty("key")); + assertEquals("default", env.getProperty("key", "default")); - env.setProperty("key", "value"); - assertEquals("value", env.getProperty("key", "default")); + env.setProperty("key", "value"); + assertEquals("value", env.getProperty("key", "default")); - Properties filteredProperties = env.getProperties("key"); - assertEquals(filteredProperties.size(), 1); + Properties filteredProperties = env.getProperties("key"); + assertEquals(filteredProperties.size(), 1); - env.setProperty("key", null); - assertEquals("default", env.getProperty("key", "default")); + env.setProperty("key", null); + assertEquals("default", env.getProperty("key", "default")); - filteredProperties = env.getProperties("key1"); - assertEquals(filteredProperties.size(), 0); + filteredProperties = env.getProperties("key1"); + assertEquals(filteredProperties.size(), 0); - filteredProperties = env.getProperties(); - assertEquals(filteredProperties.size(), 0); + filteredProperties = env.getProperties(); + assertEquals(filteredProperties.size(), 0); - } + } - @Test - public void testBasicEnv() { - Applet applet = null; + @Test + public void testBasicEnv() { + Applet applet = null; - BasicEnv env = new BasicEnv(applet, "tag1", "tag2"); + BasicEnv env = new BasicEnv(applet, "tag1", "tag2"); - TimeTaken tt = env.start("Name", 2); + TimeTaken tt = env.start("Name", 2); - long end = tt.end(); - StringBuilder sb = new StringBuilder(); + long end = tt.end(); + StringBuilder sb = new StringBuilder(); - assertEquals(tt.toString(), "Name " + (end - tt.start) / 1000000f + "ms "); - tt.output(sb); - assertEquals(sb.toString(), "XML Name " + (end - tt.start) / 1000000f + "ms"); + assertEquals(tt.toString(), "Name " + (end - tt.start) / 1000000f + "ms "); + tt.output(sb); + assertEquals(sb.toString(), "XML Name " + (end - tt.start) / 1000000f + "ms"); - env.set(decrypt); - assertEquals(env.decryptor(), decrypt); - env.set(encrypt); - assertEquals(env.encryptor(), encrypt); - } + env.set(decrypt); + assertEquals(env.decryptor(), decrypt); + env.set(encrypt); + assertEquals(env.encryptor(), encrypt); + } - @Test - public void testBasicEnvDiffFlag() { - Properties prop = new Properties(); + @Test + public void testBasicEnvDiffFlag() { + Properties prop = new Properties(); - BasicEnv env = new BasicEnv("tag1", prop); + BasicEnv env = new BasicEnv("tag1", prop); - TimeTaken tt = env.start("Name", 1); + TimeTaken tt = env.start("Name", 1); - long end = tt.end(); - StringBuilder sb = new StringBuilder(); + long end = tt.end(); + StringBuilder sb = new StringBuilder(); - assertEquals(tt.toString(), "Name " + (end - tt.start) / 1000000f + "ms "); - tt.output(sb); - assertEquals(sb.toString(), "REMOTE Name " + (end - tt.start) / 1000000f + "ms"); + assertEquals(tt.toString(), "Name " + (end - tt.start) / 1000000f + "ms "); + tt.output(sb); + assertEquals(sb.toString(), "REMOTE Name " + (end - tt.start) / 1000000f + "ms"); - tt = env.start("New Name", 4); - tt.size(10); - sb = new StringBuilder(); - tt.output(sb); - assertEquals(tt.toString(), "New Name " + (end - tt.start) / 1000000f + "ms 10"); - assertEquals(sb.toString(), "JSON New Name " + (end - tt.start) / 1000000f + "ms size: 10"); + tt = env.start("New Name", 4); + tt.size(10); + sb = new StringBuilder(); + tt.output(sb); + assertEquals(tt.toString(), "New Name " + (end - tt.start) / 1000000f + "ms 10"); + assertEquals(sb.toString(), "JSON New Name " + (end - tt.start) / 1000000f + "ms size: 10"); - env.staticSlot("tag", "prop"); + env.staticSlot("tag", "prop"); - if (System.getProperties().keySet().iterator().hasNext()) { - String key = (String) System.getProperties().keySet().iterator().next(); + if (System.getProperties().keySet().iterator().hasNext()) { + String key = (String) System.getProperties().keySet().iterator().next(); - env.loadFromSystemPropsStartsWith(key); - assertEquals(env.getProperty(key), System.getProperties().get(key)); - } + env.loadFromSystemPropsStartsWith(key); + assertEquals(env.getProperty(key), System.getProperties().get(key)); + } - BasicTrans trans = env.newTrans(); - assertEquals(trans.delegate, env); + BasicTrans trans = env.newTrans(); + assertEquals(trans.delegate, env); - } + } - @Test - public void testLoadProperties() throws IOException { - Properties prop = new Properties(); + @Test + public void testLoadProperties() throws IOException { + Properties prop = new Properties(); - BasicEnv env = new BasicEnv("tag1", prop); + BasicEnv env = new BasicEnv("tag1", prop); - env.loadPropFiles("tag1", null); - env.setProperty("tag1", "propfile.properties"); - env.loadPropFiles("tag1", null); + env.loadPropFiles("tag1", null); + env.setProperty("tag1", "propfile.properties"); + env.loadPropFiles("tag1", null); - assertEquals(env.getProperty("prop1"), "New Property"); + assertEquals(env.getProperty("prop1"), "New Property"); - env.loadToSystemPropsStartsWith("prop1"); + env.loadToSystemPropsStartsWith("prop1"); - assertTrue(System.getProperties().keySet().contains("prop1")); - assertEquals(System.getProperties().get("prop1"), "New Property"); - } + assertTrue(System.getProperties().keySet().contains("prop1")); + assertEquals(System.getProperties().get("prop1"), "New Property"); + } - @After - public void tearDown() throws IOException { - /* - * File file = new File("./log-Append" + ending + "_0.log"); if (file.exists()) - * { Files.delete(Paths.get(file.getAbsolutePath())); } file = new - * File("./log-Append" + ending + "_1.log"); if (file.exists()) { - * Files.delete(Paths.get(file.getAbsolutePath())); } file = new File("./Append" - * + ending + "_0.log"); if (file.exists()) { - * Files.delete(Paths.get(file.getAbsolutePath())); } file = new File("./Append" - * + ending + "_1.log"); if (file.exists()) { - * Files.delete(Paths.get(file.getAbsolutePath())); } - */ - } + @After + public void tearDown() throws IOException { + /* + * File file = new File("./log-Append" + ending + "_0.log"); if (file.exists()) + * { Files.delete(Paths.get(file.getAbsolutePath())); } file = new + * File("./log-Append" + ending + "_1.log"); if (file.exists()) { + * Files.delete(Paths.get(file.getAbsolutePath())); } file = new File("./Append" + * + ending + "_0.log"); if (file.exists()) { + * Files.delete(Paths.get(file.getAbsolutePath())); } file = new File("./Append" + * + ending + "_1.log"); if (file.exists()) { + * Files.delete(Paths.get(file.getAbsolutePath())); } + */ + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_EnvFactoryTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_EnvFactoryTest.java index f6c6912d..e5d0ed52 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_EnvFactoryTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_EnvFactoryTest.java @@ -31,49 +31,49 @@ import org.onap.aaf.misc.env.TransJAXB; public class JU_EnvFactoryTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testSingleton() { - BasicEnv singleton = EnvFactory.singleton(); + @Test + public void testSingleton() { + BasicEnv singleton = EnvFactory.singleton(); - assertEquals(EnvFactory.singleton, singleton); - } + assertEquals(EnvFactory.singleton, singleton); + } - @Test - public void testSetSingleton() { - String[] str = { "argument1" }; - BasicEnv env = new BasicEnv("tag", str); - EnvFactory.setSingleton(env); + @Test + public void testSetSingleton() { + String[] str = { "argument1" }; + BasicEnv env = new BasicEnv("tag", str); + EnvFactory.setSingleton(env); - assertEquals(EnvFactory.singleton(), env); - } + assertEquals(EnvFactory.singleton(), env); + } - @Test - public void testNewTrans() { - TransJAXB newTrans = EnvFactory.newTrans(); + @Test + public void testNewTrans() { + TransJAXB newTrans = EnvFactory.newTrans(); - assertTrue(newTrans instanceof BasicTrans); - } + assertTrue(newTrans instanceof BasicTrans); + } - @Test - public void testNewTransEnvJAXB() { - EnvJAXB env = new BasicEnv(""); + @Test + public void testNewTransEnvJAXB() { + EnvJAXB env = new BasicEnv(""); - TransJAXB trans = EnvFactory.newTrans(env); + TransJAXB trans = EnvFactory.newTrans(env); - assertTrue(trans instanceof BasicTrans); - } + assertTrue(trans instanceof BasicTrans); + } - @Test - public void testTransCreator() { - TransCreate transCreator = EnvFactory.transCreator(); + @Test + public void testTransCreator() { + TransCreate transCreator = EnvFactory.transCreator(); - TransJAXB newTrans = transCreator.newTrans(); + TransJAXB newTrans = transCreator.newTrans(); - assertTrue(newTrans instanceof BasicTrans); - } + assertTrue(newTrans instanceof BasicTrans); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java index e3f54929..914a01b0 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java @@ -40,23 +40,23 @@ import org.powermock.modules.junit4.PowerMockRunner; @PrepareForTest({ Log4JLogTarget.class, Logger.class }) public class JU_Log4JLogTargetTest { - @Mock - Logger log; + @Mock + Logger log; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(Logger.class); - when(Logger.getLogger("Info")).thenReturn(log); - when(log.isEnabledFor(Level.DEBUG)).thenReturn(false); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(Logger.class); + when(Logger.getLogger("Info")).thenReturn(log); + when(log.isEnabledFor(Level.DEBUG)).thenReturn(false); + } - @Test - public void test() throws APIException { - Log4JLogTarget target = new Log4JLogTarget(null, Level.INFO); - Log4JLogTarget target1 = new Log4JLogTarget("Info", Level.DEBUG); + @Test + public void test() throws APIException { + Log4JLogTarget target = new Log4JLogTarget(null, Level.INFO); + Log4JLogTarget target1 = new Log4JLogTarget("Info", Level.DEBUG); - assertFalse(target1.isLoggable()); + assertFalse(target1.isLoggable()); - } + } } \ No newline at end of file diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDataTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDataTest.java index 80de9b7b..6780a6a8 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDataTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDataTest.java @@ -43,138 +43,138 @@ import org.onap.aaf.misc.env.old.Stringifier; public class JU_JAXBDataTest { - @Mock - private Objectifier objfr; + @Mock + private Objectifier objfr; - private String object = "Text"; + private String object = "Text"; - @Mock - private Stringifier strfr; + @Mock + private Stringifier strfr; - @Mock - private IOStringifier ioStrfr; + @Mock + private IOStringifier ioStrfr; - @Mock - private JAXBDF df; + @Mock + private JAXBDF df; - @Mock - private Env env; + @Mock + private Env env; - @Mock - private Class typeClass; + @Mock + private Class typeClass; - @Mock - private OutputStream os; + @Mock + private OutputStream os; - @Mock - private Writer writer; + @Mock + private Writer writer; - @Mock - private EnvJAXB env1; + @Mock + private EnvJAXB env1; - @Before - public void setUp() throws Exception { - writer = mock(Writer.class); - os = mock(OutputStream.class); - strfr = mock(Stringifier.class); - ioStrfr = mock(IOStringifier.class); - objfr = mock(Objectifier.class); - env1 = mock(EnvJAXB.class); - } + @Before + public void setUp() throws Exception { + writer = mock(Writer.class); + os = mock(OutputStream.class); + strfr = mock(Stringifier.class); + ioStrfr = mock(IOStringifier.class); + objfr = mock(Objectifier.class); + env1 = mock(EnvJAXB.class); + } - @Test - public void testJAXBDataEnv() throws APIException, IOException { - JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object, typeClass); + @Test + public void testJAXBDataEnv() throws APIException, IOException { + JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object, typeClass); - when(objfr.objectify(env, object)).thenReturn("String1"); + when(objfr.objectify(env, object)).thenReturn("String1"); - jaxb.to(os); - jaxb.to(writer); + jaxb.to(os); + jaxb.to(writer); - verify(writer).write(object); - verify(os).write(object.getBytes()); + verify(writer).write(object); + verify(os).write(object.getBytes()); - assertEquals(jaxb.asString(), object); - assertEquals(jaxb.asString(null), object); - assertEquals(jaxb.toString(), object); - assertEquals(jaxb.getTypeClass(), typeClass); - assertEquals(jaxb.out(null), jaxb); - assertEquals(jaxb.in(null), jaxb); - assertTrue(jaxb.getInputStream() instanceof ByteArrayInputStream); - assertEquals(jaxb.asObject(), "String1"); - assertEquals(jaxb.asObject(env1), "String1"); - assertEquals(jaxb.toString(), object); - } + assertEquals(jaxb.asString(), object); + assertEquals(jaxb.asString(null), object); + assertEquals(jaxb.toString(), object); + assertEquals(jaxb.getTypeClass(), typeClass); + assertEquals(jaxb.out(null), jaxb); + assertEquals(jaxb.in(null), jaxb); + assertTrue(jaxb.getInputStream() instanceof ByteArrayInputStream); + assertEquals(jaxb.asObject(), "String1"); + assertEquals(jaxb.asObject(env1), "String1"); + assertEquals(jaxb.toString(), object); + } - @Test - public void testJAXBDataEnvForObjectifier() throws APIException, IOException { - JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object, typeClass); + @Test + public void testJAXBDataEnvForObjectifier() throws APIException, IOException { + JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object, typeClass); - when(objfr.objectify(env1, object)).thenReturn("String1"); + when(objfr.objectify(env1, object)).thenReturn("String1"); - assertEquals(jaxb.asObject(env1), "String1"); - } + assertEquals(jaxb.asObject(env1), "String1"); + } - @Test - public void testJAXBDataEnvWithObject() throws APIException, IOException { - JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); + @Test + public void testJAXBDataEnvWithObject() throws APIException, IOException { + JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); - when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); + when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); - jaxb.to(os); + jaxb.to(os); - verify(os).write(object.getBytes()); + verify(os).write(object.getBytes()); - assertEquals(jaxb.asString(), object); - assertEquals(jaxb.asString(null), object); - assertEquals(jaxb.toString(), object); - } + assertEquals(jaxb.asString(), object); + assertEquals(jaxb.asString(null), object); + assertEquals(jaxb.toString(), object); + } - @Test - public void testJAXBDataEnvForWriter() throws APIException, IOException { - JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); + @Test + public void testJAXBDataEnvForWriter() throws APIException, IOException { + JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); - when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); + when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); - jaxb.to(writer); + jaxb.to(writer); - verify(writer).write(object); + verify(writer).write(object); - assertEquals(jaxb.asString(), object); - assertEquals(jaxb.asString(null), object); - assertEquals(jaxb.toString(), object); - assertEquals(jaxb.asObject(), object); - assertEquals(jaxb.asObject(null), object); - } + assertEquals(jaxb.asString(), object); + assertEquals(jaxb.asString(null), object); + assertEquals(jaxb.toString(), object); + assertEquals(jaxb.asObject(), object); + assertEquals(jaxb.asObject(null), object); + } - @Test - public void testAsStringWithNullString() throws APIException, IOException { - JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); + @Test + public void testAsStringWithNullString() throws APIException, IOException { + JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); - when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); + when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); - assertEquals(jaxb.asString(), object); - } + assertEquals(jaxb.asString(), object); + } - @Test - public void testAsStringWithNullStringWithEnv() throws APIException, IOException { - JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); + @Test + public void testAsStringWithNullStringWithEnv() throws APIException, IOException { + JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); - when(strfr.stringify(env1, object)).thenReturn(object); + when(strfr.stringify(env1, object)).thenReturn(object); - assertEquals(jaxb.asString(env1), object); - } + assertEquals(jaxb.asString(env1), object); + } - @Test - public void testToWithIOStrifier() throws APIException, IOException { - JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); + @Test + public void testToWithIOStrifier() throws APIException, IOException { + JAXBData jaxb = new JAXBData(env, df, strfr, objfr, object); - jaxb.option(0); + jaxb.option(0); - when(strfr.stringify(env1, object)).thenReturn(object); - when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); + when(strfr.stringify(env1, object)).thenReturn(object); + when(strfr.stringify(env, object, new boolean[] { false, false })).thenReturn(object); - assertTrue(jaxb.getInputStream() instanceof ByteArrayInputStream); - assertEquals(jaxb.asString(env1), object); - } + assertTrue(jaxb.getInputStream() instanceof ByteArrayInputStream); + assertEquals(jaxb.asString(env1), object); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_ChronoTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_ChronoTest.java index 05fd6fbf..c113c86e 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_ChronoTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_ChronoTest.java @@ -36,204 +36,204 @@ import org.junit.Test; public class JU_ChronoTest { - @Before - public void setUp() throws Exception { - } - - @Test - public void testFormatter8601() { - Chrono.Formatter8601 formatter = new Chrono.Formatter8601(); + @Before + public void setUp() throws Exception { + } + + @Test + public void testFormatter8601() { + Chrono.Formatter8601 formatter = new Chrono.Formatter8601(); - LogRecord record = new LogRecord(Level.WARNING, "Log Record to test log formating"); + LogRecord record = new LogRecord(Level.WARNING, "Log Record to test log formating"); - Date date = new Date(118, 02, 02); - long time = date.getTime(); + Date date = new Date(118, 02, 02); + long time = date.getTime(); - record.setMillis(time); + record.setMillis(time); - String expectedString = Chrono.dateFmt.format(date) + " " + record.getThreadID() + " " + record.getLevel() - + ": " + record.getMessage() + "\n"; - assertEquals(expectedString, formatter.format(record)); - } + String expectedString = Chrono.dateFmt.format(date) + " " + record.getThreadID() + " " + record.getLevel() + + ": " + record.getMessage() + "\n"; + assertEquals(expectedString, formatter.format(record)); + } - @Test - public void testTimeStampWithDate() { - Date date = Calendar.getInstance().getTime(); - XMLGregorianCalendar timeStamp = Chrono.timeStamp(date); + @Test + public void testTimeStampWithDate() { + Date date = Calendar.getInstance().getTime(); + XMLGregorianCalendar timeStamp = Chrono.timeStamp(date); - GregorianCalendar gc = new GregorianCalendar(); - gc.setTime(date); - XMLGregorianCalendar expectedCalendar = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(gc); + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(date); + XMLGregorianCalendar expectedCalendar = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(gc); - assertEquals(expectedCalendar, timeStamp); - } + assertEquals(expectedCalendar, timeStamp); + } - @Test - public void testUTCStamp() { - final Date date = Calendar.getInstance().getTime(); - String expectedUTCTime = Chrono.utcFmt.format(date); + @Test + public void testUTCStamp() { + final Date date = Calendar.getInstance().getTime(); + String expectedUTCTime = Chrono.utcFmt.format(date); - String stamp = Chrono.utcStamp(date); + String stamp = Chrono.utcStamp(date); - assertEquals(stamp, expectedUTCTime); + assertEquals(stamp, expectedUTCTime); - Date date1 = null; - assertEquals("", Chrono.utcStamp(date1)); + Date date1 = null; + assertEquals("", Chrono.utcStamp(date1)); - GregorianCalendar gc = null; - assertEquals(Chrono.utcStamp(gc), ""); - gc = new GregorianCalendar(); - gc.setTime(date); - assertEquals(Chrono.utcStamp(gc), expectedUTCTime); + GregorianCalendar gc = null; + assertEquals(Chrono.utcStamp(gc), ""); + gc = new GregorianCalendar(); + gc.setTime(date); + assertEquals(Chrono.utcStamp(gc), expectedUTCTime); - XMLGregorianCalendar xgc = null; - assertEquals(Chrono.utcStamp(xgc), ""); - xgc = Chrono.timeStamp(gc); - assertEquals(Chrono.utcStamp(xgc), expectedUTCTime); + XMLGregorianCalendar xgc = null; + assertEquals(Chrono.utcStamp(xgc), ""); + xgc = Chrono.timeStamp(gc); + assertEquals(Chrono.utcStamp(xgc), expectedUTCTime); - } + } - @Test - public void testDateStamp() { - final Date date = Calendar.getInstance().getTime(); - String expectedUTCTime = Chrono.dateFmt.format(date); + @Test + public void testDateStamp() { + final Date date = Calendar.getInstance().getTime(); + String expectedUTCTime = Chrono.dateFmt.format(date); - String stamp = Chrono.dateStamp(date); + String stamp = Chrono.dateStamp(date); - assertEquals(stamp, expectedUTCTime); + assertEquals(stamp, expectedUTCTime); - Date date1 = null; - assertEquals("", Chrono.dateStamp(date1)); + Date date1 = null; + assertEquals("", Chrono.dateStamp(date1)); - GregorianCalendar gc = null; - assertEquals(Chrono.dateStamp(gc), ""); - gc = new GregorianCalendar(); - gc.setTime(date); - assertEquals(Chrono.dateStamp(gc), expectedUTCTime); + GregorianCalendar gc = null; + assertEquals(Chrono.dateStamp(gc), ""); + gc = new GregorianCalendar(); + gc.setTime(date); + assertEquals(Chrono.dateStamp(gc), expectedUTCTime); - XMLGregorianCalendar xgc = null; - assertEquals(Chrono.dateStamp(xgc), ""); - xgc = Chrono.timeStamp(gc); - assertEquals(Chrono.dateStamp(xgc), expectedUTCTime); - } + XMLGregorianCalendar xgc = null; + assertEquals(Chrono.dateStamp(xgc), ""); + xgc = Chrono.timeStamp(gc); + assertEquals(Chrono.dateStamp(xgc), expectedUTCTime); + } - @Test - public void testDateTime() { - final Date date = Calendar.getInstance().getTime(); - date.setTime(1525023883297L); + @Test + public void testDateTime() { + final Date date = Calendar.getInstance().getTime(); + date.setTime(1525023883297L); - GregorianCalendar gc = null; - assertEquals(Chrono.dateTime(gc), ""); - gc = new GregorianCalendar(); - gc.setTime(date); + GregorianCalendar gc = null; + assertEquals(Chrono.dateTime(gc), ""); + gc = new GregorianCalendar(); + gc.setTime(date); - // String expectedDateTime = "2018-04-29T11:14:43.297" + sign + hourOffSet + ":" - // + minOffSet; + // String expectedDateTime = "2018-04-29T11:14:43.297" + sign + hourOffSet + ":" + // + minOffSet; - TimeZone tz = gc.getTimeZone(); - int tz1 = (tz.getRawOffset() + tz.getDSTSavings()) / 0x8CA0; - int tz1abs = Math.abs(tz1); - String expectedDateTime = String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d", - gc.get(GregorianCalendar.YEAR), gc.get(GregorianCalendar.MONTH) + 1, - gc.get(GregorianCalendar.DAY_OF_MONTH), gc.get(GregorianCalendar.HOUR), - gc.get(GregorianCalendar.MINUTE), gc.get(GregorianCalendar.SECOND), - gc.get(GregorianCalendar.MILLISECOND), tz1 == tz1abs ? '+' : '-', tz1abs / 100, - ((tz1abs - (tz1abs / 100) * 100) * 6) / 10 // Get the "10s", then convert to mins (without losing int - // place) - ); + TimeZone tz = gc.getTimeZone(); + int tz1 = (tz.getRawOffset() + tz.getDSTSavings()) / 0x8CA0; + int tz1abs = Math.abs(tz1); + String expectedDateTime = String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d", + gc.get(GregorianCalendar.YEAR), gc.get(GregorianCalendar.MONTH) + 1, + gc.get(GregorianCalendar.DAY_OF_MONTH), gc.get(GregorianCalendar.HOUR), + gc.get(GregorianCalendar.MINUTE), gc.get(GregorianCalendar.SECOND), + gc.get(GregorianCalendar.MILLISECOND), tz1 == tz1abs ? '+' : '-', tz1abs / 100, + ((tz1abs - (tz1abs / 100) * 100) * 6) / 10 // Get the "10s", then convert to mins (without losing int + // place) + ); - String stamp = Chrono.dateTime(date); + String stamp = Chrono.dateTime(date); - assertEquals(stamp, expectedDateTime); + assertEquals(stamp, expectedDateTime); - assertEquals(Chrono.dateTime(gc), expectedDateTime); + assertEquals(Chrono.dateTime(gc), expectedDateTime); - XMLGregorianCalendar xgc = null; - assertEquals(Chrono.dateTime(xgc), ""); - xgc = Chrono.timeStamp(gc); - assertEquals(Chrono.dateTime(xgc), expectedDateTime); - } + XMLGregorianCalendar xgc = null; + assertEquals(Chrono.dateTime(xgc), ""); + xgc = Chrono.timeStamp(gc); + assertEquals(Chrono.dateTime(xgc), expectedDateTime); + } - @Test - public void testDateOnlyStamp() { - final Date date = Calendar.getInstance().getTime(); - date.setTime(1525023883297L); + @Test + public void testDateOnlyStamp() { + final Date date = Calendar.getInstance().getTime(); + date.setTime(1525023883297L); - String expectedDateTime = Chrono.dateOnlyFmt.format(date); + String expectedDateTime = Chrono.dateOnlyFmt.format(date); - String stamp = Chrono.dateOnlyStamp(date); + String stamp = Chrono.dateOnlyStamp(date); - assertEquals(stamp, expectedDateTime); + assertEquals(stamp, expectedDateTime); - Date date1 = null; - assertEquals("", Chrono.dateOnlyStamp(date1)); + Date date1 = null; + assertEquals("", Chrono.dateOnlyStamp(date1)); - GregorianCalendar gc = null; - assertEquals(Chrono.dateOnlyStamp(gc), ""); - gc = new GregorianCalendar(); - gc.setTime(date); - assertEquals(Chrono.dateOnlyStamp(gc), expectedDateTime); + GregorianCalendar gc = null; + assertEquals(Chrono.dateOnlyStamp(gc), ""); + gc = new GregorianCalendar(); + gc.setTime(date); + assertEquals(Chrono.dateOnlyStamp(gc), expectedDateTime); - XMLGregorianCalendar xgc = null; - assertEquals(Chrono.dateOnlyStamp(xgc), ""); - xgc = Chrono.timeStamp(gc); - assertEquals(Chrono.dateOnlyStamp(xgc), expectedDateTime); - } + XMLGregorianCalendar xgc = null; + assertEquals(Chrono.dateOnlyStamp(xgc), ""); + xgc = Chrono.timeStamp(gc); + assertEquals(Chrono.dateOnlyStamp(xgc), expectedDateTime); + } - @Test - public void testNiceDateStamp() { - final Date date = Calendar.getInstance().getTime(); - date.setTime(1525023883297L); + @Test + public void testNiceDateStamp() { + final Date date = Calendar.getInstance().getTime(); + date.setTime(1525023883297L); - String expectedDateTime = Chrono.niceDateFmt.format(date); + String expectedDateTime = Chrono.niceDateFmt.format(date); - String stamp = Chrono.niceDateStamp(date); + String stamp = Chrono.niceDateStamp(date); - assertEquals(stamp, expectedDateTime); + assertEquals(stamp, expectedDateTime); - Date date1 = null; - assertEquals("", Chrono.niceDateStamp(date1)); + Date date1 = null; + assertEquals("", Chrono.niceDateStamp(date1)); - GregorianCalendar gc = null; - assertEquals(Chrono.niceDateStamp(gc), ""); - gc = new GregorianCalendar(); - gc.setTime(date); - assertEquals(Chrono.niceDateStamp(gc), expectedDateTime); + GregorianCalendar gc = null; + assertEquals(Chrono.niceDateStamp(gc), ""); + gc = new GregorianCalendar(); + gc.setTime(date); + assertEquals(Chrono.niceDateStamp(gc), expectedDateTime); - XMLGregorianCalendar xgc = null; - assertEquals(Chrono.niceDateStamp(xgc), ""); - xgc = Chrono.timeStamp(gc); - assertEquals(Chrono.niceDateStamp(xgc), expectedDateTime); - } - - @Test - public void testMoment() { - final Date date = Calendar.getInstance().getTime(); - date.setTime(1525023883297L); + XMLGregorianCalendar xgc = null; + assertEquals(Chrono.niceDateStamp(xgc), ""); + xgc = Chrono.timeStamp(gc); + assertEquals(Chrono.niceDateStamp(xgc), expectedDateTime); + } + + @Test + public void testMoment() { + final Date date = Calendar.getInstance().getTime(); + date.setTime(1525023883297L); - GregorianCalendar begin = new GregorianCalendar(); - begin.setTimeInMillis(date.getTime()); - begin.set(GregorianCalendar.HOUR, 0); - begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM); - begin.set(GregorianCalendar.MINUTE, 0); - begin.set(GregorianCalendar.SECOND, 0); - begin.set(GregorianCalendar.MILLISECOND, 0); + GregorianCalendar begin = new GregorianCalendar(); + begin.setTimeInMillis(date.getTime()); + begin.set(GregorianCalendar.HOUR, 0); + begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM); + begin.set(GregorianCalendar.MINUTE, 0); + begin.set(GregorianCalendar.SECOND, 0); + begin.set(GregorianCalendar.MILLISECOND, 0); - long firstMoment = begin.getTimeInMillis(); + long firstMoment = begin.getTimeInMillis(); - begin.set(GregorianCalendar.HOUR, 11); - begin.set(GregorianCalendar.MINUTE, 59); - begin.set(GregorianCalendar.SECOND, 59); - begin.set(GregorianCalendar.MILLISECOND, 999); - begin.set(GregorianCalendar.AM_PM, GregorianCalendar.PM); + begin.set(GregorianCalendar.HOUR, 11); + begin.set(GregorianCalendar.MINUTE, 59); + begin.set(GregorianCalendar.SECOND, 59); + begin.set(GregorianCalendar.MILLISECOND, 999); + begin.set(GregorianCalendar.AM_PM, GregorianCalendar.PM); - long lastMoment = begin.getTimeInMillis(); + long lastMoment = begin.getTimeInMillis(); - assertEquals(firstMoment, Chrono.firstMomentOfDay(date.getTime())); - assertEquals(lastMoment, Chrono.lastMomentOfDay(date.getTime())); + assertEquals(firstMoment, Chrono.firstMomentOfDay(date.getTime())); + assertEquals(lastMoment, Chrono.lastMomentOfDay(date.getTime())); - float timeInMillis = (lastMoment - firstMoment) / 1000000f; - assertEquals(timeInMillis, Chrono.millisFromNanos(firstMoment, lastMoment), 0); + float timeInMillis = (lastMoment - firstMoment) / 1000000f; + assertEquals(timeInMillis, Chrono.millisFromNanos(firstMoment, lastMoment), 0); - } + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_DoubleOutputStreamTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_DoubleOutputStreamTest.java index 4b8c9dce..3e6f5355 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_DoubleOutputStreamTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_DoubleOutputStreamTest.java @@ -34,71 +34,71 @@ import org.mockito.Mock; public class JU_DoubleOutputStreamTest { - @Mock - private OutputStream stream1; + @Mock + private OutputStream stream1; - @Mock - private OutputStream stream2; + @Mock + private OutputStream stream2; - private DoubleOutputStream doubleOutputStream; + private DoubleOutputStream doubleOutputStream; - @Before - public void setup() { - stream1 = mock(OutputStream.class); - stream2 = mock(OutputStream.class); - } + @Before + public void setup() { + stream1 = mock(OutputStream.class); + stream2 = mock(OutputStream.class); + } - @Test - public void testWriteInt() throws IOException { - doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); + @Test + public void testWriteInt() throws IOException { + doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); - doubleOutputStream.write(123); + doubleOutputStream.write(123); - verify(stream1, only()).write(123); - verify(stream2, only()).write(123); - } + verify(stream1, only()).write(123); + verify(stream2, only()).write(123); + } - @Test - public void testWriteByteArray() throws IOException { - doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); + @Test + public void testWriteByteArray() throws IOException { + doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); - byte[] bytes = { 1, 2, 3, 4 }; + byte[] bytes = { 1, 2, 3, 4 }; - doubleOutputStream.write(bytes); + doubleOutputStream.write(bytes); - verify(stream1, only()).write(bytes); - verify(stream2, only()).write(bytes); + verify(stream1, only()).write(bytes); + verify(stream2, only()).write(bytes); - } + } - @Test - public void testWriteByteArrayWithOffset() throws IOException { - doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); + @Test + public void testWriteByteArrayWithOffset() throws IOException { + doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); - byte[] bytes = { 1, 2, 3, 4 }; + byte[] bytes = { 1, 2, 3, 4 }; - doubleOutputStream.write(bytes, 1, 3); - verify(stream1, only()).write(bytes, 1, 3); - verify(stream2, only()).write(bytes, 1, 3); - } + doubleOutputStream.write(bytes, 1, 3); + verify(stream1, only()).write(bytes, 1, 3); + verify(stream2, only()).write(bytes, 1, 3); + } - @Test - public void testFlush() throws IOException { - doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); + @Test + public void testFlush() throws IOException { + doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, true); - doubleOutputStream.flush(); + doubleOutputStream.flush(); - verify(stream1, only()).flush(); - verify(stream2, only()).flush(); - } + verify(stream1, only()).flush(); + verify(stream2, only()).flush(); + } - @Test - public void testClose() throws IOException { - doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, false); + @Test + public void testClose() throws IOException { + doubleOutputStream = new DoubleOutputStream(stream1, true, stream2, false); - doubleOutputStream.close(); + doubleOutputStream.close(); - verify(stream1, only()).close(); - verify(stream2, never()).close(); - } + verify(stream1, only()).close(); + verify(stream2, never()).close(); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_IndentPrintWriterTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_IndentPrintWriterTest.java index b54026f1..a307b3f8 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_IndentPrintWriterTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_IndentPrintWriterTest.java @@ -35,79 +35,79 @@ import org.mockito.Mock; public class JU_IndentPrintWriterTest { - @Mock - private OutputStream stream; + @Mock + private OutputStream stream; - @Mock - private Writer writer; + @Mock + private Writer writer; - @Before - public void setUp() throws Exception { - stream = mock(OutputStream.class); - writer = mock(Writer.class); - } + @Before + public void setUp() throws Exception { + stream = mock(OutputStream.class); + writer = mock(Writer.class); + } - @Test - public void testWriteInt() throws IOException { - IndentPrintWriter indentWriter = new IndentPrintWriter(writer); + @Test + public void testWriteInt() throws IOException { + IndentPrintWriter indentWriter = new IndentPrintWriter(writer); - indentWriter.write(123); + indentWriter.write(123); - verify(writer).write(123); + verify(writer).write(123); - assertEquals(indentWriter.getIndent(), 0); - } + assertEquals(indentWriter.getIndent(), 0); + } - @Test - public void testWriteIntWithNewLineCharacter() throws IOException { - IndentPrintWriter indentWriter = new IndentPrintWriter(writer); + @Test + public void testWriteIntWithNewLineCharacter() throws IOException { + IndentPrintWriter indentWriter = new IndentPrintWriter(writer); - indentWriter.setIndent(12); + indentWriter.setIndent(12); - indentWriter.println(); + indentWriter.println(); - indentWriter.write("123", 1, 2); + indentWriter.write("123", 1, 2); - verify(writer).write('\n'); - verify(writer).write('2'); - verify(writer).write('3'); - assertEquals(indentWriter.getIndent(), 12); - } + verify(writer).write('\n'); + verify(writer).write('2'); + verify(writer).write('3'); + assertEquals(indentWriter.getIndent(), 12); + } - @Test - public void testWriteString() throws IOException { - IndentPrintWriter indentWriter = new IndentPrintWriter(writer); + @Test + public void testWriteString() throws IOException { + IndentPrintWriter indentWriter = new IndentPrintWriter(writer); - indentWriter.inc(); + indentWriter.inc(); - indentWriter.write("123"); + indentWriter.write("123"); - verify(writer).write('1'); - verify(writer).write('2'); - verify(writer).write('3'); - assertEquals(indentWriter.getIndent(), 1); - } + verify(writer).write('1'); + verify(writer).write('2'); + verify(writer).write('3'); + assertEquals(indentWriter.getIndent(), 1); + } - @Test - public void testSetIndent() throws IOException { - IndentPrintWriter indentWriter = new IndentPrintWriter(stream); + @Test + public void testSetIndent() throws IOException { + IndentPrintWriter indentWriter = new IndentPrintWriter(stream); - indentWriter.setIndent(12); - indentWriter.dec(); + indentWriter.setIndent(12); + indentWriter.dec(); - assertEquals(indentWriter.getIndent(), 11); - } + assertEquals(indentWriter.getIndent(), 11); + } - @Test - public void testToCol() throws IOException { - IndentPrintWriter indentWriter = new IndentPrintWriter(writer); + @Test + public void testToCol() throws IOException { + IndentPrintWriter indentWriter = new IndentPrintWriter(writer); - indentWriter.toCol(5); - char[] chars = { 'a', 'b', 'c' }; - indentWriter.write(chars, 1, 2); + indentWriter.toCol(5); + char[] chars = { 'a', 'b', 'c' }; + indentWriter.write(chars, 1, 2); - verify(writer, times(5)).write(' '); - verify(writer).write('c'); - verify(writer).write('b'); - } + verify(writer, times(5)).write(' '); + verify(writer).write('c'); + verify(writer).write('b'); + } } \ No newline at end of file diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_SplitTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_SplitTest.java index ce2245bf..f5b4aaa4 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_SplitTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_SplitTest.java @@ -27,30 +27,30 @@ import org.junit.Test; public class JU_SplitTest { - @Test - public void testSplit() { - String[] splits = Split.split('c', "character c to break string"); - - assertEquals(splits.length, 4); - assertEquals(splits[0], ""); - assertEquals(splits[1], "hara"); - assertEquals(splits[2], "ter "); - assertEquals(splits[3], " to break string"); - } - - @Test - public void testSplitTrim() { - String[] splits = Split.splitTrim('c', "character c to break string", 5); - - assertEquals(splits.length, 5); - assertEquals(splits[0], ""); - assertEquals(splits[1], "hara"); - assertEquals(splits[2], "ter"); - assertEquals(splits[3], "to break string"); - assertEquals(splits[4], null); - - splits = Split.splitTrim('c', " character ", 1); - assertEquals(splits.length, 1); - assertEquals(splits[0], "character"); - } + @Test + public void testSplit() { + String[] splits = Split.split('c', "character c to break string"); + + assertEquals(splits.length, 4); + assertEquals(splits[0], ""); + assertEquals(splits[1], "hara"); + assertEquals(splits[2], "ter "); + assertEquals(splits[3], " to break string"); + } + + @Test + public void testSplitTrim() { + String[] splits = Split.splitTrim('c', "character c to break string", 5); + + assertEquals(splits.length, 5); + assertEquals(splits[0], ""); + assertEquals(splits[1], "hara"); + assertEquals(splits[2], "ter"); + assertEquals(splits[3], "to break string"); + assertEquals(splits[4], null); + + splits = Split.splitTrim('c', " character ", 1); + assertEquals(splits.length, 1); + assertEquals(splits[0], "character"); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderOutputStreamTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderOutputStreamTest.java index 377a2891..b55e2545 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderOutputStreamTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderOutputStreamTest.java @@ -31,105 +31,105 @@ import org.junit.Test; public class JU_StringBuilderOutputStreamTest { - StringBuilderOutputStream streamBuilder; - - StringBuilder builder = new StringBuilder(); - - @Before - public void setUp() throws Exception { - streamBuilder = new StringBuilderOutputStream(builder); - } - - @Test - public void testWriteIntAndReset() { - streamBuilder.write(123); - - assertEquals("123", streamBuilder.toString()); - streamBuilder.reset(); - assertEquals("", streamBuilder.toString()); - } - - @Test - public void testWriteByteArrayWithoutException() throws IOException { - byte[] bytes = { 1, 2, 3, 4 }; - streamBuilder.write(bytes); - assertEquals(4, streamBuilder.getBuffer().length()); - - streamBuilder.write(bytes, 1, 2); - assertEquals(6, streamBuilder.getBuffer().length()); - - streamBuilder.write(bytes, 1, 0); - assertEquals(6, streamBuilder.getBuffer().length()); - - streamBuilder.append(bytes[0]); - assertEquals(7, streamBuilder.getBuffer().length()); - } - - @Test - public void testWriteByteArrayWithIndexOutOfBoundException() { - byte[] bytes = { 1, 2, 3, 4 }; - - try { - streamBuilder.write(bytes, -1, 2); - fail("This is supposed to throw IndexOutOfBounds Excetpion"); - } catch (IndexOutOfBoundsException e) { - } catch (Exception e) { - fail("This should throw only IndexOutOfBounds Exception"); - } - assertEquals(0, streamBuilder.getBuffer().length()); - - } - - @Test - public void testDefaultConstructor() throws IOException { - StringBuilderOutputStream stream = new StringBuilderOutputStream(); - - assertNotNull(stream.getBuffer()); - stream.close(); - } - - @Test - public void testConstructorWithPositiveDefaultCapacity() throws IOException { - StringBuilderOutputStream stream = new StringBuilderOutputStream(10); - - assertNotNull(stream.getBuffer()); - assertEquals(10, stream.getBuffer().capacity()); - stream.close(); - } - - @Test - public void testConstructorWithNegativeCapacityException() { - try { - StringBuilderOutputStream stream = new StringBuilderOutputStream(-1); - fail("This should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } catch (Exception e) { - fail("This should throw only IllegalArgumentException"); - } - } - - @Test - public void testWriteString() { - streamBuilder.write("1234"); - - assertEquals("1234", streamBuilder.toString()); - - streamBuilder.write("1234", 1, 2); - assertEquals("12342", streamBuilder.toString()); - } - - @Test - public void testAppendCharSequence() { - streamBuilder.append("1234"); - assertEquals("1234", streamBuilder.toString()); - - streamBuilder.append(null); - assertEquals("1234null", streamBuilder.toString()); - - streamBuilder.append("1234", 1, 2); - assertEquals("1234null2", streamBuilder.toString()); - - streamBuilder.append(null, 1, 2); - assertEquals("1234null2u", streamBuilder.toString()); - } + StringBuilderOutputStream streamBuilder; + + StringBuilder builder = new StringBuilder(); + + @Before + public void setUp() throws Exception { + streamBuilder = new StringBuilderOutputStream(builder); + } + + @Test + public void testWriteIntAndReset() { + streamBuilder.write(123); + + assertEquals("123", streamBuilder.toString()); + streamBuilder.reset(); + assertEquals("", streamBuilder.toString()); + } + + @Test + public void testWriteByteArrayWithoutException() throws IOException { + byte[] bytes = { 1, 2, 3, 4 }; + streamBuilder.write(bytes); + assertEquals(4, streamBuilder.getBuffer().length()); + + streamBuilder.write(bytes, 1, 2); + assertEquals(6, streamBuilder.getBuffer().length()); + + streamBuilder.write(bytes, 1, 0); + assertEquals(6, streamBuilder.getBuffer().length()); + + streamBuilder.append(bytes[0]); + assertEquals(7, streamBuilder.getBuffer().length()); + } + + @Test + public void testWriteByteArrayWithIndexOutOfBoundException() { + byte[] bytes = { 1, 2, 3, 4 }; + + try { + streamBuilder.write(bytes, -1, 2); + fail("This is supposed to throw IndexOutOfBounds Excetpion"); + } catch (IndexOutOfBoundsException e) { + } catch (Exception e) { + fail("This should throw only IndexOutOfBounds Exception"); + } + assertEquals(0, streamBuilder.getBuffer().length()); + + } + + @Test + public void testDefaultConstructor() throws IOException { + StringBuilderOutputStream stream = new StringBuilderOutputStream(); + + assertNotNull(stream.getBuffer()); + stream.close(); + } + + @Test + public void testConstructorWithPositiveDefaultCapacity() throws IOException { + StringBuilderOutputStream stream = new StringBuilderOutputStream(10); + + assertNotNull(stream.getBuffer()); + assertEquals(10, stream.getBuffer().capacity()); + stream.close(); + } + + @Test + public void testConstructorWithNegativeCapacityException() { + try { + StringBuilderOutputStream stream = new StringBuilderOutputStream(-1); + fail("This should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } catch (Exception e) { + fail("This should throw only IllegalArgumentException"); + } + } + + @Test + public void testWriteString() { + streamBuilder.write("1234"); + + assertEquals("1234", streamBuilder.toString()); + + streamBuilder.write("1234", 1, 2); + assertEquals("12342", streamBuilder.toString()); + } + + @Test + public void testAppendCharSequence() { + streamBuilder.append("1234"); + assertEquals("1234", streamBuilder.toString()); + + streamBuilder.append(null); + assertEquals("1234null", streamBuilder.toString()); + + streamBuilder.append("1234", 1, 2); + assertEquals("1234null2", streamBuilder.toString()); + + streamBuilder.append(null, 1, 2); + assertEquals("1234null2u", streamBuilder.toString()); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderWriterTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderWriterTest.java index 6a06e866..9247d0c9 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderWriterTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/JU_StringBuilderWriterTest.java @@ -31,105 +31,105 @@ import org.junit.Test; public class JU_StringBuilderWriterTest { - StringBuilderWriter streamWriter; - - StringBuilder builder = new StringBuilder(); - - @Before - public void setUp() throws Exception { - streamWriter = new StringBuilderWriter(builder); - } - - @Test - public void testWriteIntAndReset() { - streamWriter.write(1); - - assertEquals(1, streamWriter.getBuffer().length()); - streamWriter.reset(); - assertEquals("", streamWriter.toString()); - } - - @Test - public void testWriteByteArrayWithoutException() throws IOException { - char[] bytes = { 1, 2, 3, 4 }; - streamWriter.write(bytes); - assertEquals(4, streamWriter.getBuffer().length()); - - streamWriter.write(bytes, 1, 2); - assertEquals(6, streamWriter.getBuffer().length()); - - streamWriter.write(bytes, 1, 0); - assertEquals(6, streamWriter.getBuffer().length()); - - streamWriter.append(bytes[0]); - assertEquals(7, streamWriter.getBuffer().length()); - } - - @Test - public void testWriteByteArrayWithIndexOutOfBoundException() { - char[] bytes = { 1, 2, 3, 4 }; - - try { - streamWriter.write(bytes, -1, 2); - fail("This is supposed to throw IndexOutOfBounds Excetpion"); - } catch (IndexOutOfBoundsException e) { - } catch (Exception e) { - fail("This should throw only IndexOutOfBounds Exception"); - } - assertEquals(0, streamWriter.getBuffer().length()); - - } - - @Test - public void testDefaultConstructor() throws IOException { - StringBuilderWriter stream = new StringBuilderWriter(); - - assertNotNull(stream.getBuffer()); - stream.close(); - } - - @Test - public void testConstructorWithPositiveDefaultCapacity() throws IOException { - StringBuilderWriter stream = new StringBuilderWriter(10); - - assertNotNull(stream.getBuffer()); - assertEquals(10, stream.getBuffer().capacity()); - stream.close(); - } - - @Test - public void testConstructorWithNegativeCapacityException() { - try { - StringBuilderWriter stream = new StringBuilderWriter(-1); - fail("This should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } catch (Exception e) { - fail("This should throw only IllegalArgumentException"); - } - } - - @Test - public void testWriteString() { - streamWriter.write("1234"); - - assertEquals("1234", streamWriter.toString()); - - streamWriter.write("1234", 1, 2); - assertEquals("123423", streamWriter.toString()); - } - - @Test - public void testAppendCharSequence() { - streamWriter.append("1234"); - assertEquals("1234", streamWriter.toString()); - - streamWriter.append(null); - assertEquals("1234null", streamWriter.toString()); - - streamWriter.append("1234", 1, 2); - assertEquals("1234null2", streamWriter.toString()); - - streamWriter.append(null, 1, 2); - assertEquals("1234null2u", streamWriter.toString()); - } + StringBuilderWriter streamWriter; + + StringBuilder builder = new StringBuilder(); + + @Before + public void setUp() throws Exception { + streamWriter = new StringBuilderWriter(builder); + } + + @Test + public void testWriteIntAndReset() { + streamWriter.write(1); + + assertEquals(1, streamWriter.getBuffer().length()); + streamWriter.reset(); + assertEquals("", streamWriter.toString()); + } + + @Test + public void testWriteByteArrayWithoutException() throws IOException { + char[] bytes = { 1, 2, 3, 4 }; + streamWriter.write(bytes); + assertEquals(4, streamWriter.getBuffer().length()); + + streamWriter.write(bytes, 1, 2); + assertEquals(6, streamWriter.getBuffer().length()); + + streamWriter.write(bytes, 1, 0); + assertEquals(6, streamWriter.getBuffer().length()); + + streamWriter.append(bytes[0]); + assertEquals(7, streamWriter.getBuffer().length()); + } + + @Test + public void testWriteByteArrayWithIndexOutOfBoundException() { + char[] bytes = { 1, 2, 3, 4 }; + + try { + streamWriter.write(bytes, -1, 2); + fail("This is supposed to throw IndexOutOfBounds Excetpion"); + } catch (IndexOutOfBoundsException e) { + } catch (Exception e) { + fail("This should throw only IndexOutOfBounds Exception"); + } + assertEquals(0, streamWriter.getBuffer().length()); + + } + + @Test + public void testDefaultConstructor() throws IOException { + StringBuilderWriter stream = new StringBuilderWriter(); + + assertNotNull(stream.getBuffer()); + stream.close(); + } + + @Test + public void testConstructorWithPositiveDefaultCapacity() throws IOException { + StringBuilderWriter stream = new StringBuilderWriter(10); + + assertNotNull(stream.getBuffer()); + assertEquals(10, stream.getBuffer().capacity()); + stream.close(); + } + + @Test + public void testConstructorWithNegativeCapacityException() { + try { + StringBuilderWriter stream = new StringBuilderWriter(-1); + fail("This should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } catch (Exception e) { + fail("This should throw only IllegalArgumentException"); + } + } + + @Test + public void testWriteString() { + streamWriter.write("1234"); + + assertEquals("1234", streamWriter.toString()); + + streamWriter.write("1234", 1, 2); + assertEquals("123423", streamWriter.toString()); + } + + @Test + public void testAppendCharSequence() { + streamWriter.append("1234"); + assertEquals("1234", streamWriter.toString()); + + streamWriter.append(null); + assertEquals("1234null", streamWriter.toString()); + + streamWriter.append("1234", 1, 2); + assertEquals("1234null2", streamWriter.toString()); + + streamWriter.append(null, 1, 2); + assertEquals("1234null2u", streamWriter.toString()); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_IPValidator.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_IPValidator.java index 3976718f..0ce3a84e 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_IPValidator.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_IPValidator.java @@ -29,39 +29,39 @@ import org.onap.aaf.misc.env.util.IPValidator; public class JU_IPValidator { - @Test - public void test() { - assertTrue(IPValidator.ipv4("10.10.10.10")); - assertTrue(IPValidator.ipv4("127.0.0.0")); - assertFalse(IPValidator.ipv4("10")); - assertFalse(IPValidator.ipv4("10.10.10")); - assertFalse(IPValidator.ipv4("10.10.10.")); - assertFalse(IPValidator.ipv4("10.10.10.10.")); - assertFalse(IPValidator.ipv4("10.10.10.10.10")); - assertFalse(IPValidator.ipv4("something10.10.10.10")); - assertTrue(IPValidator.ipv4("0.10.10.10")); - assertTrue(IPValidator.ipv4("0.0.0.0")); - assertTrue(IPValidator.ipv4("0.10.10.10")); - assertFalse(IPValidator.ipv4("011.255.255.255")); - assertFalse(IPValidator.ipv4("255.01.255.255")); - assertFalse(IPValidator.ipv4("255.255.255.256")); - assertFalse(IPValidator.ipv4("255.299.255.255")); + @Test + public void test() { + assertTrue(IPValidator.ipv4("10.10.10.10")); + assertTrue(IPValidator.ipv4("127.0.0.0")); + assertFalse(IPValidator.ipv4("10")); + assertFalse(IPValidator.ipv4("10.10.10")); + assertFalse(IPValidator.ipv4("10.10.10.")); + assertFalse(IPValidator.ipv4("10.10.10.10.")); + assertFalse(IPValidator.ipv4("10.10.10.10.10")); + assertFalse(IPValidator.ipv4("something10.10.10.10")); + assertTrue(IPValidator.ipv4("0.10.10.10")); + assertTrue(IPValidator.ipv4("0.0.0.0")); + assertTrue(IPValidator.ipv4("0.10.10.10")); + assertFalse(IPValidator.ipv4("011.255.255.255")); + assertFalse(IPValidator.ipv4("255.01.255.255")); + assertFalse(IPValidator.ipv4("255.255.255.256")); + assertFalse(IPValidator.ipv4("255.299.255.255")); - assertTrue(IPValidator.ipv6("0000:0000:0000:0000:0000:0000:0000:0000")); - assertTrue(IPValidator.ipv6("0:0:0:0:0:0:0:0")); - assertTrue(IPValidator.ipv6("2001:08DB:0000:0000:0023:F422:FE3B:AC10")); - assertTrue(IPValidator.ipv6("2001:8DB:0:0:23:F422:FE3B:AC10")); - assertTrue(IPValidator.ipv6("2001:8DB::23:F422:FE3B:AC10")); - assertTrue(IPValidator.ipv6("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); - assertTrue(IPValidator.ipv6("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF")); - assertFalse(IPValidator.ipv6("2001:8DB::23:G422:FE3B:AC10")); - assertFalse(IPValidator.ipv6("2001:8DB::23:G422:FE3B:AC10")); - // more than one Double Colons - assertFalse(IPValidator.ipv6("0000:0000:0000::0000::0000")); - assertFalse(IPValidator.ipv6("2001:8DB::23:G422:FE3B:AC10:FFFF")); + assertTrue(IPValidator.ipv6("0000:0000:0000:0000:0000:0000:0000:0000")); + assertTrue(IPValidator.ipv6("0:0:0:0:0:0:0:0")); + assertTrue(IPValidator.ipv6("2001:08DB:0000:0000:0023:F422:FE3B:AC10")); + assertTrue(IPValidator.ipv6("2001:8DB:0:0:23:F422:FE3B:AC10")); + assertTrue(IPValidator.ipv6("2001:8DB::23:F422:FE3B:AC10")); + assertTrue(IPValidator.ipv6("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); + assertTrue(IPValidator.ipv6("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF")); + assertFalse(IPValidator.ipv6("2001:8DB::23:G422:FE3B:AC10")); + assertFalse(IPValidator.ipv6("2001:8DB::23:G422:FE3B:AC10")); + // more than one Double Colons + assertFalse(IPValidator.ipv6("0000:0000:0000::0000::0000")); + assertFalse(IPValidator.ipv6("2001:8DB::23:G422:FE3B:AC10:FFFF")); - assertTrue(IPValidator.ip("2001:08DB:0000:0000:0023:F422:FE3B:AC10")); - assertTrue(IPValidator.ip("192.168.7.2")); - } + assertTrue(IPValidator.ip("2001:08DB:0000:0000:0023:F422:FE3B:AC10")); + assertTrue(IPValidator.ip("192.168.7.2")); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_PoolTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_PoolTest.java index 11f03d52..32e4080b 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_PoolTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/util/test/JU_PoolTest.java @@ -30,57 +30,57 @@ import org.onap.aaf.misc.env.util.Pool; public class JU_PoolTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void test() { - Pool pool = new Pool(new Pool.Creator() { + @Test + public void test() { + Pool pool = new Pool(new Pool.Creator() { - Integer content = 0; + Integer content = 0; - @Override - public Integer create() throws APIException { - return content++; - } + @Override + public Integer create() throws APIException { + return content++; + } - @Override - public void destroy(Integer t) { + @Override + public void destroy(Integer t) { - } + } - @Override - public boolean isValid(Integer t) { - return t == content; - } + @Override + public boolean isValid(Integer t) { + return t == content; + } - @Override - public void reuse(Integer t) { - content = t; - } - }); - Pool.Pooled pooled = new Pool.Pooled(new Integer(123), pool, LogTarget.SYSOUT); - Pool.Pooled pooled1 = new Pool.Pooled(new Integer(123), null, LogTarget.SYSOUT); - try { - // pool.drain(); - assertEquals("Should return intial value", 0, pool.get().content); - // pooled.toss(); - pool.prime(LogTarget.SYSOUT, 23); - assertEquals("Should Return 23 as added at last prime", 23, pool.get(LogTarget.SYSOUT).content); - pool.prime(LogTarget.SYSERR, 13); - assertEquals("Should add another 13 from SysErr and remove 1", 35, pool.get(LogTarget.SYSERR).content); - assertEquals("Create a new creator with create method", 1, pool.get().content); - assertEquals("Create a new creator with create method", 2, pool.get().content); - assertEquals("Should remove last from pool", 34, pool.get(LogTarget.SYSOUT).content); + @Override + public void reuse(Integer t) { + content = t; + } + }); + Pool.Pooled pooled = new Pool.Pooled(new Integer(123), pool, LogTarget.SYSOUT); + Pool.Pooled pooled1 = new Pool.Pooled(new Integer(123), null, LogTarget.SYSOUT); + try { + // pool.drain(); + assertEquals("Should return intial value", 0, pool.get().content); + // pooled.toss(); + pool.prime(LogTarget.SYSOUT, 23); + assertEquals("Should Return 23 as added at last prime", 23, pool.get(LogTarget.SYSOUT).content); + pool.prime(LogTarget.SYSERR, 13); + assertEquals("Should add another 13 from SysErr and remove 1", 35, pool.get(LogTarget.SYSERR).content); + assertEquals("Create a new creator with create method", 1, pool.get().content); + assertEquals("Create a new creator with create method", 2, pool.get().content); + assertEquals("Should remove last from pool", 34, pool.get(LogTarget.SYSOUT).content); - pool.drain(); - assertEquals("Should remove last from pool", 17, pool.get(LogTarget.SYSOUT).content); - pool.setMaxRange(10); - assertEquals(10, pool.getMaxRange()); - pooled.toss(); - pooled1.toss(); - } catch (APIException e) { - } - } + pool.drain(); + assertEquals("Should remove last from pool", 17, pool.get(LogTarget.SYSOUT).content); + pool.setMaxRange(10); + assertEquals(10, pool.getMaxRange()); + pooled.toss(); + pooled1.toss(); + } catch (APIException e) { + } + } } diff --git a/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java b/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java index c6537deb..e118baaa 100644 --- a/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java +++ b/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java @@ -27,61 +27,61 @@ import java.text.SimpleDateFormat; import java.util.Date; public class LogFileNamer { - private final String root; - private final String ending; - private final String dir; + private final String root; + private final String ending; + private final String dir; - public LogFileNamer(final String dir, final String root) { - this.dir = dir; - if (root == null || "".equals(root) || root.endsWith("/")) { - this.root = root; - } else { - this.root = root + "-"; - } - ending = new SimpleDateFormat("YYYYMMdd").format(new Date()); - } + public LogFileNamer(final String dir, final String root) { + this.dir = dir; + if (root == null || "".equals(root) || root.endsWith("/")) { + this.root = root; + } else { + this.root = root + "-"; + } + ending = new SimpleDateFormat("YYYYMMdd").format(new Date()); + } - public LogFileNamer noPID() { - return this; - } + public LogFileNamer noPID() { + return this; + } - private static final String FILE_FORMAT_STR = "%s/%s%s%s_%d.log"; + private static final String FILE_FORMAT_STR = "%s/%s%s%s_%d.log"; - /** - * Accepts a String. If Separated by "|" then first part is the Appender name, - * and the second is used in the FileNaming (This is to allow for shortened - * Logger names, and more verbose file names) ONAP: jna code has license issues. - * Just do Date + Unique Number - * - * @param appender - * - * returns the String Appender - * @throws IOException - */ - public String setAppender(String appender) throws IOException { - int i = 0; - File f; - while ((f = new File(String.format(FILE_FORMAT_STR, dir, root, appender, ending, i))).exists()) { - ++i; - } - - f.createNewFile(); - System.setProperty("LOG4J_FILENAME_" + appender, f.getCanonicalPath()); - return appender; - } + /** + * Accepts a String. If Separated by "|" then first part is the Appender name, + * and the second is used in the FileNaming (This is to allow for shortened + * Logger names, and more verbose file names) ONAP: jna code has license issues. + * Just do Date + Unique Number + * + * @param appender + * + * returns the String Appender + * @throws IOException + */ + public String setAppender(String appender) throws IOException { + int i = 0; + File f; + while ((f = new File(String.format(FILE_FORMAT_STR, dir, root, appender, ending, i))).exists()) { + ++i; + } + + f.createNewFile(); + System.setProperty("LOG4J_FILENAME_" + appender, f.getCanonicalPath()); + return appender; + } - public void configure(final String path, final String fname, final String log_level) throws IOException { - final String fullPath = path + '/' + fname; - if (new File(fullPath).exists()) { - org.apache.log4j.PropertyConfigurator.configureAndWatch(fullPath, 60 * 1000L); - } else { - URL rsrc = ClassLoader.getSystemResource(fname); - if (rsrc == null) { - String msg = "Neither File: " + path + '/' + fname + " nor resource on Classpath " + fname + " exist"; - throw new IOException(msg); - } - org.apache.log4j.PropertyConfigurator.configure(rsrc); - } + public void configure(final String path, final String fname, final String log_level) throws IOException { + final String fullPath = path + '/' + fname; + if (new File(fullPath).exists()) { + org.apache.log4j.PropertyConfigurator.configureAndWatch(fullPath, 60 * 1000L); + } else { + URL rsrc = ClassLoader.getSystemResource(fname); + if (rsrc == null) { + String msg = "Neither File: " + path + '/' + fname + " nor resource on Classpath " + fname + " exist"; + throw new IOException(msg); + } + org.apache.log4j.PropertyConfigurator.configure(rsrc); + } - } + } } diff --git a/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java b/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java index 8c47a409..720ed27f 100644 --- a/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java +++ b/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java @@ -34,60 +34,60 @@ import org.junit.Before; import org.junit.Test; public class JU_LogFileNamerTest { - private File dir = new File("."); + private File dir = new File("."); - private String ending = new SimpleDateFormat("YYYYMMdd").format(new Date()); + private String ending = new SimpleDateFormat("YYYYMMdd").format(new Date()); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void test() throws IOException { - LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), "log"); - assertEquals(logFileNamer, logFileNamer.noPID()); + @Test + public void test() throws IOException { + LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), "log"); + assertEquals(logFileNamer, logFileNamer.noPID()); - logFileNamer.setAppender("Append"); - assertEquals(System.getProperty("LOG4J_FILENAME_Append"), - dir.getCanonicalFile() + File.separator + "log-Append" + ending + "_0.log"); + logFileNamer.setAppender("Append"); + assertEquals(System.getProperty("LOG4J_FILENAME_Append"), + dir.getCanonicalFile() + File.separator + "log-Append" + ending + "_0.log"); - logFileNamer.setAppender("Append"); - assertEquals(System.getProperty("LOG4J_FILENAME_Append"), - dir.getCanonicalFile() + File.separator + "log-Append" + ending + "_1.log"); - } + logFileNamer.setAppender("Append"); + assertEquals(System.getProperty("LOG4J_FILENAME_Append"), + dir.getCanonicalFile() + File.separator + "log-Append" + ending + "_1.log"); + } - @Test - public void testBlankRoot() throws IOException { - LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), ""); - assertEquals(logFileNamer, logFileNamer.noPID()); + @Test + public void testBlankRoot() throws IOException { + LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), ""); + assertEquals(logFileNamer, logFileNamer.noPID()); - logFileNamer.setAppender("Append"); - assertEquals(System.getProperty("LOG4J_FILENAME_Append"), - dir.getCanonicalPath() + File.separator + "Append" + ending + "_0.log"); + logFileNamer.setAppender("Append"); + assertEquals(System.getProperty("LOG4J_FILENAME_Append"), + dir.getCanonicalPath() + File.separator + "Append" + ending + "_0.log"); - logFileNamer.setAppender("Append"); - assertEquals(System.getProperty("LOG4J_FILENAME_Append"), - dir.getCanonicalPath() + File.separator + "Append" + ending + "_1.log"); - } + logFileNamer.setAppender("Append"); + assertEquals(System.getProperty("LOG4J_FILENAME_Append"), + dir.getCanonicalPath() + File.separator + "Append" + ending + "_1.log"); + } - @After - public void tearDown() throws IOException { - File file = new File("./log-Append" + ending + "_0.log"); - if (file.exists()) { - Files.delete(Paths.get(file.getAbsolutePath())); - } - file = new File("./log-Append" + ending + "_1.log"); - if (file.exists()) { - Files.delete(Paths.get(file.getAbsolutePath())); - } - file = new File("./Append" + ending + "_0.log"); - if (file.exists()) { - Files.delete(Paths.get(file.getAbsolutePath())); - } - file = new File("./Append" + ending + "_1.log"); - if (file.exists()) { - Files.delete(Paths.get(file.getAbsolutePath())); - } - } + @After + public void tearDown() throws IOException { + File file = new File("./log-Append" + ending + "_0.log"); + if (file.exists()) { + Files.delete(Paths.get(file.getAbsolutePath())); + } + file = new File("./log-Append" + ending + "_1.log"); + if (file.exists()) { + Files.delete(Paths.get(file.getAbsolutePath())); + } + file = new File("./Append" + ending + "_0.log"); + if (file.exists()) { + Files.delete(Paths.get(file.getAbsolutePath())); + } + file = new File("./Append" + ending + "_1.log"); + if (file.exists()) { + Files.delete(Paths.get(file.getAbsolutePath())); + } + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java index 725389c9..353261a0 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java @@ -29,126 +29,126 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.rosetta.InJson.State; public class InJson implements Parse { - public Parsed parse(Reader r, Parsed parsed) throws ParseException { - // First things first, if there's a "leftover" event, process that immediately - State state = (State)parsed.state; - if(state.unsent > 0) { - parsed.event = state.unsent; - state.unsent = 0; - return parsed; - } - - int ch; - char c; - StringBuilder sb = parsed.sb; - boolean inQuotes = false, escaped = false; - boolean go = true; - try { - // Gather data from Reader, looking for special characters when not in Quotes - while(go && (ch=r.read())>=0) { - if(state.braces>=0 || ch==Parse.START_OBJ) { // ignore garbage/whitespace before content - c=(char)ch; - // Character is a quote. - if(c=='"') { - if(inQuotes) { - if(escaped) { // if escaped Quote, add to data. - sb.append(c); - escaped = false; - } else { - inQuotes = false; - } - } else { - parsed.isString=true; - inQuotes = true; - } - } else { // Not a Quote - if(inQuotes) { - if(c=='\\') { - if(escaped) { - sb.append("\\\\"); - escaped = false; - } else { - escaped = true; - } - } else { - sb.append(c); - } - } else { - switch(c) { - case ':': - parsed.dataIsName(); - parsed.isString = false; - break; - case Parse.START_OBJ: - if(state.braces++ == 0) { - parsed.event = START_DOC; - state.unsent = c; - } else { - parsed.event = c; - } - go = false; - break; - case Parse.END_OBJ: - if(--state.braces == 0) { - parsed.event = c; - state.unsent = END_DOC; - } else { - parsed.event = c; - } - go = false; - break; - // These three end the data gathering, and send it along with the event that is ending the data gathering - case Parse.NEXT: - if(parsed.name.startsWith("__")) { - parsed.event = Parse.ATTRIB; - parsed.name = parsed.name.substring(2); - } else { - parsed.event = c; - } - go = false; - break; - case Parse.START_ARRAY: - case Parse.END_ARRAY: - parsed.event = c; - go = false; - break; - - // The Escape Sequence, for Quote marks within Quotes - case '\\': - // Ignore these, unless within quotes, at which point data-gather - case ' ': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - break; - // Normal data... gather it - default: - sb.append(c); - } - } - } - } - } - return parsed; - } catch (IOException e) { - throw new ParseException(e); - } - } + public Parsed parse(Reader r, Parsed parsed) throws ParseException { + // First things first, if there's a "leftover" event, process that immediately + State state = (State)parsed.state; + if(state.unsent > 0) { + parsed.event = state.unsent; + state.unsent = 0; + return parsed; + } + + int ch; + char c; + StringBuilder sb = parsed.sb; + boolean inQuotes = false, escaped = false; + boolean go = true; + try { + // Gather data from Reader, looking for special characters when not in Quotes + while(go && (ch=r.read())>=0) { + if(state.braces>=0 || ch==Parse.START_OBJ) { // ignore garbage/whitespace before content + c=(char)ch; + // Character is a quote. + if(c=='"') { + if(inQuotes) { + if(escaped) { // if escaped Quote, add to data. + sb.append(c); + escaped = false; + } else { + inQuotes = false; + } + } else { + parsed.isString=true; + inQuotes = true; + } + } else { // Not a Quote + if(inQuotes) { + if(c=='\\') { + if(escaped) { + sb.append("\\\\"); + escaped = false; + } else { + escaped = true; + } + } else { + sb.append(c); + } + } else { + switch(c) { + case ':': + parsed.dataIsName(); + parsed.isString = false; + break; + case Parse.START_OBJ: + if(state.braces++ == 0) { + parsed.event = START_DOC; + state.unsent = c; + } else { + parsed.event = c; + } + go = false; + break; + case Parse.END_OBJ: + if(--state.braces == 0) { + parsed.event = c; + state.unsent = END_DOC; + } else { + parsed.event = c; + } + go = false; + break; + // These three end the data gathering, and send it along with the event that is ending the data gathering + case Parse.NEXT: + if(parsed.name.startsWith("__")) { + parsed.event = Parse.ATTRIB; + parsed.name = parsed.name.substring(2); + } else { + parsed.event = c; + } + go = false; + break; + case Parse.START_ARRAY: + case Parse.END_ARRAY: + parsed.event = c; + go = false; + break; + + // The Escape Sequence, for Quote marks within Quotes + case '\\': + // Ignore these, unless within quotes, at which point data-gather + case ' ': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + break; + // Normal data... gather it + default: + sb.append(c); + } + } + } + } + } + return parsed; + } catch (IOException e) { + throw new ParseException(e); + } + } - public static class State { - public int braces = 0; - public char unsent = 0; - } - -// @Override - public Parsed newParsed() { - return new Parsed(new State()); // no State needed - } + public static class State { + public int braces = 0; + public char unsent = 0; + } + +// @Override + public Parsed newParsed() { + return new Parsed(new State()); // no State needed + } -// @Override - public TimeTaken start(Env env) { - return env.start("Rosetta JSON In", Env.JSON); - } +// @Override + public TimeTaken start(Env env) { + return env.start("Rosetta JSON In", Env.JSON); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java index da66394c..91b7c57d 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java @@ -34,455 +34,455 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.rosetta.InXML.State; public class InXML implements Parse { - // package on purpose - JaxInfo jaxInfo; + // package on purpose + JaxInfo jaxInfo; - public InXML(JaxInfo jaxInfo) { - this.jaxInfo = jaxInfo; - } - - public InXML(Class cls, String ... rootNs) throws SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException { - jaxInfo = JaxInfo.build(cls,rootNs); - } + public InXML(JaxInfo jaxInfo) { + this.jaxInfo = jaxInfo; + } + + public InXML(Class cls, String ... rootNs) throws SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException { + jaxInfo = JaxInfo.build(cls,rootNs); + } - // @Override - public Parsed parse(Reader r, Parsed parsed) throws ParseException { - State state = parsed.state; - - // OK, before anything else, see if there is leftover processing, if so, do it! - if(state.unevaluated!=null) { - DerTag dt = state.unevaluated; - state.unevaluated = null; - if(!state.greatExp.eval(parsed, dt))return parsed; - } + // @Override + public Parsed parse(Reader r, Parsed parsed) throws ParseException { + State state = parsed.state; + + // OK, before anything else, see if there is leftover processing, if so, do it! + if(state.unevaluated!=null) { + DerTag dt = state.unevaluated; + state.unevaluated = null; + if(!state.greatExp.eval(parsed, dt))return parsed; + } - if(state.hasAttributes()) { - Prop prop = state.pop(); - parsed.event = Parse.ATTRIB; - parsed.name = prop.tag; - parsed.sb.append(prop.value); - parsed.isString=true; - return parsed; - } - int ch; - char c; - boolean inQuotes = false, escaped = false; + if(state.hasAttributes()) { + Prop prop = state.pop(); + parsed.event = Parse.ATTRIB; + parsed.name = prop.tag; + parsed.sb.append(prop.value); + parsed.isString=true; + return parsed; + } + int ch; + char c; + boolean inQuotes = false, escaped = false; - StringBuilder sb = parsed.sb, tempSB = new StringBuilder(); - boolean go = true; - - try { - while(go && (ch=r.read())>=0) { - c = (char)ch; - if(c == '"') { - if(state.greatExp instanceof LeafExpectations) { // within a set of Tags, make a Quote - sb.append(c); - } else { - if(inQuotes) { - if(escaped) { - sb.append('\\'); - sb.append(c); - escaped = false; - } else { - inQuotes = false; - } - } else { - parsed.isString=true; - inQuotes = true; - } - } - } else if(inQuotes) { - sb.append(c); - } else if(c=='&') { - XmlEscape.xmlEscape(sb,r); - } else if(c=='\\') { - escaped=true; - } else { - switch(c) { - case '<': - DerTag tag=new DerTag().parse(r, tempSB); - go = state.greatExp.eval(parsed, tag); - break; - default: - // don't add Whitespace to start of SB... saves removing later - if(sb.length()>0) { - sb.append(c); - } else if(!Character.isWhitespace(c)) { - sb.append(c); - } - } - } - } - return parsed; - } catch (IOException e) { - throw new ParseException(e); - } - } - - public static final class DerTag { - public String name; - public boolean isEndTag; - public List props; - private boolean isXmlInfo; - //private String ns; - - public DerTag() { - name=null; - isEndTag = false; - props = null; - isXmlInfo = false; - } - - public DerTag parse(Reader r, StringBuilder sb) throws ParseException { - int ch; - char c; - boolean inQuotes = false, escaped = false; - boolean go = true; - String tag = null; - - try { - if((ch = r.read())<0) throw new ParseException("Reader content ended before complete"); - if(ch=='?') { - isXmlInfo = true; - } - // TODO Check for !-- comments - do { - c=(char)ch; - if(c=='"') { - if(inQuotes) { - if(escaped) { - sb.append(c); - escaped = false; - } else { - inQuotes = false; - } - } else { - inQuotes = true; - } - } else if(inQuotes) { - sb.append(c); - } else { - switch(c) { - case '/': - isEndTag = true; - break; - case ' ': - endField(tag,sb); - tag = null; - break; - case '>': - endField(tag,sb); - go = false; - break; - case '=': - tag = sb.toString(); - sb.setLength(0); - break; -// case ':': -// ns = sb.toString(); -// sb.setLength(0); -// break; - case '?': - if(!isXmlInfo)sb.append(c); - break; - default: - sb.append(c); - } - } - } while(go && (ch=r.read())>=0); - } catch (IOException e) { - throw new ParseException(e); - } - return this; - } + StringBuilder sb = parsed.sb, tempSB = new StringBuilder(); + boolean go = true; + + try { + while(go && (ch=r.read())>=0) { + c = (char)ch; + if(c == '"') { + if(state.greatExp instanceof LeafExpectations) { // within a set of Tags, make a Quote + sb.append(c); + } else { + if(inQuotes) { + if(escaped) { + sb.append('\\'); + sb.append(c); + escaped = false; + } else { + inQuotes = false; + } + } else { + parsed.isString=true; + inQuotes = true; + } + } + } else if(inQuotes) { + sb.append(c); + } else if(c=='&') { + XmlEscape.xmlEscape(sb,r); + } else if(c=='\\') { + escaped=true; + } else { + switch(c) { + case '<': + DerTag tag=new DerTag().parse(r, tempSB); + go = state.greatExp.eval(parsed, tag); + break; + default: + // don't add Whitespace to start of SB... saves removing later + if(sb.length()>0) { + sb.append(c); + } else if(!Character.isWhitespace(c)) { + sb.append(c); + } + } + } + } + return parsed; + } catch (IOException e) { + throw new ParseException(e); + } + } + + public static final class DerTag { + public String name; + public boolean isEndTag; + public List props; + private boolean isXmlInfo; + //private String ns; + + public DerTag() { + name=null; + isEndTag = false; + props = null; + isXmlInfo = false; + } + + public DerTag parse(Reader r, StringBuilder sb) throws ParseException { + int ch; + char c; + boolean inQuotes = false, escaped = false; + boolean go = true; + String tag = null; + + try { + if((ch = r.read())<0) throw new ParseException("Reader content ended before complete"); + if(ch=='?') { + isXmlInfo = true; + } + // TODO Check for !-- comments + do { + c=(char)ch; + if(c=='"') { + if(inQuotes) { + if(escaped) { + sb.append(c); + escaped = false; + } else { + inQuotes = false; + } + } else { + inQuotes = true; + } + } else if(inQuotes) { + sb.append(c); + } else { + switch(c) { + case '/': + isEndTag = true; + break; + case ' ': + endField(tag,sb); + tag = null; + break; + case '>': + endField(tag,sb); + go = false; + break; + case '=': + tag = sb.toString(); + sb.setLength(0); + break; +// case ':': +// ns = sb.toString(); +// sb.setLength(0); +// break; + case '?': + if(!isXmlInfo)sb.append(c); + break; + default: + sb.append(c); + } + } + } while(go && (ch=r.read())>=0); + } catch (IOException e) { + throw new ParseException(e); + } + return this; + } - private void endField(String tag, StringBuilder sb) { - if(name==null) { - name = sb.toString(); - sb.setLength(0); - } else { - String value = sb.toString(); - sb.setLength(0); - if(tag !=null && value != null) { - if(props==null)props = new ArrayList<>(); - props.add(new Prop(tag,value)); - } - } - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(isEndTag?"End":"Start"); - sb.append(" Tag\n"); - sb.append(" Name: "); - sb.append(name); - if(props!=null) for(Prop p : props) { - sb.append("\n "); - sb.append(p.tag); - sb.append("=\""); - sb.append(p.value); - sb.append('"'); - } - return sb.toString(); - } - } - - private static class ArrayState { - public boolean firstObj = true; - public boolean didNext = false; - } + private void endField(String tag, StringBuilder sb) { + if(name==null) { + name = sb.toString(); + sb.setLength(0); + } else { + String value = sb.toString(); + sb.setLength(0); + if(tag !=null && value != null) { + if(props==null)props = new ArrayList<>(); + props.add(new Prop(tag,value)); + } + } + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(isEndTag?"End":"Start"); + sb.append(" Tag\n"); + sb.append(" Name: "); + sb.append(name); + if(props!=null) for(Prop p : props) { + sb.append("\n "); + sb.append(p.tag); + sb.append("=\""); + sb.append(p.value); + sb.append('"'); + } + return sb.toString(); + } + } + + private static class ArrayState { + public boolean firstObj = true; + public boolean didNext = false; + } - public static class State { - public GreatExpectations greatExp; - public DerTag unevaluated; - public Stack arrayInfo; - private List attribs; - private int idx; - public State(JaxInfo ji, DerTag dt) throws ParseException { - greatExp = new RootExpectations(this, ji, null); - unevaluated = null; - attribs = null;; - } - - public boolean hasAttributes() { - return attribs!=null && idx arrayInfo; + private List attribs; + private int idx; + public State(JaxInfo ji, DerTag dt) throws ParseException { + greatExp = new RootExpectations(this, ji, null); + unevaluated = null; + attribs = null;; + } + + public boolean hasAttributes() { + return attribs!=null && idx(); - idx = 0; - } - attribs.add(prop); - } - - public Prop pop() { - Prop rv = null; - if(attribs!=null) { - rv = attribs.get(idx++); - if(idx>=attribs.size())attribs = null; - } - return rv; - } - } - - private static abstract class GreatExpectations { - protected JaxInfo ji; - protected GreatExpectations prev; - private Map ns; - - public GreatExpectations(State state, JaxInfo curr, GreatExpectations prev, DerTag derTag) throws ParseException { - this.prev = prev; - ns = null; - ji = getDerived(state, curr,derTag); - } - - public abstract boolean eval(Parsed parsed, DerTag derTag) throws ParseException; + public void push(Prop prop) { + if(attribs==null) { + attribs = new ArrayList<>(); + idx = 0; + } + attribs.add(prop); + } + + public Prop pop() { + Prop rv = null; + if(attribs!=null) { + rv = attribs.get(idx++); + if(idx>=attribs.size())attribs = null; + } + return rv; + } + } + + private static abstract class GreatExpectations { + protected JaxInfo ji; + protected GreatExpectations prev; + private Map ns; + + public GreatExpectations(State state, JaxInfo curr, GreatExpectations prev, DerTag derTag) throws ParseException { + this.prev = prev; + ns = null; + ji = getDerived(state, curr,derTag); + } + + public abstract boolean eval(Parsed parsed, DerTag derTag) throws ParseException; - // Recursively look back for any namespaces - protected Map getNS() { - if(ns!=null)return ns; - if(prev!=null) { - return prev.getNS(); - } - return null; - } + // Recursively look back for any namespaces + protected Map getNS() { + if(ns!=null)return ns; + if(prev!=null) { + return prev.getNS(); + } + return null; + } - private void addNS(Prop prop) { - Map existingNS = getNS(); - if(ns==null)ns = new HashMap<>(); - // First make a copy of previous NSs so that we have everything we need, but can overwrite, if necessary - if(existingNS!=null && ns!=existingNS) { - ns.putAll(ns); - } - ns.put(prop.tag, prop.value); - } + private void addNS(Prop prop) { + Map existingNS = getNS(); + if(ns==null)ns = new HashMap<>(); + // First make a copy of previous NSs so that we have everything we need, but can overwrite, if necessary + if(existingNS!=null && ns!=existingNS) { + ns.putAll(ns); + } + ns.put(prop.tag, prop.value); + } - private JaxInfo getDerived(State state, JaxInfo ji, DerTag derTag) throws ParseException { - if(derTag==null)return ji; - - List props = derTag.props; - - Prop derived = null; - if(props!=null) { - // Load Namespaces (if any) - for(Prop prop : props) { - if(prop.tag.startsWith("xmlns:")) { - addNS(prop); - } - } - for(Prop prop : props) { - if(prop.tag.endsWith(":type")) { - int idx = prop.tag.indexOf(':'); - String potentialNS = "xmlns:"+prop.tag.substring(0,idx); - Map ns = getNS(); - boolean noNamespace = false; - if(ns==null) { - noNamespace = true; - } else { - String nsVal = ns.get(potentialNS); - if(nsVal==null) noNamespace = true; - else { - derived = new Prop(Parsed.EXTENSION_TAG,prop.value); - state.push(derived); - } - } - if(noNamespace) { - throw new ParseException(prop.tag + " utilizes an invalid Namespace prefix"); - } - } else if(!prop.tag.startsWith("xmlns")) { - state.push(prop); - } - } - } - return derived==null?ji:ji.getDerived(derived.value); - } - } - - private static class RootExpectations extends GreatExpectations { - - public RootExpectations(State state, JaxInfo curr, GreatExpectations prev) throws ParseException { - super(state,curr,prev, null); - } - - // @Override - public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { - if(derTag.isXmlInfo) { - parsed.event = START_DOC; - } else if(ji.name.equals(derTag.name)) { - if(derTag.isEndTag) { - parsed.event = END_DOC; - parsed.state.greatExp = prev; - } else { - //parsed.name = derTag.name; - parsed.event = START_OBJ; - parsed.state.greatExp = new ObjectExpectations(parsed.state,ji, this, false, derTag); - } - } - return false; - } - } - - private static class ObjectExpectations extends GreatExpectations { - private boolean printName; + private JaxInfo getDerived(State state, JaxInfo ji, DerTag derTag) throws ParseException { + if(derTag==null)return ji; + + List props = derTag.props; + + Prop derived = null; + if(props!=null) { + // Load Namespaces (if any) + for(Prop prop : props) { + if(prop.tag.startsWith("xmlns:")) { + addNS(prop); + } + } + for(Prop prop : props) { + if(prop.tag.endsWith(":type")) { + int idx = prop.tag.indexOf(':'); + String potentialNS = "xmlns:"+prop.tag.substring(0,idx); + Map ns = getNS(); + boolean noNamespace = false; + if(ns==null) { + noNamespace = true; + } else { + String nsVal = ns.get(potentialNS); + if(nsVal==null) noNamespace = true; + else { + derived = new Prop(Parsed.EXTENSION_TAG,prop.value); + state.push(derived); + } + } + if(noNamespace) { + throw new ParseException(prop.tag + " utilizes an invalid Namespace prefix"); + } + } else if(!prop.tag.startsWith("xmlns")) { + state.push(prop); + } + } + } + return derived==null?ji:ji.getDerived(derived.value); + } + } + + private static class RootExpectations extends GreatExpectations { + + public RootExpectations(State state, JaxInfo curr, GreatExpectations prev) throws ParseException { + super(state,curr,prev, null); + } + + // @Override + public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { + if(derTag.isXmlInfo) { + parsed.event = START_DOC; + } else if(ji.name.equals(derTag.name)) { + if(derTag.isEndTag) { + parsed.event = END_DOC; + parsed.state.greatExp = prev; + } else { + //parsed.name = derTag.name; + parsed.event = START_OBJ; + parsed.state.greatExp = new ObjectExpectations(parsed.state,ji, this, false, derTag); + } + } + return false; + } + } + + private static class ObjectExpectations extends GreatExpectations { + private boolean printName; - public ObjectExpectations(State state, JaxInfo curr, GreatExpectations prev, boolean printName, DerTag derTag) throws ParseException { - super(state, curr, prev, derTag); - this.printName=printName; - } + public ObjectExpectations(State state, JaxInfo curr, GreatExpectations prev, boolean printName, DerTag derTag) throws ParseException { + super(state, curr, prev, derTag); + this.printName=printName; + } - // @Override - public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { - if(derTag.isEndTag && ji.name.equals(derTag.name)) { - parsed.state.greatExp = prev; - parsed.event = END_OBJ; - if(printName)parsed.name = ji.name; - } else { - //Standard Members - for(JaxInfo memb : ji.members) { - if(memb.name.equals(derTag.name)) { - parsed.name = memb.name; - if(memb.isArray) { - parsed.state.unevaluated = derTag; // evaluate within Array Context - parsed.event = START_ARRAY; - parsed.state.greatExp = new ArrayExpectations(parsed.state,memb,this); - return false; - } else if(memb.isObject()) { - if(derTag.isEndTag) { - throw new ParseException("Unexpected End Tag '); - } else { - parsed.event = START_OBJ; + // @Override + public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { + if(derTag.isEndTag && ji.name.equals(derTag.name)) { + parsed.state.greatExp = prev; + parsed.event = END_OBJ; + if(printName)parsed.name = ji.name; + } else { + //Standard Members + for(JaxInfo memb : ji.members) { + if(memb.name.equals(derTag.name)) { + parsed.name = memb.name; + if(memb.isArray) { + parsed.state.unevaluated = derTag; // evaluate within Array Context + parsed.event = START_ARRAY; + parsed.state.greatExp = new ArrayExpectations(parsed.state,memb,this); + return false; + } else if(memb.isObject()) { + if(derTag.isEndTag) { + throw new ParseException("Unexpected End Tag '); + } else { + parsed.event = START_OBJ; - parsed.state.greatExp = new ObjectExpectations(parsed.state, memb,this,true,derTag); - return false; - } - } else { // a leaf - if(derTag.isEndTag) { - throw new ParseException("Misplaced End Tag '); - } else { - parsed.state.greatExp = new LeafExpectations(parsed.state,memb, this); - return true; // finish out Leaf without returning - } - } - } - } + parsed.state.greatExp = new ObjectExpectations(parsed.state, memb,this,true,derTag); + return false; + } + } else { // a leaf + if(derTag.isEndTag) { + throw new ParseException("Misplaced End Tag '); + } else { + parsed.state.greatExp = new LeafExpectations(parsed.state,memb, this); + return true; // finish out Leaf without returning + } + } + } + } - throw new ParseException("Unexpected Tag <" + derTag.name + '>'); - } - return false; - } - } - - private static class LeafExpectations extends GreatExpectations { - public LeafExpectations(State state, JaxInfo curr, GreatExpectations prev) throws ParseException { - super(state, curr, prev, null); - } + throw new ParseException("Unexpected Tag <" + derTag.name + '>'); + } + return false; + } + } + + private static class LeafExpectations extends GreatExpectations { + public LeafExpectations(State state, JaxInfo curr, GreatExpectations prev) throws ParseException { + super(state, curr, prev, null); + } - // @Override - public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { - if(ji.name.equals(derTag.name) && derTag.isEndTag) { - parsed.event = NEXT; - parsed.isString = ji.isString; - parsed.state.greatExp = prev; - } else { - throw new ParseException("Expected '); - } - return false; - } - } + // @Override + public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { + if(ji.name.equals(derTag.name) && derTag.isEndTag) { + parsed.event = NEXT; + parsed.isString = ji.isString; + parsed.state.greatExp = prev; + } else { + throw new ParseException("Expected '); + } + return false; + } + } - private static class ArrayExpectations extends GreatExpectations { - public ArrayExpectations(State state, JaxInfo ji, GreatExpectations prev) throws ParseException { - super(state, ji, prev,null); - if(state.arrayInfo==null)state.arrayInfo=new Stack(); - state.arrayInfo.push(new ArrayState()); - } - // @Override - public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { - if(ji.name.equals(derTag.name) && !derTag.isEndTag) { - if(ji.isObject()) { - if(derTag.isEndTag) { - throw new ParseException("Unexpected End Tag '); - } else { - ArrayState ai = parsed.state.arrayInfo.peek(); - if(ai.firstObj || ai.didNext) { - ai.firstObj = false; - ai.didNext = false; - parsed.event = START_OBJ; - parsed.name=derTag.name; - parsed.state.greatExp = new ObjectExpectations(parsed.state,ji,this,true, derTag); - } else { - ai.didNext = true; - parsed.event = NEXT; - parsed.state.unevaluated = derTag; - } - } - } else { // a leave - if(derTag.isEndTag) { - throw new ParseException("Misplaced End Tag '); - } else { - parsed.state.greatExp = new LeafExpectations(parsed.state, ji, this); - return true; // finish out Leaf without returning - } - } - } else { // Tag now different... Array is done - parsed.state.unevaluated = derTag; - parsed.event=END_ARRAY; - parsed.state.greatExp = prev; - parsed.state.arrayInfo.pop(); - } - return false; - } - } - // @Override - public Parsed newParsed() throws ParseException { - return new Parsed(new State(jaxInfo, null)); - } + private static class ArrayExpectations extends GreatExpectations { + public ArrayExpectations(State state, JaxInfo ji, GreatExpectations prev) throws ParseException { + super(state, ji, prev,null); + if(state.arrayInfo==null)state.arrayInfo=new Stack(); + state.arrayInfo.push(new ArrayState()); + } + // @Override + public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { + if(ji.name.equals(derTag.name) && !derTag.isEndTag) { + if(ji.isObject()) { + if(derTag.isEndTag) { + throw new ParseException("Unexpected End Tag '); + } else { + ArrayState ai = parsed.state.arrayInfo.peek(); + if(ai.firstObj || ai.didNext) { + ai.firstObj = false; + ai.didNext = false; + parsed.event = START_OBJ; + parsed.name=derTag.name; + parsed.state.greatExp = new ObjectExpectations(parsed.state,ji,this,true, derTag); + } else { + ai.didNext = true; + parsed.event = NEXT; + parsed.state.unevaluated = derTag; + } + } + } else { // a leave + if(derTag.isEndTag) { + throw new ParseException("Misplaced End Tag '); + } else { + parsed.state.greatExp = new LeafExpectations(parsed.state, ji, this); + return true; // finish out Leaf without returning + } + } + } else { // Tag now different... Array is done + parsed.state.unevaluated = derTag; + parsed.event=END_ARRAY; + parsed.state.greatExp = prev; + parsed.state.arrayInfo.pop(); + } + return false; + } + } + // @Override + public Parsed newParsed() throws ParseException { + return new Parsed(new State(jaxInfo, null)); + } - // @Override - public TimeTaken start(Env env) { - return env.start("Rosetta XML In", Env.XML); - } - + // @Override + public TimeTaken start(Env env) { + return env.start("Rosetta XML In", Env.XML); + } + } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxEval.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxEval.java index 2708aa2f..cb6d2f8c 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxEval.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxEval.java @@ -22,5 +22,5 @@ package org.onap.aaf.misc.rosetta; public interface JaxEval{ - public abstract JaxEval eval(Parsed p) throws ParseException; + public abstract JaxEval eval(Parsed p) throws ParseException; } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java index 6c20ba25..edc5f787 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java @@ -35,214 +35,214 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; public class JaxInfo { - private static final String DEFAULT = "##default"; - public static final int DATA = 0; - public static final int ARRAY = 1; - public static final int OBJECT = 2; - - public final String name; - public final Class clss; - public Map extensions; // Classes, which might be found at runtime, that extend this class. Lazy Instantiation - public final JaxInfo[] members; - public final boolean isArray; - public final boolean isString; - public final boolean required; - public final boolean nillable; - public String ns; - public boolean isObject() {return members!=null;} - - private JaxInfo(String n, String ns, Class c, JaxInfo[] members, boolean string, boolean array, boolean required, boolean nillable) { - name = n; - this.ns = ns; - clss = c; - this.members = members; - this.isString = string; - isArray = array; - this.required = required; - this.nillable = nillable; - extensions = null; - } - + private static final String DEFAULT = "##default"; + public static final int DATA = 0; + public static final int ARRAY = 1; + public static final int OBJECT = 2; + + public final String name; + public final Class clss; + public Map extensions; // Classes, which might be found at runtime, that extend this class. Lazy Instantiation + public final JaxInfo[] members; + public final boolean isArray; + public final boolean isString; + public final boolean required; + public final boolean nillable; + public String ns; + public boolean isObject() {return members!=null;} + + private JaxInfo(String n, String ns, Class c, JaxInfo[] members, boolean string, boolean array, boolean required, boolean nillable) { + name = n; + this.ns = ns; + clss = c; + this.members = members; + this.isString = string; + isArray = array; + this.required = required; + this.nillable = nillable; + extensions = null; + } + - public int getType() { - if(isArray)return ARRAY; - else if(members!=null)return OBJECT; - return DATA; - } - - public JaxInfo getDerived(String derivedName) { - JaxInfo derived; - // Lazy Instantiation - if(extensions == null) { - extensions = new HashMap<>(); - derived = null; - } else { - derived = extensions.get(derivedName); - } - - if(derived == null) { - //TODO for the moment, Classes are in same package - Package pkg = clss.getPackage(); - try { - Class dc = getClass().getClassLoader().loadClass(pkg.getName()+'.'+Character.toUpperCase(derivedName.charAt(0))+derivedName.substring(1)); - derived = JaxInfo.build(dc, this); // Use this JAXInfo's name so the tags are correct - extensions.put(derivedName, derived); - } catch (Exception e) { - e.printStackTrace(); - } - } - return derived; - } + public int getType() { + if(isArray)return ARRAY; + else if(members!=null)return OBJECT; + return DATA; + } + + public JaxInfo getDerived(String derivedName) { + JaxInfo derived; + // Lazy Instantiation + if(extensions == null) { + extensions = new HashMap<>(); + derived = null; + } else { + derived = extensions.get(derivedName); + } + + if(derived == null) { + //TODO for the moment, Classes are in same package + Package pkg = clss.getPackage(); + try { + Class dc = getClass().getClassLoader().loadClass(pkg.getName()+'.'+Character.toUpperCase(derivedName.charAt(0))+derivedName.substring(1)); + derived = JaxInfo.build(dc, this); // Use this JAXInfo's name so the tags are correct + extensions.put(derivedName, derived); + } catch (Exception e) { + e.printStackTrace(); + } + } + return derived; + } - public static JaxInfo get(JaxInfo[] fields, String name) { - for(JaxInfo f : fields) { - if(name.equals(f.name)) return f; - } - return null; - } + public static JaxInfo get(JaxInfo[] fields, String name) { + for(JaxInfo f : fields) { + if(name.equals(f.name)) return f; + } + return null; + } - /** - * Build up JAXB Information (recursively) - * - * @param cls - * @param rootNns - * @return - * @throws SecurityException - * @throws NoSuchFieldException - * @throws ClassNotFoundException - * @throws ParseException - */ - public static JaxInfo build(Class cls, JaxInfo parent) throws NoSuchFieldException, ClassNotFoundException, ParseException { - return new JaxInfo(parent.name,parent.ns, cls,buildFields(cls,parent.ns),parent.isString, parent.isArray,parent.required,parent.nillable); - } - /** - * Build up JAXB Information (recursively) - * - * @param cls - * @param rootNns - * @return - * @throws SecurityException - * @throws NoSuchFieldException - * @throws ClassNotFoundException - * @throws ParseException - */ - public static JaxInfo build(Class cls, String ... rootNns) throws SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException { - String defaultNS; - if(rootNns.length>0 && rootNns[0]!=null) { - defaultNS = rootNns[0]; - } else { - Package pkg = cls.getPackage(); - XmlSchema xs = pkg.getAnnotation(XmlSchema.class); - defaultNS = xs==null?"":xs.namespace(); - } - String name; - if(rootNns.length>1) { - name = rootNns[1]; - } else { - XmlRootElement xre = cls.getAnnotation(XmlRootElement.class); - if(xre!=null) { - name = xre.name(); - } else { - XmlType xt = cls.getAnnotation(XmlType.class); - if(xt!=null) { - name=xt.name(); - } else { - throw new ParseException("Need a JAXB Object with XmlRootElement, or stipulate in parms"); - } - } - } - - return new JaxInfo(name,defaultNS, cls,buildFields(cls,defaultNS),false,false,false,false); - } - - // Build up the name and members of this particular class - // This is recursive, if a member is a JAXB Object as well. - private static JaxInfo[] buildFields(Class clazz, String defaultNS) throws SecurityException, NoSuchFieldException, ClassNotFoundException { - ArrayList fields = null; // allow for lazy instantiation, because many structures won't have XmlType - Class cls = clazz; - // Build up Method names from JAXB Annotations - XmlType xt; - while((xt = cls.getAnnotation(XmlType.class))!=null) { - if(fields==null)fields = new ArrayList<>(); - for(String field : xt.propOrder()) { - if("".equals(field)) break; // odd bug. "" returned when no fields exist, rather than empty array - Field rf = cls.getDeclaredField(field); - Class ft = rf.getType(); - - boolean required = false; - boolean nillable = false; - String xmlName = field; - String namespace = defaultNS; - - XmlElement xe = rf.getAnnotation(XmlElement.class); - if(xe!=null) { - xmlName=xe.name(); - required = xe.required(); - nillable = false; - if(DEFAULT.equals(xmlName)) { - xmlName = field; - } - namespace = xe.namespace(); - if(DEFAULT.equals(namespace)) { - namespace = defaultNS; - } - } - // If object is a List, then it is possible multiple, per XML/JAXB evaluation - if(ft.isAssignableFrom(List.class)) { - Type t = rf.getGenericType(); - String classname = t.toString(); - int start = classname.indexOf('<'); - int end = classname.indexOf('>'); - Class genClass = Class.forName(classname.substring(start+1, end)); - xe = genClass.getAnnotation(XmlElement.class); - if(xe!=null && !DEFAULT.equals(xe.namespace())) { - namespace = xe.namespace(); - } - // add recursed recursed member, marked as array - fields.add(new JaxInfo(xmlName,namespace,genClass,buildFields(genClass,namespace), genClass.equals(String.class),true,required,nillable)); - } else { - boolean isString = ft.equals(String.class) || ft.equals(XMLGregorianCalendar.class); - // add recursed member - fields.add(new JaxInfo(xmlName,namespace,ft,buildFields(ft,namespace),isString,false,required,nillable)); - } - } - cls = cls.getSuperclass(); - }; - if(fields!=null) { - JaxInfo[] rv = new JaxInfo[fields.size()]; - fields.toArray(rv); - return rv; - } else { - return null; - } - } + /** + * Build up JAXB Information (recursively) + * + * @param cls + * @param rootNns + * @return + * @throws SecurityException + * @throws NoSuchFieldException + * @throws ClassNotFoundException + * @throws ParseException + */ + public static JaxInfo build(Class cls, JaxInfo parent) throws NoSuchFieldException, ClassNotFoundException, ParseException { + return new JaxInfo(parent.name,parent.ns, cls,buildFields(cls,parent.ns),parent.isString, parent.isArray,parent.required,parent.nillable); + } + /** + * Build up JAXB Information (recursively) + * + * @param cls + * @param rootNns + * @return + * @throws SecurityException + * @throws NoSuchFieldException + * @throws ClassNotFoundException + * @throws ParseException + */ + public static JaxInfo build(Class cls, String ... rootNns) throws SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException { + String defaultNS; + if(rootNns.length>0 && rootNns[0]!=null) { + defaultNS = rootNns[0]; + } else { + Package pkg = cls.getPackage(); + XmlSchema xs = pkg.getAnnotation(XmlSchema.class); + defaultNS = xs==null?"":xs.namespace(); + } + String name; + if(rootNns.length>1) { + name = rootNns[1]; + } else { + XmlRootElement xre = cls.getAnnotation(XmlRootElement.class); + if(xre!=null) { + name = xre.name(); + } else { + XmlType xt = cls.getAnnotation(XmlType.class); + if(xt!=null) { + name=xt.name(); + } else { + throw new ParseException("Need a JAXB Object with XmlRootElement, or stipulate in parms"); + } + } + } + + return new JaxInfo(name,defaultNS, cls,buildFields(cls,defaultNS),false,false,false,false); + } + + // Build up the name and members of this particular class + // This is recursive, if a member is a JAXB Object as well. + private static JaxInfo[] buildFields(Class clazz, String defaultNS) throws SecurityException, NoSuchFieldException, ClassNotFoundException { + ArrayList fields = null; // allow for lazy instantiation, because many structures won't have XmlType + Class cls = clazz; + // Build up Method names from JAXB Annotations + XmlType xt; + while((xt = cls.getAnnotation(XmlType.class))!=null) { + if(fields==null)fields = new ArrayList<>(); + for(String field : xt.propOrder()) { + if("".equals(field)) break; // odd bug. "" returned when no fields exist, rather than empty array + Field rf = cls.getDeclaredField(field); + Class ft = rf.getType(); + + boolean required = false; + boolean nillable = false; + String xmlName = field; + String namespace = defaultNS; + + XmlElement xe = rf.getAnnotation(XmlElement.class); + if(xe!=null) { + xmlName=xe.name(); + required = xe.required(); + nillable = false; + if(DEFAULT.equals(xmlName)) { + xmlName = field; + } + namespace = xe.namespace(); + if(DEFAULT.equals(namespace)) { + namespace = defaultNS; + } + } + // If object is a List, then it is possible multiple, per XML/JAXB evaluation + if(ft.isAssignableFrom(List.class)) { + Type t = rf.getGenericType(); + String classname = t.toString(); + int start = classname.indexOf('<'); + int end = classname.indexOf('>'); + Class genClass = Class.forName(classname.substring(start+1, end)); + xe = genClass.getAnnotation(XmlElement.class); + if(xe!=null && !DEFAULT.equals(xe.namespace())) { + namespace = xe.namespace(); + } + // add recursed recursed member, marked as array + fields.add(new JaxInfo(xmlName,namespace,genClass,buildFields(genClass,namespace), genClass.equals(String.class),true,required,nillable)); + } else { + boolean isString = ft.equals(String.class) || ft.equals(XMLGregorianCalendar.class); + // add recursed member + fields.add(new JaxInfo(xmlName,namespace,ft,buildFields(ft,namespace),isString,false,required,nillable)); + } + } + cls = cls.getSuperclass(); + }; + if(fields!=null) { + JaxInfo[] rv = new JaxInfo[fields.size()]; + fields.toArray(rv); + return rv; + } else { + return null; + } + } - public StringBuilder dump(StringBuilder sb, int idx) { - for(int i=0;i */ public class JaxSet { - private static Map,JaxSet> jsets = new HashMap<>(); - private Map> members; + private static Map,JaxSet> jsets = new HashMap<>(); + private Map> members; - private JaxSet(Class cls) { - members = new TreeMap<>(); - XmlType xmltype = cls.getAnnotation(XmlType.class); - Class paramType[] = new Class[] {String.class}; - for(String str : xmltype.propOrder()) { - try { - String setName = "set" + Character.toUpperCase(str.charAt(0)) + str.subSequence(1, str.length()); - Method meth = cls.getMethod(setName,paramType ); - if(meth!=null) { - members.put(str, new Setter(meth) { - public void set(T o, Object t) throws ParseException { - try { - this.meth.invoke(o, t); - } catch (Exception e) { - throw new ParseException(e); - } - } - }); - } - } catch (Exception e) { - // oops - } - } - } - - public static abstract class Setter { - protected final Method meth; - public Setter(Method meth) { - this.meth = meth; - } - public abstract void set(O o, Object obj) throws ParseException; - } + private JaxSet(Class cls) { + members = new TreeMap<>(); + XmlType xmltype = cls.getAnnotation(XmlType.class); + Class paramType[] = new Class[] {String.class}; + for(String str : xmltype.propOrder()) { + try { + String setName = "set" + Character.toUpperCase(str.charAt(0)) + str.subSequence(1, str.length()); + Method meth = cls.getMethod(setName,paramType ); + if(meth!=null) { + members.put(str, new Setter(meth) { + public void set(T o, Object t) throws ParseException { + try { + this.meth.invoke(o, t); + } catch (Exception e) { + throw new ParseException(e); + } + } + }); + } + } catch (Exception e) { + // oops + } + } + } + + public static abstract class Setter { + protected final Method meth; + public Setter(Method meth) { + this.meth = meth; + } + public abstract void set(O o, Object obj) throws ParseException; + } - public static JaxSet get(Class cls) { - synchronized(jsets) { - @SuppressWarnings("unchecked") - JaxSet js = (JaxSet)jsets.get(cls); - if(js == null) { - jsets.put(cls, js = new JaxSet<>(cls)); - } - return js; - } - } + public static JaxSet get(Class cls) { + synchronized(jsets) { + @SuppressWarnings("unchecked") + JaxSet js = (JaxSet)jsets.get(cls); + if(js == null) { + jsets.put(cls, js = new JaxSet<>(cls)); + } + return js; + } + } - public Setter get(String key) { - return members.get(key); - } + public Setter get(String key) { + return members.get(key); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java index 51cec078..5e03ac91 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java @@ -32,82 +32,82 @@ package org.onap.aaf.misc.rosetta; * */ public class Ladder { - public static final int DEFAULT_INIT_SIZE=8; - private final int init_size; - private int rung; // as in ladder - private Object[] struts; + public static final int DEFAULT_INIT_SIZE=8; + private final int init_size; + private int rung; // as in ladder + private Object[] struts; - public Ladder() { - rung=0; - init_size = DEFAULT_INIT_SIZE; - struts=new Object[init_size]; - } + public Ladder() { + rung=0; + init_size = DEFAULT_INIT_SIZE; + struts=new Object[init_size]; + } - public Ladder(int initSize) { - rung=0; - init_size = initSize; - struts=new Object[init_size]; - } + public Ladder(int initSize) { + rung=0; + init_size = initSize; + struts=new Object[init_size]; + } - public void bottom() { - rung = 0; - } - - public void top() { - rung = struts.length-1; - while(rung>0 && struts[rung]==null)--rung; - } - - public int howHigh() { - return rung; - } - - public void jumpTo(int rung) { - if(rung>=struts.length) { - Object[] temp = new Object[init_size*((rung/init_size)+1)]; - System.arraycopy(struts, 0, temp, 0, struts.length); - struts = temp; - } - this.rung = rung; - } - - public int height() { - return struts.length; - } - - public void cutTo(int rungs) { - Object[] temp = new Object[rungs]; - System.arraycopy(struts, 0, temp, 0, Math.min(rungs, struts.length)); - struts = temp; - } - - public void ascend() { - ++rung; - if(rung>=struts.length) { - Object[] temp = new Object[struts.length+init_size]; - System.arraycopy(struts, 0, temp, 0, struts.length); - struts = temp; - } - } - - public void descend() { - --rung; - } - - @SuppressWarnings("unchecked") - public T peek() { - return (T)struts[rung]; - } - - public void push(T t) { - struts[rung]=t; - } - - @SuppressWarnings("unchecked") - public T pop() { - T t = (T)struts[rung]; - struts[rung]=null; - return t; - } + public void bottom() { + rung = 0; + } + + public void top() { + rung = struts.length-1; + while(rung>0 && struts[rung]==null)--rung; + } + + public int howHigh() { + return rung; + } + + public void jumpTo(int rung) { + if(rung>=struts.length) { + Object[] temp = new Object[init_size*((rung/init_size)+1)]; + System.arraycopy(struts, 0, temp, 0, struts.length); + struts = temp; + } + this.rung = rung; + } + + public int height() { + return struts.length; + } + + public void cutTo(int rungs) { + Object[] temp = new Object[rungs]; + System.arraycopy(struts, 0, temp, 0, Math.min(rungs, struts.length)); + struts = temp; + } + + public void ascend() { + ++rung; + if(rung>=struts.length) { + Object[] temp = new Object[struts.length+init_size]; + System.arraycopy(struts, 0, temp, 0, struts.length); + struts = temp; + } + } + + public void descend() { + --rung; + } + + @SuppressWarnings("unchecked") + public T peek() { + return (T)struts[rung]; + } + + public void push(T t) { + struts[rung]=t; + } + + @SuppressWarnings("unchecked") + public T pop() { + T t = (T)struts[rung]; + struts[rung]=null; + return t; + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java index 595bc630..4b8d2bf3 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java @@ -29,57 +29,57 @@ import org.onap.aaf.misc.env.TimeTaken; public abstract class Marshal implements Parse { - /* (non-Javadoc) - * @see org.onap.aaf.misc.rosetta.Parse#newParsed() - */ - @Override - public Parsed newParsed() throws ParseException { - return new Parsed(new State()); - } + /* (non-Javadoc) + * @see org.onap.aaf.misc.rosetta.Parse#newParsed() + */ + @Override + public Parsed newParsed() throws ParseException { + return new Parsed(new State()); + } - @Override - public TimeTaken start(Env env) { - //TODO is a way to mark not-JSON? - return env.start("Rosetta Marshal", Env.JSON); - }; + @Override + public TimeTaken start(Env env) { + //TODO is a way to mark not-JSON? + return env.start("Rosetta Marshal", Env.JSON); + }; - public static class State { - // Note: Need a STATEFUL stack... one that will remain stateful until marked as finished - // "finished" is know by Iterators with no more to do/null - // Thus the concept of "Ladder", which one ascends and decends - public Ladder> ladder = new Ladder>(); - public boolean smallest = true; - } + public static class State { + // Note: Need a STATEFUL stack... one that will remain stateful until marked as finished + // "finished" is know by Iterators with no more to do/null + // Thus the concept of "Ladder", which one ascends and decends + public Ladder> ladder = new Ladder>(); + public boolean smallest = true; + } - public static final Iterator DONE_ITERATOR = new Iterator() { - @Override - public boolean hasNext() { - return false; - } + public static final Iterator DONE_ITERATOR = new Iterator() { + @Override + public boolean hasNext() { + return false; + } - @Override - public Void next() { - if(!hasNext()) { - throw new NoSuchElementException(); - } - return null; - } + @Override + public Void next() { + if(!hasNext()) { + throw new NoSuchElementException(); + } + return null; + } - @Override - public void remove() { - } - }; + @Override + public void remove() { + } + }; - /** - * Typical definition of Done is when Iterator in Ladder is "DONE_ITERATOR" - * - * It is important, however, that the "Ladder Rung" is set to the right level. - * - * @param state - * @return - */ - public boolean amFinished(State state) { - return DONE_ITERATOR.equals(state.ladder.peek()); - } + /** + * Typical definition of Done is when Iterator in Ladder is "DONE_ITERATOR" + * + * It is important, however, that the "Ladder Rung" is set to the right level. + * + * @param state + * @return + */ + public boolean amFinished(State state) { + return DONE_ITERATOR.equals(state.ladder.peek()); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Nulls.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Nulls.java index 38b021ea..d36c07ec 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Nulls.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Nulls.java @@ -29,38 +29,38 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.TimeTaken; public class Nulls { - public static final Parse IN = new Parse() { + public static final Parse IN = new Parse() { - // @Override - public Parsed parse(Reader r, Parsed parsed)throws ParseException { - parsed.event = Parse.END_DOC; - return parsed; - } + // @Override + public Parsed parse(Reader r, Parsed parsed)throws ParseException { + parsed.event = Parse.END_DOC; + return parsed; + } - // @Override - public Parsed newParsed() { - Parsed parsed = new Parsed(); - parsed.event = Parse.END_DOC; - return parsed; - } + // @Override + public Parsed newParsed() { + Parsed parsed = new Parsed(); + parsed.event = Parse.END_DOC; + return parsed; + } - // @Override - public TimeTaken start(Env env) { - return env.start("IN", Env.SUB); - } - - }; - - public static final Out OUT = new Out() { + // @Override + public TimeTaken start(Env env) { + return env.start("IN", Env.SUB); + } + + }; + + public static final Out OUT = new Out() { - // @Override - public void extract(IN in, Writer writer, Parse parse, boolean ... options)throws IOException, ParseException { - } - @Override - public String logName() { - return "Rosetta NULL"; - } + // @Override + public void extract(IN in, Writer writer, Parse parse, boolean ... options)throws IOException, ParseException { + } + @Override + public String logName() { + return "Rosetta NULL"; + } - }; + }; } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Out.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Out.java index 567a6261..aa2b2992 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Out.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Out.java @@ -27,17 +27,17 @@ import java.io.OutputStreamWriter; import java.io.Writer; public abstract class Out { - public abstract void extract(IN in, Writer writer, Parse parse, boolean ... options) throws IOException, ParseException; - - public void extract(IN in, OutputStream os, Parse parse, boolean ... options) throws IOException, ParseException { - Writer w = new OutputStreamWriter(os); - try { - extract(in, w, parse, options); - } finally { - w.flush(); - } - } - - public abstract String logName(); - + public abstract void extract(IN in, Writer writer, Parse parse, boolean ... options) throws IOException, ParseException; + + public void extract(IN in, OutputStream os, Parse parse, boolean ... options) throws IOException, ParseException { + Writer w = new OutputStreamWriter(os); + try { + extract(in, w, parse, options); + } finally { + w.flush(); + } + } + + public abstract String logName(); + } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java index db7b956c..2716c8be 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java @@ -25,27 +25,27 @@ import java.io.IOException; import java.io.Writer; public class OutJax extends Out { - private JaxEval jaxEval; - - public OutJax(JaxEval je) { - this.jaxEval = je; - } - - @Override - public void extract(IN in, Writer writer, Parse parse, boolean... options) throws IOException, ParseException { - Parsed p = parse.newParsed(); - JaxEval je = this.jaxEval; - while((p = parse.parse(in,p.reuse())).valid()) { - if(je==null)throw new ParseException("Incomplete content"); - je = je.eval(p); - } - - } - - @Override - public String logName() { - return "Rosetta JAX"; - } + private JaxEval jaxEval; + + public OutJax(JaxEval je) { + this.jaxEval = je; + } + + @Override + public void extract(IN in, Writer writer, Parse parse, boolean... options) throws IOException, ParseException { + Parsed p = parse.newParsed(); + JaxEval je = this.jaxEval; + while((p = parse.parse(in,p.reuse())).valid()) { + if(je==null)throw new ParseException("Incomplete content"); + je = je.eval(p); + } + + } + + @Override + public String logName() { + return "Rosetta JAX"; + } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java index 2340bdb6..d0a26784 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java @@ -29,204 +29,204 @@ import org.onap.aaf.misc.env.util.IndentPrintWriter; public class OutJson extends Out { - @Override - public void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { - Parsed p = prs.newParsed(); - IndentPrintWriter ipw; - if(options.length>0 && options[0]) { // is Pretty - ipw = writer instanceof IndentPrintWriter?(IndentPrintWriter)writer:new IndentPrintWriter(writer); - writer = ipw; - } else { - ipw = null; - } - - // If it's a fragment, print first Object Name. If root Object, skip first name - Stack jsonLevel = new Stack(); - jsonLevel.push(new LevelStack(options.length>1 && options[1])); - boolean print = true, hadData=false; - char afterName=0, beforeName=0, maybe = 0, prev=0; - - int count = 0; - while((p = prs.parse(in,p.reuse())).valid()) { - ++count; - switch(p.event) { - case 1: - continue; - case 2: - if(count==2) { // it's empty, write open/close on it's own - writer.append('{'); - writer.append('}'); - } - writer.flush(); - return; - case '{': - afterName = '{'; - if(jsonLevel.peek().printObjectName) { - print = true; - } else { // don't print names on first - print=false; - } - maybe=jsonLevel.peek().listItem(); - jsonLevel.push(new LevelStack(true)); - break; - case '}': - if(p.hasData()) { // if we have data, we print that, so may need to prepend a comma. - maybe = jsonLevel.peek().listItem(); - } else { // No data means just print, - p.name = ""; // XML tags come through with names, but no data - } - print = true; - jsonLevel.pop(); - afterName = p.event; - break; - case '[': - afterName = p.event; - if((prev==',' && !hadData) || prev==']')maybe=','; - else maybe = jsonLevel.peek().listItem(); + @Override + public void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { + Parsed p = prs.newParsed(); + IndentPrintWriter ipw; + if(options.length>0 && options[0]) { // is Pretty + ipw = writer instanceof IndentPrintWriter?(IndentPrintWriter)writer:new IndentPrintWriter(writer); + writer = ipw; + } else { + ipw = null; + } + + // If it's a fragment, print first Object Name. If root Object, skip first name + Stack jsonLevel = new Stack(); + jsonLevel.push(new LevelStack(options.length>1 && options[1])); + boolean print = true, hadData=false; + char afterName=0, beforeName=0, maybe = 0, prev=0; + + int count = 0; + while((p = prs.parse(in,p.reuse())).valid()) { + ++count; + switch(p.event) { + case 1: + continue; + case 2: + if(count==2) { // it's empty, write open/close on it's own + writer.append('{'); + writer.append('}'); + } + writer.flush(); + return; + case '{': + afterName = '{'; + if(jsonLevel.peek().printObjectName) { + print = true; + } else { // don't print names on first + print=false; + } + maybe=jsonLevel.peek().listItem(); + jsonLevel.push(new LevelStack(true)); + break; + case '}': + if(p.hasData()) { // if we have data, we print that, so may need to prepend a comma. + maybe = jsonLevel.peek().listItem(); + } else { // No data means just print, + p.name = ""; // XML tags come through with names, but no data + } + print = true; + jsonLevel.pop(); + afterName = p.event; + break; + case '[': + afterName = p.event; + if((prev==',' && !hadData) || prev==']')maybe=','; + else maybe = jsonLevel.peek().listItem(); - jsonLevel.push(new LevelStack(false)); - print=true; - break; - case ']': - afterName = p.event; - if(p.hasData()) { - if(prev==',' && !hadData)maybe=','; - else maybe = jsonLevel.peek().listItem(); - } else { - p.name = ""; // XML tags come through with names, but no data - } - jsonLevel.pop(); + jsonLevel.push(new LevelStack(false)); + print=true; + break; + case ']': + afterName = p.event; + if(p.hasData()) { + if(prev==',' && !hadData)maybe=','; + else maybe = jsonLevel.peek().listItem(); + } else { + p.name = ""; // XML tags come through with names, but no data + } + jsonLevel.pop(); - print = true; - break; - case 3: - case ',': - if(!p.hasData()) { - p.isString=false; - print=false; - } else { - maybe=jsonLevel.peek().listItem(); - print = true; - } - break; - default: - print = true; - } - - if(maybe!=0) { - if(ipw==null)writer.append(maybe); - else ipw.println(maybe); - maybe = 0; - } - - if(beforeName!=0) { - if(ipw==null)writer.append(beforeName); - else ipw.println(beforeName); - beforeName = 0; - } - if(print) { - if(p.hasName()) { - writer.append('"'); - if(p.event==3)writer.append("__"); - writer.append(p.name); - writer.append("\":"); - } - if(p.hasData()) { - if(p.isString) { - writer.append('"'); - escapedWrite(writer, p.sb); - writer.append('"'); - } else if(p.sb.length()>0) { - writer.append(p.sb); - } - } - } - if(afterName!=0) { - if(ipw==null)writer.append(afterName); - else { - switch(afterName) { - case '{': - ipw.println(afterName); - ipw.inc(); - break; - case '}': - ipw.dec(); - ipw.println(); - ipw.print(afterName); - break; - case ']': - if(prev=='}' || prev==',')ipw.println(); - ipw.dec(); - ipw.print(afterName); - break; + print = true; + break; + case 3: + case ',': + if(!p.hasData()) { + p.isString=false; + print=false; + } else { + maybe=jsonLevel.peek().listItem(); + print = true; + } + break; + default: + print = true; + } + + if(maybe!=0) { + if(ipw==null)writer.append(maybe); + else ipw.println(maybe); + maybe = 0; + } + + if(beforeName!=0) { + if(ipw==null)writer.append(beforeName); + else ipw.println(beforeName); + beforeName = 0; + } + if(print) { + if(p.hasName()) { + writer.append('"'); + if(p.event==3)writer.append("__"); + writer.append(p.name); + writer.append("\":"); + } + if(p.hasData()) { + if(p.isString) { + writer.append('"'); + escapedWrite(writer, p.sb); + writer.append('"'); + } else if(p.sb.length()>0) { + writer.append(p.sb); + } + } + } + if(afterName!=0) { + if(ipw==null)writer.append(afterName); + else { + switch(afterName) { + case '{': + ipw.println(afterName); + ipw.inc(); + break; + case '}': + ipw.dec(); + ipw.println(); + ipw.print(afterName); + break; + case ']': + if(prev=='}' || prev==',')ipw.println(); + ipw.dec(); + ipw.print(afterName); + break; - case ',': - ipw.println(afterName); - break; - default: - ipw.print(afterName); - } - } - afterName = 0; - } - - if(ipw!=null) { - switch(p.event) { - case '[': - ipw.inc(); - ipw.println(); - break; - } - } - prev = p.event; - hadData = p.hasData(); + case ',': + ipw.println(afterName); + break; + default: + ipw.print(afterName); + } + } + afterName = 0; + } + + if(ipw!=null) { + switch(p.event) { + case '[': + ipw.inc(); + ipw.println(); + break; + } + } + prev = p.event; + hadData = p.hasData(); - } - writer.flush(); - } + } + writer.flush(); + } - private void escapedWrite(Writer writer, StringBuilder sb) throws IOException { - char c; - for(int i=0;i void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { - Parsed p = prs.newParsed(); - - while((p = prs.parse(in,p.reuse())).valid()) { - writer.append(p.toString()); - writer.append('\n'); - } - } - - @Override - public String logName() { - return "Rosetta RAW"; - } + @Override + public void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { + Parsed p = prs.newParsed(); + + while((p = prs.parse(in,p.reuse())).valid()) { + writer.append(p.toString()); + writer.append('\n'); + } + } + + @Override + public String logName() { + return "Rosetta RAW"; + } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java index 8557c584..a887cb96 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java @@ -33,193 +33,193 @@ import org.onap.aaf.misc.env.util.IndentPrintWriter; import org.onap.aaf.misc.env.util.StringBuilderWriter; public class OutXML extends Out{ - private static final String XMLNS_XSI = "xmlns:xsi"; - public static final String XML_INFO = ""; - public static final String XML_SCHEMA_INSTANCE = "http://www.w3.org/2001/XMLSchema-instance"; - - private String root; - private List props; + private static final String XMLNS_XSI = "xmlns:xsi"; + public static final String XML_INFO = ""; + public static final String XML_SCHEMA_INSTANCE = "http://www.w3.org/2001/XMLSchema-instance"; + + private String root; + private List props; - public OutXML(String root, String ... params) { - this.root = root; - props = new ArrayList<>(); - for(String p : params) { - String[] tv=p.split("="); - if(tv.length==2) - props.add(new Prop(tv[0],tv[1])); - } - } - - public OutXML(JaxInfo jaxInfo) { - this(jaxInfo.name,genNS(jaxInfo)); - } - - public OutXML(InXML inXML) { - this(inXML.jaxInfo.name,genNS(inXML.jaxInfo)); - } - - private static String[] genNS(JaxInfo jaxInfo) { - return new String[] {"xmlns=" + jaxInfo.ns}; - } - - - @Override - public void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { - Parsed p = prs.newParsed(); - Stack stack = new Stack(); - // If it's an IndentPrintWriter, it is pretty printing. - boolean pretty = (options.length>0&&options[0]); - - IndentPrintWriter ipw; - if(pretty) { - if(writer instanceof IndentPrintWriter) { - ipw = (IndentPrintWriter)writer; - } else { - writer = ipw = new IndentPrintWriter(writer); - } - } else { - ipw=null; - } - boolean closeTag = false; - Level level = new Level(null); - while((p = prs.parse(in,p.reuse())).valid()) { - if(!p.hasName() && level.multi!=null) { - p.name=level.multi; - } - if(closeTag && p.event!=Parse.ATTRIB) { - writer.append('>'); - if(pretty)writer.append('\n'); - closeTag = false; - } - switch(p.event) { - case Parse.START_DOC: - if(!(options.length>1&&options[1])) // if not a fragment, print XML Info data - if(pretty)ipw.println(XML_INFO); - else writer.append(XML_INFO); - break; - case Parse.END_DOC: - break; - case Parse.START_OBJ: - stack.push(level); - level = new Level(level); - if(p.hasName()) { - closeTag = tag(writer,level.sbw,pretty,pretty,p.name,null); - } else if(root!=null && stack.size()==1) { // first Object - closeTag = tag(writer,level.sbw,pretty,pretty,root,null); - // Write Root Props - for(Prop prop : props) { - attrib(writer,pretty,prop.tag, prop.value,level); - } - } - if(pretty)ipw.inc(); - break; - case Parse.END_OBJ: - if(p.hasData()) - closeTag = tag(writer,writer,pretty,false,p.name, XmlEscape.convert(p.sb)); - if(pretty)ipw.dec(); - writer.append(level.sbw.getBuffer()); - level = stack.pop(); - break; - case Parse.START_ARRAY: - level.multi = p.name; - break; - case Parse.END_ARRAY: - if(p.hasData()) - closeTag = tag(writer,writer,pretty,false, p.name, XmlEscape.convert(p.sb)); - level.multi=null; - break; - case Parse.ATTRIB: - if(p.hasData()) - attrib(writer,pretty,p.name, XmlEscape.convert(p.sb), level); - break; - case Parse.NEXT: - if(p.hasData()) - closeTag = tag(writer,writer,pretty, false,p.name, XmlEscape.convert(p.sb)); - break; - } - } - writer.append(level.sbw.getBuffer()); - writer.flush(); - } - - private class Level { - public final StringBuilderWriter sbw; - public String multi; - private Level prev; - private Map nses; - - public Level(Level level) { - sbw = new StringBuilderWriter(); - multi = null; - prev = level; - } + public OutXML(String root, String ... params) { + this.root = root; + props = new ArrayList<>(); + for(String p : params) { + String[] tv=p.split("="); + if(tv.length==2) + props.add(new Prop(tv[0],tv[1])); + } + } + + public OutXML(JaxInfo jaxInfo) { + this(jaxInfo.name,genNS(jaxInfo)); + } + + public OutXML(InXML inXML) { + this(inXML.jaxInfo.name,genNS(inXML.jaxInfo)); + } + + private static String[] genNS(JaxInfo jaxInfo) { + return new String[] {"xmlns=" + jaxInfo.ns}; + } + + + @Override + public void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { + Parsed p = prs.newParsed(); + Stack stack = new Stack(); + // If it's an IndentPrintWriter, it is pretty printing. + boolean pretty = (options.length>0&&options[0]); + + IndentPrintWriter ipw; + if(pretty) { + if(writer instanceof IndentPrintWriter) { + ipw = (IndentPrintWriter)writer; + } else { + writer = ipw = new IndentPrintWriter(writer); + } + } else { + ipw=null; + } + boolean closeTag = false; + Level level = new Level(null); + while((p = prs.parse(in,p.reuse())).valid()) { + if(!p.hasName() && level.multi!=null) { + p.name=level.multi; + } + if(closeTag && p.event!=Parse.ATTRIB) { + writer.append('>'); + if(pretty)writer.append('\n'); + closeTag = false; + } + switch(p.event) { + case Parse.START_DOC: + if(!(options.length>1&&options[1])) // if not a fragment, print XML Info data + if(pretty)ipw.println(XML_INFO); + else writer.append(XML_INFO); + break; + case Parse.END_DOC: + break; + case Parse.START_OBJ: + stack.push(level); + level = new Level(level); + if(p.hasName()) { + closeTag = tag(writer,level.sbw,pretty,pretty,p.name,null); + } else if(root!=null && stack.size()==1) { // first Object + closeTag = tag(writer,level.sbw,pretty,pretty,root,null); + // Write Root Props + for(Prop prop : props) { + attrib(writer,pretty,prop.tag, prop.value,level); + } + } + if(pretty)ipw.inc(); + break; + case Parse.END_OBJ: + if(p.hasData()) + closeTag = tag(writer,writer,pretty,false,p.name, XmlEscape.convert(p.sb)); + if(pretty)ipw.dec(); + writer.append(level.sbw.getBuffer()); + level = stack.pop(); + break; + case Parse.START_ARRAY: + level.multi = p.name; + break; + case Parse.END_ARRAY: + if(p.hasData()) + closeTag = tag(writer,writer,pretty,false, p.name, XmlEscape.convert(p.sb)); + level.multi=null; + break; + case Parse.ATTRIB: + if(p.hasData()) + attrib(writer,pretty,p.name, XmlEscape.convert(p.sb), level); + break; + case Parse.NEXT: + if(p.hasData()) + closeTag = tag(writer,writer,pretty, false,p.name, XmlEscape.convert(p.sb)); + break; + } + } + writer.append(level.sbw.getBuffer()); + writer.flush(); + } + + private class Level { + public final StringBuilderWriter sbw; + public String multi; + private Level prev; + private Map nses; + + public Level(Level level) { + sbw = new StringBuilderWriter(); + multi = null; + prev = level; + } - public boolean hasPrinted(String ns, String value, boolean create) { - boolean rv = false; - if(nses==null) { - if(prev!=null)rv = prev.hasPrinted(ns, value, false); - } else { - String v = nses.get(ns); - return value.equals(v); // note: accomodates not finding NS as well - } - - if(create && !rv) { - if(nses == null) nses = new HashMap<>(); - nses.put(ns, value); - } - return rv; - } - - - - } - - private boolean tag(Writer fore, Writer aft, boolean pretty, boolean returns, String tag, String data) throws IOException { - fore.append('<'); - fore.append(tag); - if(data!=null) { - fore.append('>'); // if no data, it may need some attributes... - fore.append(data); - if(returns)fore.append('\n'); - } - aft.append(""); - if(pretty)aft.append('\n'); - return data==null; - } - - private void attrib(Writer fore, boolean pretty, String tag, String value, Level level) throws IOException { - String realTag = tag.startsWith("__")?tag.substring(2):tag; // remove __ - if(realTag.equals(Parsed.EXTENSION_TAG)) { // Convert Derived name into XML defined Inheritance - fore.append(" xsi:type=\""); - fore.append(value); - fore.append('"'); - if(!level.hasPrinted(XMLNS_XSI, XML_SCHEMA_INSTANCE,true)) { - fore.append(' '); - fore.append(XMLNS_XSI); - fore.append("=\""); - fore.append(XML_SCHEMA_INSTANCE); - fore.append("\""); - } - } else { - if(realTag.startsWith("xmlns:") ) { - if(level.hasPrinted(realTag, value, true)) { - return; - } - } - fore.append(' '); - fore.append(realTag); - fore.append("=\""); - fore.append(value); - fore.append('"'); - } - } + public boolean hasPrinted(String ns, String value, boolean create) { + boolean rv = false; + if(nses==null) { + if(prev!=null)rv = prev.hasPrinted(ns, value, false); + } else { + String v = nses.get(ns); + return value.equals(v); // note: accomodates not finding NS as well + } + + if(create && !rv) { + if(nses == null) nses = new HashMap<>(); + nses.put(ns, value); + } + return rv; + } + + + + } + + private boolean tag(Writer fore, Writer aft, boolean pretty, boolean returns, String tag, String data) throws IOException { + fore.append('<'); + fore.append(tag); + if(data!=null) { + fore.append('>'); // if no data, it may need some attributes... + fore.append(data); + if(returns)fore.append('\n'); + } + aft.append(""); + if(pretty)aft.append('\n'); + return data==null; + } + + private void attrib(Writer fore, boolean pretty, String tag, String value, Level level) throws IOException { + String realTag = tag.startsWith("__")?tag.substring(2):tag; // remove __ + if(realTag.equals(Parsed.EXTENSION_TAG)) { // Convert Derived name into XML defined Inheritance + fore.append(" xsi:type=\""); + fore.append(value); + fore.append('"'); + if(!level.hasPrinted(XMLNS_XSI, XML_SCHEMA_INSTANCE,true)) { + fore.append(' '); + fore.append(XMLNS_XSI); + fore.append("=\""); + fore.append(XML_SCHEMA_INSTANCE); + fore.append("\""); + } + } else { + if(realTag.startsWith("xmlns:") ) { + if(level.hasPrinted(realTag, value, true)) { + return; + } + } + fore.append(' '); + fore.append(realTag); + fore.append("=\""); + fore.append(value); + fore.append('"'); + } + } - @Override - public String logName() { - return "Rosetta XML"; - } + @Override + public String logName() { + return "Rosetta XML"; + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parse.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parse.java index 657baf5c..d068530c 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parse.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parse.java @@ -25,21 +25,21 @@ import org.onap.aaf.misc.env.Env; import org.onap.aaf.misc.env.TimeTaken; public interface Parse { - public Parsed parse(IN in, Parsed parsed) throws ParseException; - - // EVENTS - public static final char NONE = 0; - public static final char START_DOC = 1; - public static final char END_DOC = 2; - public static final char ATTRIB = 3; - - public static final char NEXT = ','; - public static final char START_OBJ = '{'; - public static final char END_OBJ = '}'; - public static final char START_ARRAY = '['; - public static final char END_ARRAY = ']'; - - public Parsed newParsed() throws ParseException; - public TimeTaken start(Env env); - + public Parsed parse(IN in, Parsed parsed) throws ParseException; + + // EVENTS + public static final char NONE = 0; + public static final char START_DOC = 1; + public static final char END_DOC = 2; + public static final char ATTRIB = 3; + + public static final char NEXT = ','; + public static final char START_OBJ = '{'; + public static final char END_OBJ = '}'; + public static final char START_ARRAY = '['; + public static final char END_ARRAY = ']'; + + public Parsed newParsed() throws ParseException; + public TimeTaken start(Env env); + } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/ParseException.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/ParseException.java index d986776d..38ea956a 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/ParseException.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/ParseException.java @@ -22,21 +22,21 @@ package org.onap.aaf.misc.rosetta; public class ParseException extends Exception { - private static final long serialVersionUID = 7808836939102997012L; + private static final long serialVersionUID = 7808836939102997012L; - public ParseException() { - } + public ParseException() { + } - public ParseException(String message) { - super(message); - } + public ParseException(String message) { + super(message); + } - public ParseException(Throwable cause) { - super(cause); - } + public ParseException(Throwable cause) { + super(cause); + } - public ParseException(String message, Throwable cause) { - super(message, cause); - } + public ParseException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java index 326c5bba..a4c679db 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java @@ -23,67 +23,67 @@ package org.onap.aaf.misc.rosetta; public class Parsed { - public static final String EXTENSION_TAG="extension"; - - public boolean isString; - - public StringBuilder sb; - public char event; - public String name; - public S state; + public static final String EXTENSION_TAG="extension"; + + public boolean isString; + + public StringBuilder sb; + public char event; + public String name; + public S state; - public Parsed() { - this(null); - } + public Parsed() { + this(null); + } - // Package on purpose - Parsed(S theState) { - sb = new StringBuilder(); - isString = false; - event = Parse.NONE; - name = ""; - state = theState; - } + // Package on purpose + Parsed(S theState) { + sb = new StringBuilder(); + isString = false; + event = Parse.NONE; + name = ""; + state = theState; + } - public boolean valid() { - return event!=Parse.NONE; - } - - public Parsed reuse() { - isString=false; - sb.setLength(0); - event = Parse.NONE; - name = ""; - // don't touch T... - return this; - } + public boolean valid() { + return event!=Parse.NONE; + } + + public Parsed reuse() { + isString=false; + sb.setLength(0); + event = Parse.NONE; + name = ""; + // don't touch T... + return this; + } - public void dataIsName() { - name = sb.toString(); - sb.setLength(0); - } + public void dataIsName() { + name = sb.toString(); + sb.setLength(0); + } - public boolean hasName() { - return name.length()>0; - } + public boolean hasName() { + return name.length()>0; + } - public boolean hasData() { - return sb.length()>0; - } - - public String toString() { - StringBuilder sb2 = new StringBuilder(); - if(event<40)sb2.append((int)event); - else sb2.append(event); - sb2.append(" - "); - sb2.append(name); - if(sb.length()>0) { - sb2.append(" : "); - if(isString)sb2.append('"'); - sb2.append(sb); - if(isString)sb2.append('"'); - } - return sb2.toString(); - } + public boolean hasData() { + return sb.length()>0; + } + + public String toString() { + StringBuilder sb2 = new StringBuilder(); + if(event<40)sb2.append((int)event); + else sb2.append(event); + sb2.append(" - "); + sb2.append(name); + if(sb.length()>0) { + sb2.append(" : "); + if(isString)sb2.append('"'); + sb2.append(sb); + if(isString)sb2.append('"'); + } + return sb2.toString(); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java index 07bd40f0..ae9c8934 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java @@ -22,22 +22,22 @@ package org.onap.aaf.misc.rosetta; class Prop { - public String tag; - public String value; - public Prop(String t, String v) { - tag = t; - value =v; - } - - public Prop(String t_equals_v) { - String[] tv = t_equals_v.split("="); - if(tv.length>1) { - tag = tv[0]; - value = tv[1]; - } - } + public String tag; + public String value; + public Prop(String t, String v) { + tag = t; + value =v; + } + + public Prop(String t_equals_v) { + String[] tv = t_equals_v.split("="); + if(tv.length>1) { + tag = tv[0]; + value = tv[1]; + } + } - public String toString() { - return tag + '=' + value; - } + public String toString() { + return tag + '=' + value; + } } \ No newline at end of file diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java index 45c27052..a596b705 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java @@ -38,157 +38,157 @@ import org.onap.aaf.misc.rosetta.Saved.State; * */ public class Saved extends Out implements Parse{ - private static final String ROSETTA_SAVED = "Rosetta Saved"; - private final static int INIT_SIZE=128; - private Content content[]; - private int idx; - private boolean append = false; - - /** - * Read from Parsed Stream and save - */ - // @Override - public void extract(IN in, Writer ignore, Parse parser, boolean ... options) throws IOException, ParseException { - Parsed p = parser.newParsed(); - if(!append) { - // reuse array if not too big - if(content==null||content.length>INIT_SIZE*3) { - content = new Content[INIT_SIZE]; - idx = -1; - } else do { - content[idx]=null; - } while(--idx>=0); - } - - // Note: idx needs to be -1 on initialization and no appendages - while((p = parser.parse(in,p.reuse())).valid()) { - if(!(append && (p.event==START_DOC || p.event==END_DOC))) { // skip any start/end of document in appendages - if(++idx>=content.length) { - Content temp[] = new Content[content.length*2]; - System.arraycopy(content, 0, temp, 0, idx); - content = temp; - } - content[idx]= new Content(p); - } - } - } - - // @Override - public Parsed parse(Reader ignore, Parsed parsed) throws ParseException { - int i; - if((i=parsed.state.count++)<=idx) - content[i].load(parsed); - else - parsed.event = Parse.NONE; - return parsed; - } + private static final String ROSETTA_SAVED = "Rosetta Saved"; + private final static int INIT_SIZE=128; + private Content content[]; + private int idx; + private boolean append = false; + + /** + * Read from Parsed Stream and save + */ + // @Override + public void extract(IN in, Writer ignore, Parse parser, boolean ... options) throws IOException, ParseException { + Parsed p = parser.newParsed(); + if(!append) { + // reuse array if not too big + if(content==null||content.length>INIT_SIZE*3) { + content = new Content[INIT_SIZE]; + idx = -1; + } else do { + content[idx]=null; + } while(--idx>=0); + } + + // Note: idx needs to be -1 on initialization and no appendages + while((p = parser.parse(in,p.reuse())).valid()) { + if(!(append && (p.event==START_DOC || p.event==END_DOC))) { // skip any start/end of document in appendages + if(++idx>=content.length) { + Content temp[] = new Content[content.length*2]; + System.arraycopy(content, 0, temp, 0, idx); + content = temp; + } + content[idx]= new Content(p); + } + } + } + + // @Override + public Parsed parse(Reader ignore, Parsed parsed) throws ParseException { + int i; + if((i=parsed.state.count++)<=idx) + content[i].load(parsed); + else + parsed.event = Parse.NONE; + return parsed; + } - public Content[] cut(char event, int count) { - append = true; - for(int i=idx;i>=0;--i) { - if(content[i].event==event) count--; - if(count==0) { - Content[] appended = new Content[idx-i+1]; - System.arraycopy(content, i, appended, 0, appended.length); - idx = i-1; - return appended; - } - } - return new Content[0]; - } + public Content[] cut(char event, int count) { + append = true; + for(int i=idx;i>=0;--i) { + if(content[i].event==event) count--; + if(count==0) { + Content[] appended = new Content[idx-i+1]; + System.arraycopy(content, i, appended, 0, appended.length); + idx = i-1; + return appended; + } + } + return new Content[0]; + } - public void paste(Content[] appended) { - if(appended!=null) { - if(idx+appended.length>content.length) { - Content temp[] = new Content[content.length*2]; - System.arraycopy(content, 0, temp, 0, idx); - content = temp; - } - System.arraycopy(appended,0,content,idx+1,appended.length); - idx+=appended.length; - } - this.append = false; - } + public void paste(Content[] appended) { + if(appended!=null) { + if(idx+appended.length>content.length) { + Content temp[] = new Content[content.length*2]; + System.arraycopy(content, 0, temp, 0, idx); + content = temp; + } + System.arraycopy(appended,0,content,idx+1,appended.length); + idx+=appended.length; + } + this.append = false; + } - public static class State { - public int count = 0; - } - - public static class Content { - private boolean isString; - private char event; - private String name; - private List props; - private String str; - - public Content(Parsed p) { - isString = p.isString; - event = p.event; - name = p.name; - // avoid copying, because most elements don't have content - // Cannot set to "equals", because sb ends up being cleared (and reused) - str = p.sb.length()==0?null:p.sb.toString(); - } + public static class State { + public int count = 0; + } + + public static class Content { + private boolean isString; + private char event; + private String name; + private List props; + private String str; + + public Content(Parsed p) { + isString = p.isString; + event = p.event; + name = p.name; + // avoid copying, because most elements don't have content + // Cannot set to "equals", because sb ends up being cleared (and reused) + str = p.sb.length()==0?null:p.sb.toString(); + } - public void load(Parsed p) { - p.isString = isString; - p.event = event; - p.name = name; - if(str!=null) - p.sb.append(str); - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(event); - sb.append(" - "); - sb.append(name); - sb.append(": "); - if(isString)sb.append('"'); - sb.append(str); - if(isString)sb.append('"'); - sb.append(' '); - if(props!=null) { - boolean comma = false; - for(Prop prop : props) { - if(comma)sb.append(','); - else comma = true; - sb.append(prop.tag); - sb.append('='); - sb.append(prop.value); - } - } - return sb.toString(); - } - } - - //// @Override - public Parsed newParsed() { - Parsed ps = new Parsed(new State()); - return ps; - } + public void load(Parsed p) { + p.isString = isString; + p.event = event; + p.name = name; + if(str!=null) + p.sb.append(str); + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(event); + sb.append(" - "); + sb.append(name); + sb.append(": "); + if(isString)sb.append('"'); + sb.append(str); + if(isString)sb.append('"'); + sb.append(' '); + if(props!=null) { + boolean comma = false; + for(Prop prop : props) { + if(comma)sb.append(','); + else comma = true; + sb.append(prop.tag); + sb.append('='); + sb.append(prop.value); + } + } + return sb.toString(); + } + } + + //// @Override + public Parsed newParsed() { + Parsed ps = new Parsed(new State()); + return ps; + } - /** - * Convenience function - * @param rdr - * @param in - * @throws IOException - * @throws ParseException - */ - public void load(IN in, Parse parser) throws IOException, ParseException { - extract(in,(Writer)null, parser); - } + /** + * Convenience function + * @param rdr + * @param in + * @throws IOException + * @throws ParseException + */ + public void load(IN in, Parse parser) throws IOException, ParseException { + extract(in,(Writer)null, parser); + } - // @Override - public TimeTaken start(Env env) { - return env.start(ROSETTA_SAVED, 0); - } - - @Override - public String logName() { - return ROSETTA_SAVED; - } + // @Override + public TimeTaken start(Env env) { + return env.start(ROSETTA_SAVED, 0); + } + + @Override + public String logName() { + return ROSETTA_SAVED; + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java index aac1e30f..1b0eec07 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java @@ -27,345 +27,345 @@ import java.util.Map.Entry; import java.util.TreeMap; public class XmlEscape { - private XmlEscape() {} - - private static final TreeMap charMap; // see initialization at end - private static final TreeMap intMap; // see initialization at end + private XmlEscape() {} + + private static final TreeMap charMap; // see initialization at end + private static final TreeMap intMap; // see initialization at end - public static void xmlEscape(StringBuilder sb, Reader r) throws ParseException { - try { - int c; - StringBuilder esc = new StringBuilder(); - for(int cnt = 0;cnt<9 /*max*/; ++cnt) { - if((c=r.read())<0)throw new ParseException("Invalid Data: Unfinished Escape Sequence"); - if(c!=';') { - esc.append((char)c); - } else { // evaluate - Integer i = charMap.get(esc.toString()); - if(i==null) { - // leave in nasty XML format for now. - sb.append('&'); - sb.append(esc); - sb.append(';'); - } else { - sb.append((char)i.intValue()); - } - break; - } - } - - - } catch (IOException e) { - throw new ParseException(e); - } - } - - public static void xmlEscape(StringBuilder sb, int chr) { - sb.append('&'); - sb.append(intMap.get(chr)); - sb.append(';'); - } - - public static String convert(StringBuilder insb) { - int idx, ch; - StringBuilder sb=null; - for(idx=0;idx=160 || ch==34 || ch==38 || ch==39 || ch==60 || ch==62) { - sb = new StringBuilder(); - sb.append(insb,0,idx); - break; - } - } - - if(sb==null)return insb.toString(); - - for(int i=idx;i=160 || ch==34 || ch==38 || ch==39 || ch==60 || ch==62) { + sb = new StringBuilder(); + sb.append(insb,0,idx); + break; + } + } + + if(sb==null)return insb.toString(); + + for(int i=idx;i(); - intMap = new TreeMap<>(); - charMap.put("quot", 34); - charMap.put("amp",38); - charMap.put("apos",39); - charMap.put("lt",60); - charMap.put("gt",62); - charMap.put("nbsp",160); - charMap.put("iexcl",161); - charMap.put("cent",162); - charMap.put("pound",163); - charMap.put("curren",164); - charMap.put("yen",165); - charMap.put("brvbar",166); - charMap.put("sect",167); - charMap.put("uml",168); - charMap.put("copy",169); - charMap.put("ordf",170); - charMap.put("laquo",171); - charMap.put("not",172); - charMap.put("shy",173); - charMap.put("reg",174); - charMap.put("macr",175); - charMap.put("deg",176); - charMap.put("plusmn",177); - charMap.put("sup2",178); - charMap.put("sup3",179); - charMap.put("acute",180); - charMap.put("micro",181); - charMap.put("para",182); - charMap.put("middot",183); - charMap.put("cedil",184); - charMap.put("sup1",185); - charMap.put("ordm",186); - charMap.put("raquo",187); - charMap.put("frac14",188); - charMap.put("frac12",189); - charMap.put("frac34",190); - charMap.put("iquest",191); - charMap.put("Agrave",192); - charMap.put("Aacute",193); - charMap.put("Acirc",194); - charMap.put("Atilde",195); - charMap.put("Auml",196); - charMap.put("Aring",197); - charMap.put("AElig",198); - charMap.put("Ccedil",199); - charMap.put("Egrave",200); - charMap.put("Eacute",201); - charMap.put("Ecirc",202); - charMap.put("Euml",203); - charMap.put("Igrave",204); - charMap.put("Iacute",205); - charMap.put("Icirc",206); - charMap.put("Iuml",207); - charMap.put("ETH",208); - charMap.put("Ntilde",209); - charMap.put("Ograve",210); - charMap.put("Oacute",211); - charMap.put("Ocirc",212); - charMap.put("Otilde",213); - charMap.put("Ouml",214); - charMap.put("times",215); - charMap.put("Oslash",216); - charMap.put("Ugrave",217); - charMap.put("Uacute",218); - charMap.put("Ucirc",219); - charMap.put("Uuml",220); - charMap.put("Yacute",221); - charMap.put("THORN",222); - charMap.put("szlig",223); - charMap.put("agrave",224); - charMap.put("aacute",225); - charMap.put("acirc",226); - charMap.put("atilde",227); - charMap.put("auml",228); - charMap.put("aring",229); - charMap.put("aelig",230); - charMap.put("ccedil",231); - charMap.put("egrave",232); - charMap.put("eacute",233); - charMap.put("ecirc",234); - charMap.put("euml",235); - charMap.put("igrave",236); - charMap.put("iacute",237); - charMap.put("icirc",238); - charMap.put("iuml",239); - charMap.put("eth",240); - charMap.put("ntilde",241); - charMap.put("ograve",242); - charMap.put("oacute",243); - charMap.put("ocirc",244); - charMap.put("otilde",245); - charMap.put("ouml",246); - charMap.put("divide",247); - charMap.put("oslash",248); - charMap.put("ugrave",249); - charMap.put("uacute",250); - charMap.put("ucirc",251); - charMap.put("uuml",252); - charMap.put("yacute",253); - charMap.put("thorn",254); - charMap.put("yuml",255); - charMap.put("OElig",338); - charMap.put("oelig",339); - charMap.put("Scaron",352); - charMap.put("scaron",353); - charMap.put("Yuml",376); - charMap.put("fnof",402); - charMap.put("circ",710); - charMap.put("tilde",732); - charMap.put("Alpha",913); - charMap.put("Beta",914); - charMap.put("Gamma",915); - charMap.put("Delta",916); - charMap.put("Epsilon",917); - charMap.put("Zeta",918); - charMap.put("Eta",919); - charMap.put("Theta",920); - charMap.put("Iota",921); - charMap.put("Kappa",922); - charMap.put("Lambda",923); - charMap.put("Mu",924); - charMap.put("Nu",925); - charMap.put("Xi",926); - charMap.put("Omicron",927); - charMap.put("Pi",928); - charMap.put("Rho",929); - charMap.put("Sigma",931); - charMap.put("Tau",932); - charMap.put("Upsilon",933); - charMap.put("Phi",934); - charMap.put("Chi",935); - charMap.put("Psi",936); - charMap.put("Omega",937); - charMap.put("alpha",945); - charMap.put("beta",946); - charMap.put("gamma",947); - charMap.put("delta",948); - charMap.put("epsilon",949); - charMap.put("zeta",950); - charMap.put("eta",951); - charMap.put("theta",952); - charMap.put("iota",953); - charMap.put("kappa",954); - charMap.put("lambda",955); - charMap.put("mu",956); - charMap.put("nu",957); - charMap.put("xi",958); - charMap.put("omicron",959); - charMap.put("pi",960); - charMap.put("rho",961); - charMap.put("sigmaf",962); - charMap.put("sigma",963); - charMap.put("tau",964); - charMap.put("upsilon",965); - charMap.put("phi",966); - charMap.put("chi",967); - charMap.put("psi",968); - charMap.put("omega",969); - charMap.put("thetasym",977); - charMap.put("upsih",978); - charMap.put("piv",982); - charMap.put("ensp",8194); - charMap.put("emsp",8195); - charMap.put("thinsp",8201); - charMap.put("zwnj",8204); - charMap.put("zwj",8205); - charMap.put("lrm",8206); - charMap.put("rlm",8207); - charMap.put("ndash",8211); - charMap.put("mdash",8212); - charMap.put("lsquo",8216); - charMap.put("rsquo",8217); - charMap.put("sbquo",8218); - charMap.put("ldquo",8220); - charMap.put("rdquo",8221); - charMap.put("bdquo",8222); - charMap.put("dagger",8224); - charMap.put("Dagger",8225); - charMap.put("bull",8226); - charMap.put("hellip",8230); - charMap.put("permil",8240); - charMap.put("prime",8242); - charMap.put("Prime",8243); - charMap.put("lsaquo",8249); - charMap.put("rsaquo",8250); - charMap.put("oline",8254); - charMap.put("frasl",8260); - charMap.put("euro",8364); - charMap.put("image",8465); - charMap.put("weierp",8472); - charMap.put("real",8476); - charMap.put("trade",8482); - charMap.put("alefsym",8501); - charMap.put("larr",8592); - charMap.put("uarr",8593); - charMap.put("rarr",8594); - charMap.put("darr",8595); - charMap.put("harr",8596); - charMap.put("crarr",8629); - charMap.put("lArr",8656); - charMap.put("uArr",8657); - charMap.put("rArr",8658); - charMap.put("dArr",8659); - charMap.put("hArr",8660); - charMap.put("forall",8704); - charMap.put("part",8706); - charMap.put("exist",8707); - charMap.put("empty",8709); - charMap.put("nabla",8711); - charMap.put("isin",8712); - charMap.put("notin",8713); - charMap.put("ni",8715); - charMap.put("prod",8719); - charMap.put("sum",8721); - charMap.put("minus",8722); - charMap.put("lowast",8727); - charMap.put("radic",8730); - charMap.put("prop",8733); - charMap.put("infin",8734); - charMap.put("ang",8736); - charMap.put("and",8743); - charMap.put("or",8744); - charMap.put("cap",8745); - charMap.put("cup",8746); - charMap.put("int",8747); - charMap.put("there4",8756); - charMap.put("sim",8764); - charMap.put("cong",8773); - charMap.put("asymp",8776); - charMap.put("ne",8800); - charMap.put("equiv",8801); - charMap.put("le",8804); - charMap.put("ge",8805); - charMap.put("sub",8834); - charMap.put("sup",8835); - charMap.put("nsub",8836); - charMap.put("sube",8838); - charMap.put("supe",8839); - charMap.put("oplus",8853); - charMap.put("otimes",8855); - charMap.put("perp",8869); - charMap.put("sdot",8901); - charMap.put("lceil",8968); - charMap.put("rceil",8969); - charMap.put("lfloor",8970); - charMap.put("rfloor",8971); - charMap.put("lang",9001); - charMap.put("rang",9002); - charMap.put("loz",9674); - charMap.put("spades",9824); - charMap.put("clubs",9827); - charMap.put("hearts",9829); - charMap.put("diams",9830); - - for( Entry es: charMap.entrySet()) { - if(es.getValue()>=160); // save small space... note that no longer has amp, etc. - intMap.put(es.getValue(), es.getKey()); - } - } + static { + charMap = new TreeMap<>(); + intMap = new TreeMap<>(); + charMap.put("quot", 34); + charMap.put("amp",38); + charMap.put("apos",39); + charMap.put("lt",60); + charMap.put("gt",62); + charMap.put("nbsp",160); + charMap.put("iexcl",161); + charMap.put("cent",162); + charMap.put("pound",163); + charMap.put("curren",164); + charMap.put("yen",165); + charMap.put("brvbar",166); + charMap.put("sect",167); + charMap.put("uml",168); + charMap.put("copy",169); + charMap.put("ordf",170); + charMap.put("laquo",171); + charMap.put("not",172); + charMap.put("shy",173); + charMap.put("reg",174); + charMap.put("macr",175); + charMap.put("deg",176); + charMap.put("plusmn",177); + charMap.put("sup2",178); + charMap.put("sup3",179); + charMap.put("acute",180); + charMap.put("micro",181); + charMap.put("para",182); + charMap.put("middot",183); + charMap.put("cedil",184); + charMap.put("sup1",185); + charMap.put("ordm",186); + charMap.put("raquo",187); + charMap.put("frac14",188); + charMap.put("frac12",189); + charMap.put("frac34",190); + charMap.put("iquest",191); + charMap.put("Agrave",192); + charMap.put("Aacute",193); + charMap.put("Acirc",194); + charMap.put("Atilde",195); + charMap.put("Auml",196); + charMap.put("Aring",197); + charMap.put("AElig",198); + charMap.put("Ccedil",199); + charMap.put("Egrave",200); + charMap.put("Eacute",201); + charMap.put("Ecirc",202); + charMap.put("Euml",203); + charMap.put("Igrave",204); + charMap.put("Iacute",205); + charMap.put("Icirc",206); + charMap.put("Iuml",207); + charMap.put("ETH",208); + charMap.put("Ntilde",209); + charMap.put("Ograve",210); + charMap.put("Oacute",211); + charMap.put("Ocirc",212); + charMap.put("Otilde",213); + charMap.put("Ouml",214); + charMap.put("times",215); + charMap.put("Oslash",216); + charMap.put("Ugrave",217); + charMap.put("Uacute",218); + charMap.put("Ucirc",219); + charMap.put("Uuml",220); + charMap.put("Yacute",221); + charMap.put("THORN",222); + charMap.put("szlig",223); + charMap.put("agrave",224); + charMap.put("aacute",225); + charMap.put("acirc",226); + charMap.put("atilde",227); + charMap.put("auml",228); + charMap.put("aring",229); + charMap.put("aelig",230); + charMap.put("ccedil",231); + charMap.put("egrave",232); + charMap.put("eacute",233); + charMap.put("ecirc",234); + charMap.put("euml",235); + charMap.put("igrave",236); + charMap.put("iacute",237); + charMap.put("icirc",238); + charMap.put("iuml",239); + charMap.put("eth",240); + charMap.put("ntilde",241); + charMap.put("ograve",242); + charMap.put("oacute",243); + charMap.put("ocirc",244); + charMap.put("otilde",245); + charMap.put("ouml",246); + charMap.put("divide",247); + charMap.put("oslash",248); + charMap.put("ugrave",249); + charMap.put("uacute",250); + charMap.put("ucirc",251); + charMap.put("uuml",252); + charMap.put("yacute",253); + charMap.put("thorn",254); + charMap.put("yuml",255); + charMap.put("OElig",338); + charMap.put("oelig",339); + charMap.put("Scaron",352); + charMap.put("scaron",353); + charMap.put("Yuml",376); + charMap.put("fnof",402); + charMap.put("circ",710); + charMap.put("tilde",732); + charMap.put("Alpha",913); + charMap.put("Beta",914); + charMap.put("Gamma",915); + charMap.put("Delta",916); + charMap.put("Epsilon",917); + charMap.put("Zeta",918); + charMap.put("Eta",919); + charMap.put("Theta",920); + charMap.put("Iota",921); + charMap.put("Kappa",922); + charMap.put("Lambda",923); + charMap.put("Mu",924); + charMap.put("Nu",925); + charMap.put("Xi",926); + charMap.put("Omicron",927); + charMap.put("Pi",928); + charMap.put("Rho",929); + charMap.put("Sigma",931); + charMap.put("Tau",932); + charMap.put("Upsilon",933); + charMap.put("Phi",934); + charMap.put("Chi",935); + charMap.put("Psi",936); + charMap.put("Omega",937); + charMap.put("alpha",945); + charMap.put("beta",946); + charMap.put("gamma",947); + charMap.put("delta",948); + charMap.put("epsilon",949); + charMap.put("zeta",950); + charMap.put("eta",951); + charMap.put("theta",952); + charMap.put("iota",953); + charMap.put("kappa",954); + charMap.put("lambda",955); + charMap.put("mu",956); + charMap.put("nu",957); + charMap.put("xi",958); + charMap.put("omicron",959); + charMap.put("pi",960); + charMap.put("rho",961); + charMap.put("sigmaf",962); + charMap.put("sigma",963); + charMap.put("tau",964); + charMap.put("upsilon",965); + charMap.put("phi",966); + charMap.put("chi",967); + charMap.put("psi",968); + charMap.put("omega",969); + charMap.put("thetasym",977); + charMap.put("upsih",978); + charMap.put("piv",982); + charMap.put("ensp",8194); + charMap.put("emsp",8195); + charMap.put("thinsp",8201); + charMap.put("zwnj",8204); + charMap.put("zwj",8205); + charMap.put("lrm",8206); + charMap.put("rlm",8207); + charMap.put("ndash",8211); + charMap.put("mdash",8212); + charMap.put("lsquo",8216); + charMap.put("rsquo",8217); + charMap.put("sbquo",8218); + charMap.put("ldquo",8220); + charMap.put("rdquo",8221); + charMap.put("bdquo",8222); + charMap.put("dagger",8224); + charMap.put("Dagger",8225); + charMap.put("bull",8226); + charMap.put("hellip",8230); + charMap.put("permil",8240); + charMap.put("prime",8242); + charMap.put("Prime",8243); + charMap.put("lsaquo",8249); + charMap.put("rsaquo",8250); + charMap.put("oline",8254); + charMap.put("frasl",8260); + charMap.put("euro",8364); + charMap.put("image",8465); + charMap.put("weierp",8472); + charMap.put("real",8476); + charMap.put("trade",8482); + charMap.put("alefsym",8501); + charMap.put("larr",8592); + charMap.put("uarr",8593); + charMap.put("rarr",8594); + charMap.put("darr",8595); + charMap.put("harr",8596); + charMap.put("crarr",8629); + charMap.put("lArr",8656); + charMap.put("uArr",8657); + charMap.put("rArr",8658); + charMap.put("dArr",8659); + charMap.put("hArr",8660); + charMap.put("forall",8704); + charMap.put("part",8706); + charMap.put("exist",8707); + charMap.put("empty",8709); + charMap.put("nabla",8711); + charMap.put("isin",8712); + charMap.put("notin",8713); + charMap.put("ni",8715); + charMap.put("prod",8719); + charMap.put("sum",8721); + charMap.put("minus",8722); + charMap.put("lowast",8727); + charMap.put("radic",8730); + charMap.put("prop",8733); + charMap.put("infin",8734); + charMap.put("ang",8736); + charMap.put("and",8743); + charMap.put("or",8744); + charMap.put("cap",8745); + charMap.put("cup",8746); + charMap.put("int",8747); + charMap.put("there4",8756); + charMap.put("sim",8764); + charMap.put("cong",8773); + charMap.put("asymp",8776); + charMap.put("ne",8800); + charMap.put("equiv",8801); + charMap.put("le",8804); + charMap.put("ge",8805); + charMap.put("sub",8834); + charMap.put("sup",8835); + charMap.put("nsub",8836); + charMap.put("sube",8838); + charMap.put("supe",8839); + charMap.put("oplus",8853); + charMap.put("otimes",8855); + charMap.put("perp",8869); + charMap.put("sdot",8901); + charMap.put("lceil",8968); + charMap.put("rceil",8969); + charMap.put("lfloor",8970); + charMap.put("rfloor",8971); + charMap.put("lang",9001); + charMap.put("rang",9002); + charMap.put("loz",9674); + charMap.put("spades",9824); + charMap.put("clubs",9827); + charMap.put("hearts",9829); + charMap.put("diams",9830); + + for( Entry es: charMap.entrySet()) { + if(es.getValue()>=160); // save small space... note that no longer has amp, etc. + intMap.put(es.getValue(), es.getKey()); + } + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java index 68baebb6..69926974 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java @@ -56,210 +56,210 @@ import org.onap.aaf.misc.rosetta.ParseException; import org.onap.aaf.misc.rosetta.marshal.DocMarshal; public class RosettaDF extends BaseDataFactory implements DataFactory { - - static InJson inJSON = new InJson(); - InXML inXML; + + static InJson inJSON = new InJson(); + InXML inXML; - static OutJson outJSON = new OutJson(); - OutXML outXML; - static OutRaw outRAW = new OutRaw(); - - // Temporary until we write JAXB impl... - JAXBmar jaxMar; - JAXBumar jaxUmar; - - private Parse defaultIn; - private Out defaultOut; - private RosettaEnv env; - private TYPE inType; - private TYPE outType; - private int defOption; - Marshal marshal = null; - + static OutJson outJSON = new OutJson(); + OutXML outXML; + static OutRaw outRAW = new OutRaw(); + + // Temporary until we write JAXB impl... + JAXBmar jaxMar; + JAXBumar jaxUmar; + + private Parse defaultIn; + private Out defaultOut; + private RosettaEnv env; + private TYPE inType; + private TYPE outType; + private int defOption; + Marshal marshal = null; + - /** - * Private constructor to setup Type specific data manipulators - * @param schema - * @param rootNs - * @param cls - * @throws SecurityException - * @throws NoSuchFieldException - * @throws ClassNotFoundException - * @throws ParseException - * @throws JAXBException - */ - // package on purpose - RosettaDF(RosettaEnv env, Schema schema, String rootNs, Class cls) throws APIException { - this.env = env; - try { - // Note: rootNs can be null, in order to derive content from Class. - JaxInfo ji = rootNs==null?JaxInfo.build(cls):JaxInfo.build(cls,rootNs); - // Note: JAXBmar sets qname to null if not exists - jaxMar = new JAXBmar(rootNs==null?null:new QName("xmlns",rootNs),cls); - // Note: JAXBumar sets schema to null if not exists - jaxUmar = new JAXBumar(schema, cls); - - defaultIn = inXML = new InXML(ji); - defaultOut = outXML = new OutXML(ji); - inType=outType=Data.TYPE.XML; - defOption = 0; - } catch (Exception e) { - throw new APIException(e); - } - } - + /** + * Private constructor to setup Type specific data manipulators + * @param schema + * @param rootNs + * @param cls + * @throws SecurityException + * @throws NoSuchFieldException + * @throws ClassNotFoundException + * @throws ParseException + * @throws JAXBException + */ + // package on purpose + RosettaDF(RosettaEnv env, Schema schema, String rootNs, Class cls) throws APIException { + this.env = env; + try { + // Note: rootNs can be null, in order to derive content from Class. + JaxInfo ji = rootNs==null?JaxInfo.build(cls):JaxInfo.build(cls,rootNs); + // Note: JAXBmar sets qname to null if not exists + jaxMar = new JAXBmar(rootNs==null?null:new QName("xmlns",rootNs),cls); + // Note: JAXBumar sets schema to null if not exists + jaxUmar = new JAXBumar(schema, cls); + + defaultIn = inXML = new InXML(ji); + defaultOut = outXML = new OutXML(ji); + inType=outType=Data.TYPE.XML; + defOption = 0; + } catch (Exception e) { + throw new APIException(e); + } + } + - // @Override - public RosettaData newData() { - RosettaData data = new RosettaData(env, this) - .in(inType) - .out(outType) - .option(defOption); - return data; - } + // @Override + public RosettaData newData() { + RosettaData data = new RosettaData(env, this) + .in(inType) + .out(outType) + .option(defOption); + return data; + } - // @Override - public RosettaData newData(Env trans) { - RosettaData data = new RosettaData(trans, this) - .in(inType) - .out(outType) - .option(defOption); - return data; - } + // @Override + public RosettaData newData(Env trans) { + RosettaData data = new RosettaData(trans, this) + .in(inType) + .out(outType) + .option(defOption); + return data; + } - @SuppressWarnings("unchecked") - // @Override - public Class getTypeClass() { - return (Class)jaxMar.getMarshalClass(); - } + @SuppressWarnings("unchecked") + // @Override + public Class getTypeClass() { + return (Class)jaxMar.getMarshalClass(); + } - public RosettaDF in(Data.TYPE type) { - inType = type; - defaultIn=getIn(type==Data.TYPE.DEFAULT?Data.TYPE.JSON:type); - return this; - } + public RosettaDF in(Data.TYPE type) { + inType = type; + defaultIn=getIn(type==Data.TYPE.DEFAULT?Data.TYPE.JSON:type); + return this; + } - /** - * If exists, first option is "Pretty", second is "Fragment" - * - * @param options - * @return - */ - public RosettaDF out(Data.TYPE type) { - outType = type; - defaultOut = getOut(type==Data.TYPE.DEFAULT?Data.TYPE.JSON:type); - return this; - } - - public Parse getIn(Data.TYPE type) { - switch(type) { - case DEFAULT: - return defaultIn; - case JSON: - return inJSON; - case XML: - return inXML; - default: - return defaultIn; - } - } - - public Out getOut(Data.TYPE type) { - switch(type) { - case DEFAULT: - return defaultOut; - case JSON: - return outJSON; - case XML: - return outXML; - case RAW: - return outRAW; - default: - return defaultOut; - } - } - - public int logType(org.onap.aaf.misc.env.Data.TYPE ot) { - switch(ot) { - case JSON: - return Env.JSON; - default: - return Env.XML; - } - } + /** + * If exists, first option is "Pretty", second is "Fragment" + * + * @param options + * @return + */ + public RosettaDF out(Data.TYPE type) { + outType = type; + defaultOut = getOut(type==Data.TYPE.DEFAULT?Data.TYPE.JSON:type); + return this; + } + + public Parse getIn(Data.TYPE type) { + switch(type) { + case DEFAULT: + return defaultIn; + case JSON: + return inJSON; + case XML: + return inXML; + default: + return defaultIn; + } + } + + public Out getOut(Data.TYPE type) { + switch(type) { + case DEFAULT: + return defaultOut; + case JSON: + return outJSON; + case XML: + return outXML; + case RAW: + return outRAW; + default: + return defaultOut; + } + } + + public int logType(org.onap.aaf.misc.env.Data.TYPE ot) { + switch(ot) { + case JSON: + return Env.JSON; + default: + return Env.XML; + } + } - public RosettaEnv getEnv() { - return env; - } + public RosettaEnv getEnv() { + return env; + } - public Data.TYPE getInType() { - return inType; - } + public Data.TYPE getInType() { + return inType; + } - public Data.TYPE getOutType() { - return outType; - } + public Data.TYPE getOutType() { + return outType; + } - public RosettaDF option(int option) { - defOption = option; - - return this; - } + public RosettaDF option(int option) { + defOption = option; + + return this; + } - /** - * Assigning Root Marshal Object - * - * Will wrap with DocMarshal Object if not already - * - * @param marshal - * @return - */ - public RosettaDF rootMarshal(Marshal marshal) { - if(marshal instanceof DocMarshal) { - this.marshal = marshal; - } else { - this.marshal = DocMarshal.root(marshal); - } - return this; - } - - public void direct(Trans trans, T t, OutputStream os, boolean ... options) throws APIException, IOException { - Out out = getOut(outType); - TimeTaken tt = trans.start(out.logName(),logType(outType)); // determine from Out.. without dependency on Env? - try { - if(marshal==null) { // Unknown marshaller... do working XML marshal/extraction - StringWriter sw = new StringWriter(); - jaxMar.marshal(trans.debug(), t, sw, options); - out.extract(new StringReader(sw.toString()), new OutputStreamWriter(os), inXML,options); - } else { - out.extract(t, new OutputStreamWriter(os), marshal,options); - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - } + /** + * Assigning Root Marshal Object + * + * Will wrap with DocMarshal Object if not already + * + * @param marshal + * @return + */ + public RosettaDF rootMarshal(Marshal marshal) { + if(marshal instanceof DocMarshal) { + this.marshal = marshal; + } else { + this.marshal = DocMarshal.root(marshal); + } + return this; + } + + public void direct(Trans trans, T t, OutputStream os, boolean ... options) throws APIException, IOException { + Out out = getOut(outType); + TimeTaken tt = trans.start(out.logName(),logType(outType)); // determine from Out.. without dependency on Env? + try { + if(marshal==null) { // Unknown marshaller... do working XML marshal/extraction + StringWriter sw = new StringWriter(); + jaxMar.marshal(trans.debug(), t, sw, options); + out.extract(new StringReader(sw.toString()), new OutputStreamWriter(os), inXML,options); + } else { + out.extract(t, new OutputStreamWriter(os), marshal,options); + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + } - public void direct(Trans trans, T t, Writer writer, boolean ... options) throws APIException, IOException { - Out out = getOut(outType); - TimeTaken tt = trans.start(out.logName(),logType(outType)); // determine from Out.. without dependency on Env? - try { - if(marshal==null) { // Unknown marshaller... do working XML marshal/extraction - StringWriter sw = new StringWriter(); - jaxMar.marshal(trans.debug(), t, sw, options); - out.extract(new StringReader(sw.toString()), writer, inXML,options); - } else { - out.extract(t, writer, marshal,options); - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - } + public void direct(Trans trans, T t, Writer writer, boolean ... options) throws APIException, IOException { + Out out = getOut(outType); + TimeTaken tt = trans.start(out.logName(),logType(outType)); // determine from Out.. without dependency on Env? + try { + if(marshal==null) { // Unknown marshaller... do working XML marshal/extraction + StringWriter sw = new StringWriter(); + jaxMar.marshal(trans.debug(), t, sw, options); + out.extract(new StringReader(sw.toString()), writer, inXML,options); + } else { + out.extract(t, writer, marshal,options); + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java index 446c3c9c..97f68dae 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java @@ -40,273 +40,273 @@ import org.onap.aaf.misc.rosetta.Parse; import org.onap.aaf.misc.rosetta.Saved; public class RosettaData implements Data{ - private Env trans; - private RosettaDF df; - private Saved saved; - private TYPE inType, outType; - // Note: This is an array of boolean in order to pass into other methods - private boolean options[] = new boolean[] {false, false}; - // Temp Storage of XML. Only when we must use JAXB to read in Objects - private String xml,json; - - // package on purpose - RosettaData(Env env, RosettaDF rosettaDF) { - df = rosettaDF; - saved = new Saved(); // Note: Saved constructs storage as needed... - trans = env; - inType = df.getInType(); - outType = df.getOutType(); // take defaults - } + private Env trans; + private RosettaDF df; + private Saved saved; + private TYPE inType, outType; + // Note: This is an array of boolean in order to pass into other methods + private boolean options[] = new boolean[] {false, false}; + // Temp Storage of XML. Only when we must use JAXB to read in Objects + private String xml,json; + + // package on purpose + RosettaData(Env env, RosettaDF rosettaDF) { + df = rosettaDF; + saved = new Saved(); // Note: Saved constructs storage as needed... + trans = env; + inType = df.getInType(); + outType = df.getOutType(); // take defaults + } -// // @Override - public RosettaData in(TYPE rosettaType) { - inType = rosettaType; - return this; - } - -// // @Override - public RosettaData out(TYPE rosettaType) { - outType = rosettaType; - return this; - } +// // @Override + public RosettaData in(TYPE rosettaType) { + inType = rosettaType; + return this; + } + +// // @Override + public RosettaData out(TYPE rosettaType) { + outType = rosettaType; + return this; + } -// // @Override - public RosettaData load(Reader rdr) throws APIException { - Parse in = df.getIn(inType); - TimeTaken tt = in.start(trans); - try { - saved.extract(rdr, (Writer)null, in); - xml=json=null; - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - return this; - } - - // @Override - public RosettaData load(InputStream is) throws APIException { - Parse in = df.getIn(inType); - TimeTaken tt = in.start(trans); - try { - saved.extract(new InputStreamReader(is), (Writer)null, in); - xml=json=null; - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - return this; - } +// // @Override + public RosettaData load(Reader rdr) throws APIException { + Parse in = df.getIn(inType); + TimeTaken tt = in.start(trans); + try { + saved.extract(rdr, (Writer)null, in); + xml=json=null; + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + return this; + } + + // @Override + public RosettaData load(InputStream is) throws APIException { + Parse in = df.getIn(inType); + TimeTaken tt = in.start(trans); + try { + saved.extract(new InputStreamReader(is), (Writer)null, in); + xml=json=null; + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + return this; + } - // @Override - public RosettaData load(String str) throws APIException { - Parse in = df.getIn(inType); - TimeTaken tt = in.start(trans); - try { - saved.extract(new StringReader(str), (Writer)null, in); - switch(inType) { - case XML: - xml = str; - break; - case JSON: - json = str; - break; - default: - - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - return this; - } + // @Override + public RosettaData load(String str) throws APIException { + Parse in = df.getIn(inType); + TimeTaken tt = in.start(trans); + try { + saved.extract(new StringReader(str), (Writer)null, in); + switch(inType) { + case XML: + xml = str; + break; + case JSON: + json = str; + break; + default: + + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + return this; + } - // @Override - public RosettaData load(T t) throws APIException { - Parse in = df.getIn(inType); - TimeTaken tt = in.start(trans); - try { - if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction - StringWriter sw = new StringWriter(); - df.jaxMar.marshal(trans.debug(), t, sw, options); - saved.extract(new StringReader(xml = sw.toString()), (Writer)null, df.inXML); - } else { - saved.extract(t, (Writer)null, df.marshal); - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - return this; - } + // @Override + public RosettaData load(T t) throws APIException { + Parse in = df.getIn(inType); + TimeTaken tt = in.start(trans); + try { + if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction + StringWriter sw = new StringWriter(); + df.jaxMar.marshal(trans.debug(), t, sw, options); + saved.extract(new StringReader(xml = sw.toString()), (Writer)null, df.inXML); + } else { + saved.extract(t, (Writer)null, df.marshal); + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + return this; + } - public Saved getEvents() { - return saved; - } - - // @Override - public T asObject() throws APIException { - Out out = df.getOut(TYPE.XML); - TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? - try { - //TODO Replace JAXB with Direct Object method!!! - StringWriter sw = new StringWriter(); - out.extract(null, sw, saved); - return df.jaxUmar.unmarshal(trans.debug(), sw.toString()); - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - } + public Saved getEvents() { + return saved; + } + + // @Override + public T asObject() throws APIException { + Out out = df.getOut(TYPE.XML); + TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? + try { + //TODO Replace JAXB with Direct Object method!!! + StringWriter sw = new StringWriter(); + out.extract(null, sw, saved); + return df.jaxUmar.unmarshal(trans.debug(), sw.toString()); + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + } - // @Override - public String asString() throws APIException { - Out out = df.getOut(outType); - TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? - try { - if(outType==TYPE.XML) { - if(xml==null) { - StringWriter sw = new StringWriter(); - out.extract(null, sw, saved, options); - xml = sw.toString(); - } - return xml; - } else { // is JSON - if(json==null) { - StringWriter sw = new StringWriter(); - out.extract(null, sw, saved, options); - json = sw.toString(); - } - return json; - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - } + // @Override + public String asString() throws APIException { + Out out = df.getOut(outType); + TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? + try { + if(outType==TYPE.XML) { + if(xml==null) { + StringWriter sw = new StringWriter(); + out.extract(null, sw, saved, options); + xml = sw.toString(); + } + return xml; + } else { // is JSON + if(json==null) { + StringWriter sw = new StringWriter(); + out.extract(null, sw, saved, options); + json = sw.toString(); + } + return json; + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + } - // @Override - public RosettaData to(OutputStream os) throws APIException, IOException { - Out out = df.getOut(outType); - TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? - try { - if(outType==TYPE.XML && xml!=null) { - os.write(xml.getBytes()); - } else if(outType==TYPE.JSON && json!=null) { - os.write(json.getBytes()); - } else { - out.extract(null, os, saved, options); - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - return this; - } + // @Override + public RosettaData to(OutputStream os) throws APIException, IOException { + Out out = df.getOut(outType); + TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? + try { + if(outType==TYPE.XML && xml!=null) { + os.write(xml.getBytes()); + } else if(outType==TYPE.JSON && json!=null) { + os.write(json.getBytes()); + } else { + out.extract(null, os, saved, options); + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + return this; + } - // @Override - public RosettaData to(Writer writer) throws APIException, IOException { - Out out = df.getOut(outType); - TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? - try { - if(outType==TYPE.XML && xml!=null) { - writer.append(xml); - } else if(outType==TYPE.JSON && json!=null) { - writer.append(json); - } else { - out.extract(null, writer, saved, options); - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - return this; - } - - // @Override - public Class getTypeClass() { - return df.getTypeClass(); - } + // @Override + public RosettaData to(Writer writer) throws APIException, IOException { + Out out = df.getOut(outType); + TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? + try { + if(outType==TYPE.XML && xml!=null) { + writer.append(xml); + } else if(outType==TYPE.JSON && json!=null) { + writer.append(json); + } else { + out.extract(null, writer, saved, options); + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + return this; + } + + // @Override + public Class getTypeClass() { + return df.getTypeClass(); + } - private static final boolean[] emptyOption = new boolean[0]; - - public void direct(InputStream is, OutputStream os) throws APIException, IOException { - direct(is,os,emptyOption); - } - - public void direct(Reader reader, Writer writer, boolean ... options) throws APIException, IOException { - Parse in = df.getIn(inType); - Out out = df.getOut(outType); - TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? - try { - out.extract(reader, writer, in,options); - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - } + private static final boolean[] emptyOption = new boolean[0]; + + public void direct(InputStream is, OutputStream os) throws APIException, IOException { + direct(is,os,emptyOption); + } + + public void direct(Reader reader, Writer writer, boolean ... options) throws APIException, IOException { + Parse in = df.getIn(inType); + Out out = df.getOut(outType); + TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? + try { + out.extract(reader, writer, in,options); + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + } - public void direct(T t, Writer writer, boolean ... options) throws APIException, IOException { - Out out = df.getOut(outType); - TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? - try { - if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction - StringWriter sw = new StringWriter(); - df.jaxMar.marshal(trans.debug(), t, sw, options); - out.extract(new StringReader(xml = sw.toString()), writer, df.inXML,options); - } else { - out.extract(t, writer, df.marshal,options); - } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - } + public void direct(T t, Writer writer, boolean ... options) throws APIException, IOException { + Out out = df.getOut(outType); + TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? + try { + if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction + StringWriter sw = new StringWriter(); + df.jaxMar.marshal(trans.debug(), t, sw, options); + out.extract(new StringReader(xml = sw.toString()), writer, df.inXML,options); + } else { + out.extract(t, writer, df.marshal,options); + } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + } - public void direct(T t, OutputStream os, boolean ... options) throws APIException, IOException { - Out out = df.getOut(outType); - TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? - try { - if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction - if(outType.equals(TYPE.XML)) { - df.jaxMar.marshal(trans.debug(), t, os, options); - } else { - StringWriter sw = new StringWriter(); - df.jaxMar.marshal(trans.debug(), t, sw, options); - out.extract(new StringReader(xml = sw.toString()), new OutputStreamWriter(os), df.inXML,options); - } - } else { - out.extract(t, new OutputStreamWriter(os), df.marshal,options); - } + public void direct(T t, OutputStream os, boolean ... options) throws APIException, IOException { + Out out = df.getOut(outType); + TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? + try { + if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction + if(outType.equals(TYPE.XML)) { + df.jaxMar.marshal(trans.debug(), t, os, options); + } else { + StringWriter sw = new StringWriter(); + df.jaxMar.marshal(trans.debug(), t, sw, options); + out.extract(new StringReader(xml = sw.toString()), new OutputStreamWriter(os), df.inXML,options); + } + } else { + out.extract(t, new OutputStreamWriter(os), df.marshal,options); + } - } catch (Exception e) { - throw new APIException(e); - } finally { - tt.done(); - } - } + } catch (Exception e) { + throw new APIException(e); + } finally { + tt.done(); + } + } - - public void direct(InputStream is, OutputStream os, boolean ... options) throws APIException, IOException { - direct(new InputStreamReader(is),new OutputStreamWriter(os), options); - } + + public void direct(InputStream is, OutputStream os, boolean ... options) throws APIException, IOException { + direct(new InputStreamReader(is),new OutputStreamWriter(os), options); + } - // // @Override - public RosettaData option(int option) { - options[0] = (option&Data.PRETTY)==Data.PRETTY; - options[1] = (option&Data.FRAGMENT)==Data.FRAGMENT; - return this; - } + // // @Override + public RosettaData option(int option) { + options[0] = (option&Data.PRETTY)==Data.PRETTY; + options[1] = (option&Data.FRAGMENT)==Data.FRAGMENT; + return this; + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaEnv.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaEnv.java index 05c75b7e..43855d6c 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaEnv.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaEnv.java @@ -39,51 +39,51 @@ import org.onap.aaf.misc.env.APIException; */ public class RosettaEnv extends org.onap.aaf.misc.env.impl.BasicEnv { - public RosettaEnv() { - super(); - } + public RosettaEnv() { + super(); + } - public RosettaEnv(Applet applet, String... tags) { - super(applet, tags); - } + public RosettaEnv(Applet applet, String... tags) { + super(applet, tags); + } - public RosettaEnv(String[] args) { - super(args); - } + public RosettaEnv(String[] args) { + super(args); + } - public RosettaEnv(String tag, String[] args) { - super(tag, args); - } + public RosettaEnv(String tag, String[] args) { + super(tag, args); + } - public RosettaEnv(String tag, Properties props) { - super(tag, props); - } + public RosettaEnv(String tag, Properties props) { + super(tag, props); + } - public RosettaEnv(Properties props) { - super(props); - } - - @SuppressWarnings("unchecked") - @Override - public RosettaDF newDataFactory(Class... classes) throws APIException { - return new RosettaDF(this, null, null, (Class)classes[0]); - } + public RosettaEnv(Properties props) { + super(props); + } + + @SuppressWarnings("unchecked") + @Override + public RosettaDF newDataFactory(Class... classes) throws APIException { + return new RosettaDF(this, null, null, (Class)classes[0]); + } - @SuppressWarnings("unchecked") - @Override - public RosettaDF newDataFactory(Schema schema, Class... classes) throws APIException { - return new RosettaDF(this, schema, null, (Class)classes[0]); - } + @SuppressWarnings("unchecked") + @Override + public RosettaDF newDataFactory(Schema schema, Class... classes) throws APIException { + return new RosettaDF(this, schema, null, (Class)classes[0]); + } - @SuppressWarnings("unchecked") - @Override - public RosettaDF newDataFactory(QName qName, Class ... classes) throws APIException { - return new RosettaDF(this, null, qName.getNamespaceURI(),(Class)classes[0]); - } + @SuppressWarnings("unchecked") + @Override + public RosettaDF newDataFactory(QName qName, Class ... classes) throws APIException { + return new RosettaDF(this, null, qName.getNamespaceURI(),(Class)classes[0]); + } - @SuppressWarnings("unchecked") - @Override - public RosettaDF newDataFactory(Schema schema, QName qName, Class ... classes) throws APIException { - return new RosettaDF(this, schema,qName.getNamespaceURI(),(Class)classes[0]); - } + @SuppressWarnings("unchecked") + @Override + public RosettaDF newDataFactory(Schema schema, QName qName, Class ... classes) throws APIException { + return new RosettaDF(this, schema,qName.getNamespaceURI(),(Class)classes[0]); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java index 1655928d..849a3214 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java @@ -34,106 +34,106 @@ import org.onap.aaf.misc.env.util.Chrono; * @param */ public abstract class DataWriter { - public abstract boolean write(T t, StringBuilder sb); - - public final static DataWriter STRING = new DataWriter() { - @Override - public boolean write(String s, StringBuilder sb) { - sb.append(s); - return true; - } - }; - - public final static DataWriter INTEGER = new DataWriter() { - @Override - public boolean write(Integer i, StringBuilder sb) { - sb.append(i); - return false; - } - }; - - public final static DataWriter LONG = new DataWriter() { - @Override - public boolean write(Long t, StringBuilder sb) { - sb.append(t); - return false; - } - }; + public abstract boolean write(T t, StringBuilder sb); + + public final static DataWriter STRING = new DataWriter() { + @Override + public boolean write(String s, StringBuilder sb) { + sb.append(s); + return true; + } + }; + + public final static DataWriter INTEGER = new DataWriter() { + @Override + public boolean write(Integer i, StringBuilder sb) { + sb.append(i); + return false; + } + }; + + public final static DataWriter LONG = new DataWriter() { + @Override + public boolean write(Long t, StringBuilder sb) { + sb.append(t); + return false; + } + }; - public final static DataWriter BYTE = new DataWriter() { - @Override - public boolean write(Byte t, StringBuilder sb) { - sb.append(t); - return false; - } - }; + public final static DataWriter BYTE = new DataWriter() { + @Override + public boolean write(Byte t, StringBuilder sb) { + sb.append(t); + return false; + } + }; - public final static DataWriter CHAR = new DataWriter() { - @Override - public boolean write(Character t, StringBuilder sb) { - sb.append(t); - return true; - } - }; + public final static DataWriter CHAR = new DataWriter() { + @Override + public boolean write(Character t, StringBuilder sb) { + sb.append(t); + return true; + } + }; - public final static DataWriter BOOL = new DataWriter() { - @Override - public boolean write(Boolean t, StringBuilder sb) { - sb.append(t); - return true; - } - }; + public final static DataWriter BOOL = new DataWriter() { + @Override + public boolean write(Boolean t, StringBuilder sb) { + sb.append(t); + return true; + } + }; - /* - public final static DataWriter BYTE_ARRAY = new DataWriter() { - @Override - public boolean write(byte[] ba, StringBuilder sb) { - ByteArrayInputStream bais = new ByteArrayInputStream(ba); - StringBuilderOutputStream sbos = new StringBuilderOutputStream(sb); -// try { - //TODO find Base64 -// Symm.base64noSplit().encode(bais, sbos); -// } catch (IOException e) { -// // leave blank -// } - return true; - } - - }; - */ + /* + public final static DataWriter BYTE_ARRAY = new DataWriter() { + @Override + public boolean write(byte[] ba, StringBuilder sb) { + ByteArrayInputStream bais = new ByteArrayInputStream(ba); + StringBuilderOutputStream sbos = new StringBuilderOutputStream(sb); +// try { + //TODO find Base64 +// Symm.base64noSplit().encode(bais, sbos); +// } catch (IOException e) { +// // leave blank +// } + return true; + } + + }; + */ - public final static DataWriter DATE = new DataWriter() { - @Override - public boolean write(XMLGregorianCalendar t, StringBuilder sb) { - sb.append(Chrono.dateOnlyStamp(t)); - return true; - } - }; - - public final static DataWriter DATE_TIME = new DataWriter() { - @Override - public boolean write(XMLGregorianCalendar t, StringBuilder sb) { - sb.append(Chrono.dateTime(t)); - return true; - } - }; + public final static DataWriter DATE = new DataWriter() { + @Override + public boolean write(XMLGregorianCalendar t, StringBuilder sb) { + sb.append(Chrono.dateOnlyStamp(t)); + return true; + } + }; + + public final static DataWriter DATE_TIME = new DataWriter() { + @Override + public boolean write(XMLGregorianCalendar t, StringBuilder sb) { + sb.append(Chrono.dateTime(t)); + return true; + } + }; - private static final char[] chars="0123456789ABCDEF".toCharArray(); - public final static DataWriter HEX_BINARY = new DataWriter() { - @Override - public boolean write(byte[] ba, StringBuilder sb) { - // FYI, doing this because don't want intermediate - // String in "HexString" or the processing in - // "String.format" - //sb.append("0x"); - for(int i=0;i>4)]); - sb.append(chars[b&0xF]); - } - return true; - } - }; + private static final char[] chars="0123456789ABCDEF".toCharArray(); + public final static DataWriter HEX_BINARY = new DataWriter() { + @Override + public boolean write(byte[] ba, StringBuilder sb) { + // FYI, doing this because don't want intermediate + // String in "HexString" or the processing in + // "String.format" + //sb.append("0x"); + for(int i=0;i>4)]); + sb.append(chars[b&0xF]); + } + return true; + } + }; } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java index 2776546f..6cabe068 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java @@ -30,57 +30,57 @@ import org.onap.aaf.misc.rosetta.ParseException; import org.onap.aaf.misc.rosetta.Parsed; public class DocMarshal extends Marshal { - private Marshal root; - - public DocMarshal(Marshal root) { - this.root = root; - } - - @Override - public Parsed parse(T t, Parsed parsed) throws ParseException { - Ladder> ladder = parsed.state.ladder; - Iterator iter = ladder.peek(); - if(iter==null) { - ladder.push(PENDING_ITERATOR); - parsed.event = START_DOC; - } else if (DONE_ITERATOR.equals(iter)) { - } else { - ladder.ascend(); // look at field info - Iterator currFieldIter = ladder.peek(); - if(!DONE_ITERATOR.equals(currFieldIter)){ - parsed = root.parse(t, parsed); - } - ladder.descend(); - if(DONE_ITERATOR.equals(currFieldIter) || parsed.event==NONE) { - parsed.event = END_DOC; - ladder.push(DONE_ITERATOR); - } - } - return parsed; // if unchanged, then it will end process + private Marshal root; + + public DocMarshal(Marshal root) { + this.root = root; + } + + @Override + public Parsed parse(T t, Parsed parsed) throws ParseException { + Ladder> ladder = parsed.state.ladder; + Iterator iter = ladder.peek(); + if(iter==null) { + ladder.push(PENDING_ITERATOR); + parsed.event = START_DOC; + } else if (DONE_ITERATOR.equals(iter)) { + } else { + ladder.ascend(); // look at field info + Iterator currFieldIter = ladder.peek(); + if(!DONE_ITERATOR.equals(currFieldIter)){ + parsed = root.parse(t, parsed); + } + ladder.descend(); + if(DONE_ITERATOR.equals(currFieldIter) || parsed.event==NONE) { + parsed.event = END_DOC; + ladder.push(DONE_ITERATOR); + } + } + return parsed; // if unchanged, then it will end process - } + } - public static final Iterator PENDING_ITERATOR = new Iterator() { - @Override - public boolean hasNext() { - return false; - } + public static final Iterator PENDING_ITERATOR = new Iterator() { + @Override + public boolean hasNext() { + return false; + } - @Override - public Void next() { - if(!hasNext()) { - throw new NoSuchElementException(); - } - return null; - } + @Override + public Void next() { + if(!hasNext()) { + throw new NoSuchElementException(); + } + return null; + } - @Override - public void remove() { - } - }; + @Override + public void remove() { + } + }; - public static DocMarshal root(Marshal m) { - return (DocMarshal)new DocMarshal(m); - } + public static DocMarshal root(Marshal m) { + return (DocMarshal)new DocMarshal(m); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java index 3006f897..48f3608d 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java @@ -31,62 +31,62 @@ import org.onap.aaf.misc.rosetta.Parsed; public abstract class FieldArray extends Marshal { - private DataWriter dataWriter; - private String name; + private DataWriter dataWriter; + private String name; - public FieldArray(String name, DataWriter dw) { - this.name = name; - dataWriter = dw; - } - - @SuppressWarnings("unchecked") - @Override - public Parsed parse(T t, Parsed parsed) throws ParseException { - Ladder> ladder = parsed.state.ladder; - Iterator iter = ladder.peek(); - if(iter==null) { - List list = data(t); - if(list.isEmpty() && parsed.state.smallest) { - ladder.push(DONE_ITERATOR); - } else { - ladder.push(new ListIterator(list)); - parsed.event = START_ARRAY; - parsed.name = name; - } - } else if (DONE_ITERATOR.equals(iter)) { - } else { - ladder.ascend(); // look at field info - Iterator memIter = ladder.peek(); - ListIterator mems = (ListIterator)iter; - S mem; - if(memIter==null) { - mem=mems.next(); - } else if(!DONE_ITERATOR.equals(memIter)) { - mem=mems.peek(); - } else if(iter.hasNext()) { - mem=null; - ladder.push(null); - } else { - mem=null; - } - - if(mem!=null) { - parsed.isString=dataWriter.write(mem, parsed.sb); - parsed.event = NEXT; - } - ladder.descend(); - if(mem==null) { - if(iter.hasNext()) { - parsed.event = NEXT; - } else { - parsed.event = END_ARRAY; - ladder.push(DONE_ITERATOR); - } - } - } - return parsed; // if unchanged, then it will end process - } + public FieldArray(String name, DataWriter dw) { + this.name = name; + dataWriter = dw; + } + + @SuppressWarnings("unchecked") + @Override + public Parsed parse(T t, Parsed parsed) throws ParseException { + Ladder> ladder = parsed.state.ladder; + Iterator iter = ladder.peek(); + if(iter==null) { + List list = data(t); + if(list.isEmpty() && parsed.state.smallest) { + ladder.push(DONE_ITERATOR); + } else { + ladder.push(new ListIterator(list)); + parsed.event = START_ARRAY; + parsed.name = name; + } + } else if (DONE_ITERATOR.equals(iter)) { + } else { + ladder.ascend(); // look at field info + Iterator memIter = ladder.peek(); + ListIterator mems = (ListIterator)iter; + S mem; + if(memIter==null) { + mem=mems.next(); + } else if(!DONE_ITERATOR.equals(memIter)) { + mem=mems.peek(); + } else if(iter.hasNext()) { + mem=null; + ladder.push(null); + } else { + mem=null; + } + + if(mem!=null) { + parsed.isString=dataWriter.write(mem, parsed.sb); + parsed.event = NEXT; + } + ladder.descend(); + if(mem==null) { + if(iter.hasNext()) { + parsed.event = NEXT; + } else { + parsed.event = END_ARRAY; + ladder.push(DONE_ITERATOR); + } + } + } + return parsed; // if unchanged, then it will end process + } - protected abstract List data(T t); + protected abstract List data(T t); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldBlob.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldBlob.java index 1de14e82..34fa5dd6 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldBlob.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldBlob.java @@ -22,17 +22,17 @@ package org.onap.aaf.misc.rosetta.marshal; public abstract class FieldBlob extends FieldMarshal{ - public FieldBlob(String name) { - super(name); - } + public FieldBlob(String name) { + super(name); + } - protected abstract byte[] data(T t); + protected abstract byte[] data(T t); - @Override - protected boolean data(T t, StringBuilder sb) { - return false; - // unimplemented - //return DataWriter.BYTE_ARRAY.write(data(t),sb); - } + @Override + protected boolean data(T t, StringBuilder sb) { + return false; + // unimplemented + //return DataWriter.BYTE_ARRAY.write(data(t),sb); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDate.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDate.java index b3632a14..2418d7af 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDate.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDate.java @@ -24,14 +24,14 @@ package org.onap.aaf.misc.rosetta.marshal; import javax.xml.datatype.XMLGregorianCalendar; public abstract class FieldDate extends FieldMarshal { - public FieldDate(String name) { - super(name); - } + public FieldDate(String name) { + super(name); + } - @Override - final protected boolean data(T t, StringBuilder sb) { - return DataWriter.DATE.write(data(t), sb); - } + @Override + final protected boolean data(T t, StringBuilder sb) { + return DataWriter.DATE.write(data(t), sb); + } - protected abstract XMLGregorianCalendar data(T t); + protected abstract XMLGregorianCalendar data(T t); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDateTime.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDateTime.java index 8aa29829..ae125617 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDateTime.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldDateTime.java @@ -24,14 +24,14 @@ package org.onap.aaf.misc.rosetta.marshal; import javax.xml.datatype.XMLGregorianCalendar; public abstract class FieldDateTime extends FieldMarshal { - public FieldDateTime(String name) { - super(name); - } + public FieldDateTime(String name) { + super(name); + } - @Override - final protected boolean data(T t, StringBuilder sb) { - return DataWriter.DATE_TIME.write(data(t), sb); - } + @Override + final protected boolean data(T t, StringBuilder sb) { + return DataWriter.DATE_TIME.write(data(t), sb); + } - protected abstract XMLGregorianCalendar data(T t); + protected abstract XMLGregorianCalendar data(T t); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldHexBinary.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldHexBinary.java index 589d0920..fa9e6323 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldHexBinary.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldHexBinary.java @@ -22,14 +22,14 @@ package org.onap.aaf.misc.rosetta.marshal; public abstract class FieldHexBinary extends FieldMarshal{ - public FieldHexBinary(String name) { - super(name); - } + public FieldHexBinary(String name) { + super(name); + } - protected abstract byte[] data(T t); + protected abstract byte[] data(T t); - @Override - protected boolean data(T t, StringBuilder sb) { - return DataWriter.HEX_BINARY.write(data(t), sb); - } + @Override + protected boolean data(T t, StringBuilder sb) { + return DataWriter.HEX_BINARY.write(data(t), sb); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldMarshal.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldMarshal.java index cb8b6557..2e77618b 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldMarshal.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldMarshal.java @@ -27,33 +27,33 @@ import org.onap.aaf.misc.rosetta.Parse; import org.onap.aaf.misc.rosetta.Parsed; public abstract class FieldMarshal extends Marshal { - private String name; + private String name; - public FieldMarshal(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public Parsed parse(T t, Parsed parsed) { - parsed.state.ladder.push(DONE_ITERATOR); - parsed.event = Parse.NEXT; - parsed.name = name; - parsed.isString = data(t,parsed.sb); - return parsed; - } + public FieldMarshal(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public Parsed parse(T t, Parsed parsed) { + parsed.state.ladder.push(DONE_ITERATOR); + parsed.event = Parse.NEXT; + parsed.name = name; + parsed.isString = data(t,parsed.sb); + return parsed; + } - /** - * Write Value to StringBuilder - * Return true if value looks like a String - * false if it is Numeric - * @param t - * @param sb - * @return - */ - protected abstract boolean data(T t, StringBuilder sb); - + /** + * Write Value to StringBuilder + * Return true if value looks like a String + * false if it is Numeric + * @param t + * @param sb + * @return + */ + protected abstract boolean data(T t, StringBuilder sb); + } \ No newline at end of file diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldNumeric.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldNumeric.java index aac9ac69..0a5c28ad 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldNumeric.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldNumeric.java @@ -22,15 +22,15 @@ package org.onap.aaf.misc.rosetta.marshal; public abstract class FieldNumeric extends FieldMarshal { - public FieldNumeric(String name) { - super(name); - } + public FieldNumeric(String name) { + super(name); + } - @Override - final protected boolean data(T t, StringBuilder sb) { - sb.append(data(t)); - return false; - } + @Override + final protected boolean data(T t, StringBuilder sb) { + sb.append(data(t)); + return false; + } - protected abstract N data(T t); + protected abstract N data(T t); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldString.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldString.java index 2337c3c9..e96b6967 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldString.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldString.java @@ -22,15 +22,15 @@ package org.onap.aaf.misc.rosetta.marshal; public abstract class FieldString extends FieldMarshal { - public FieldString(String name) { - super(name); - } + public FieldString(String name) { + super(name); + } - protected abstract String data(T t); + protected abstract String data(T t); - @Override - final protected boolean data(T t, StringBuilder sb) { - return DataWriter.STRING.write(data(t), sb); - } + @Override + final protected boolean data(T t, StringBuilder sb) { + return DataWriter.STRING.write(data(t), sb); + } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ListIterator.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ListIterator.java index 6045141d..ed8b98c4 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ListIterator.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ListIterator.java @@ -31,29 +31,29 @@ import java.util.List; * @param */ final class ListIterator implements Iterator { - private T curr; - private Iterator delg; - public ListIterator(List list) { - curr = null; - delg = list.iterator(); - } - @Override - public boolean hasNext() { - return delg.hasNext(); - } + private T curr; + private Iterator delg; + public ListIterator(List list) { + curr = null; + delg = list.iterator(); + } + @Override + public boolean hasNext() { + return delg.hasNext(); + } - @Override - public T next() { - return curr = delg.hasNext()?delg.next():null; - } - - public T peek() { - return curr==null?next():curr; - } + @Override + public T next() { + return curr = delg.hasNext()?delg.next():null; + } + + public T peek() { + return curr==null?next():curr; + } - @Override - public void remove() { - delg.remove(); - } - + @Override + public void remove() { + delg.remove(); + } + } \ No newline at end of file diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java index fa95dee5..384e0c98 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java @@ -31,59 +31,59 @@ import org.onap.aaf.misc.rosetta.Parsed; public abstract class ObjArray extends Marshal { - private String name; - private Marshal subMarshaller; + private String name; + private Marshal subMarshaller; - public ObjArray(String name, Marshal subMarshaller) { - this.name = name; - this.subMarshaller = subMarshaller; - } + public ObjArray(String name, Marshal subMarshaller) { + this.name = name; + this.subMarshaller = subMarshaller; + } - @SuppressWarnings("unchecked") - @Override - public Parsed parse(T t, Parsed parsed) throws ParseException { - Ladder> ladder = parsed.state.ladder; - Iterator iter = ladder.peek(); - if(iter==null) { - List list = data(t); - if(list.isEmpty() && parsed.state.smallest) { - ladder.push(DONE_ITERATOR); - } else { - ladder.push(new ListIterator(list)); - parsed.event = START_ARRAY; - parsed.name = name; - } - } else if (!DONE_ITERATOR.equals(iter)) { - ladder.ascend(); // look at field info - Iterator memIter = ladder.peek(); - ListIterator mems = (ListIterator)iter; - S mem; - if(memIter==null) { - mem=mems.next(); - } else if(!DONE_ITERATOR.equals(memIter)) { - mem=mems.peek(); - } else if(iter.hasNext()) { - mem=null; - ladder.push(null); - } else { - mem=null; - } + @SuppressWarnings("unchecked") + @Override + public Parsed parse(T t, Parsed parsed) throws ParseException { + Ladder> ladder = parsed.state.ladder; + Iterator iter = ladder.peek(); + if(iter==null) { + List list = data(t); + if(list.isEmpty() && parsed.state.smallest) { + ladder.push(DONE_ITERATOR); + } else { + ladder.push(new ListIterator(list)); + parsed.event = START_ARRAY; + parsed.name = name; + } + } else if (!DONE_ITERATOR.equals(iter)) { + ladder.ascend(); // look at field info + Iterator memIter = ladder.peek(); + ListIterator mems = (ListIterator)iter; + S mem; + if(memIter==null) { + mem=mems.next(); + } else if(!DONE_ITERATOR.equals(memIter)) { + mem=mems.peek(); + } else if(iter.hasNext()) { + mem=null; + ladder.push(null); + } else { + mem=null; + } - if(mem!=null) - parsed = subMarshaller.parse(mem, parsed); - ladder.descend(); - if(mem==null) { - if(iter.hasNext()) { - parsed.event = NEXT; - } else { - parsed.event = END_ARRAY; - ladder.push(DONE_ITERATOR); - } - } - } - return parsed; // if unchanged, then it will end process - } + if(mem!=null) + parsed = subMarshaller.parse(mem, parsed); + ladder.descend(); + if(mem==null) { + if(iter.hasNext()) { + parsed.event = NEXT; + } else { + parsed.event = END_ARRAY; + ladder.push(DONE_ITERATOR); + } + } + } + return parsed; // if unchanged, then it will end process + } - protected abstract List data(T t); + protected abstract List data(T t); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java index cb2c478a..31e214b5 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java @@ -38,94 +38,94 @@ import org.onap.aaf.misc.rosetta.Parsed; * @param */ public abstract class ObjMarshal extends Marshal { - // Note: Not Using List or ArrayList, because there is no "Peek" concept in their iterator. - private Marshal[] pml; - private int end=0; - - /** - * @param pm - */ - @SuppressWarnings("unchecked") - protected void add(Marshal pm) { - if(pml==null) { - pml = new Marshal[Ladder.DEFAULT_INIT_SIZE]; - } else if(end>pml.length) { - Object temp[] = pml; - pml = new Marshal[pml.length+Ladder.DEFAULT_INIT_SIZE]; - System.arraycopy(temp, 0, pml, 0, pml.length); - } - pml[end]=pm; - ++end; - } - - /* (non-Javadoc) - * @see org.onap.aaf.misc.rosetta.Parse#parse(java.lang.Object, org.onap.aaf.misc.rosetta.Parsed) - */ - @SuppressWarnings("unchecked") - @Override - public Parsed parse(T in, Parsed parsed) throws ParseException { - Ladder> ladder = parsed.state.ladder; - Iterator> iter = (Iterator>)ladder.peek(); - if(iter==null) { - if(pml.length>0) { - ladder.push(new FieldsIterator()); - parsed.event = START_OBJ; - } else { - ladder.push(DONE_ITERATOR); - } - } else if (!DONE_ITERATOR.equals(iter)) { - FieldsIterator fields = (FieldsIterator)iter; - ladder.ascend(); // look at field info - Iterator currFieldIter = ladder.peek(); - Marshal marshal; - if(currFieldIter==null) { - marshal=fields.next(); - } else if(!DONE_ITERATOR.equals(currFieldIter)) { - marshal=fields.peek(); - if(marshal==null && fields.hasNext())marshal=fields.next(); - } else if(fields.hasNext()) { - marshal=fields.next(); - ladder.push(null); - } else { - marshal=null; - } + // Note: Not Using List or ArrayList, because there is no "Peek" concept in their iterator. + private Marshal[] pml; + private int end=0; + + /** + * @param pm + */ + @SuppressWarnings("unchecked") + protected void add(Marshal pm) { + if(pml==null) { + pml = new Marshal[Ladder.DEFAULT_INIT_SIZE]; + } else if(end>pml.length) { + Object temp[] = pml; + pml = new Marshal[pml.length+Ladder.DEFAULT_INIT_SIZE]; + System.arraycopy(temp, 0, pml, 0, pml.length); + } + pml[end]=pm; + ++end; + } + + /* (non-Javadoc) + * @see org.onap.aaf.misc.rosetta.Parse#parse(java.lang.Object, org.onap.aaf.misc.rosetta.Parsed) + */ + @SuppressWarnings("unchecked") + @Override + public Parsed parse(T in, Parsed parsed) throws ParseException { + Ladder> ladder = parsed.state.ladder; + Iterator> iter = (Iterator>)ladder.peek(); + if(iter==null) { + if(pml.length>0) { + ladder.push(new FieldsIterator()); + parsed.event = START_OBJ; + } else { + ladder.push(DONE_ITERATOR); + } + } else if (!DONE_ITERATOR.equals(iter)) { + FieldsIterator fields = (FieldsIterator)iter; + ladder.ascend(); // look at field info + Iterator currFieldIter = ladder.peek(); + Marshal marshal; + if(currFieldIter==null) { + marshal=fields.next(); + } else if(!DONE_ITERATOR.equals(currFieldIter)) { + marshal=fields.peek(); + if(marshal==null && fields.hasNext())marshal=fields.next(); + } else if(fields.hasNext()) { + marshal=fields.next(); + ladder.push(null); + } else { + marshal=null; + } - if(marshal!=null) - parsed = marshal.parse(in, parsed); - ladder.descend(); - if(marshal==null || parsed.event==NONE) { - parsed.event = END_OBJ; - ladder.push(DONE_ITERATOR); - } - } - return parsed; // if unchanged, then it will end process - } + if(marshal!=null) + parsed = marshal.parse(in, parsed); + ladder.descend(); + if(marshal==null || parsed.event==NONE) { + parsed.event = END_OBJ; + ladder.push(DONE_ITERATOR); + } + } + return parsed; // if unchanged, then it will end process + } - private class FieldsIterator implements Iterator> { - private int idx = -1; + private class FieldsIterator implements Iterator> { + private int idx = -1; - @Override - public boolean hasNext() { - return idx next() { - if(!hasNext()) { - throw new NoSuchElementException(); - } - return pml[++idx]; - } + @Override + public Marshal next() { + if(!hasNext()) { + throw new NoSuchElementException(); + } + return pml[++idx]; + } - public Marshal peek() { - return idx<0?null:pml[idx]; - } - - @Override - public void remove() { - pml[idx]=null; - } - - } + public Marshal peek() { + return idx<0?null:pml[idx]; + } + + @Override + public void remove() { + pml[idx]=null; + } + + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java index 121deea0..3e12f594 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java @@ -44,225 +44,225 @@ import s.xsd.LargerData; import s.xsd.SampleData; public class JU_FromJSON { - private static int ITERATIONS = 10000; - static String str = "{\"SampleData\":[" + - "{\"id\":\"sd object \\\"1\\\"\",\"date\":1316084944213,\"item\":[\"Item 1.1\",\"Item 1.2\"]}," + - "{\"id\":\"sd object \\\"2\\\"\",\"date\":1316084945343,\"item\":[\"Item 2.1\",\"Item 2.2\"]}],\"fluff\":\"MyFluff\"}"; - InJson inJSON = new InJson(); + private static int ITERATIONS = 10000; + static String str = "{\"SampleData\":[" + + "{\"id\":\"sd object \\\"1\\\"\",\"date\":1316084944213,\"item\":[\"Item 1.1\",\"Item 1.2\"]}," + + "{\"id\":\"sd object \\\"2\\\"\",\"date\":1316084945343,\"item\":[\"Item 2.1\",\"Item 2.2\"]}],\"fluff\":\"MyFluff\"}"; + InJson inJSON = new InJson(); - @Test - public void rawParse() throws Exception { - System.out.println("*** PARSE JSON -> RAW Dump ***"); - System.out.println(str); - StringBuilderWriter sbw = new StringBuilderWriter(); - new OutRaw().extract(new StringReader(str),sbw,inJSON); - System.out.println(sbw.getBuffer()); - } - - @Test - public void parseJSON2Dump() throws Exception { - System.out.println("*** PARSE JSON -> Dump ***"); - System.out.println(str); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - - new OutDump().extract(new StringReader(str), sbw, inJSON); - - System.out.println(sbw.getBuffer()); - } - - @Test - public void nonprettyJSON() throws Exception { - System.out.println("*** JSON -> (Intermediate Stream) -> Non-pretty JSON ***"); - System.out.println(str); - StringBuilderWriter sbw = new StringBuilderWriter(1024); + @Test + public void rawParse() throws Exception { + System.out.println("*** PARSE JSON -> RAW Dump ***"); + System.out.println(str); + StringBuilderWriter sbw = new StringBuilderWriter(); + new OutRaw().extract(new StringReader(str),sbw,inJSON); + System.out.println(sbw.getBuffer()); + } + + @Test + public void parseJSON2Dump() throws Exception { + System.out.println("*** PARSE JSON -> Dump ***"); + System.out.println(str); + StringBuilderWriter sbw = new StringBuilderWriter(1024); + + new OutDump().extract(new StringReader(str), sbw, inJSON); + + System.out.println(sbw.getBuffer()); + } + + @Test + public void nonprettyJSON() throws Exception { + System.out.println("*** JSON -> (Intermediate Stream) -> Non-pretty JSON ***"); + System.out.println(str); + StringBuilderWriter sbw = new StringBuilderWriter(1024); - Out jout = new OutJson(); - Trans trans; - Report report = new Report(ITERATIONS,"JSON"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Reader sr = new StringReader(str); - TimeTaken tt = trans.start("Parse JSON", Env.JSON); - try { - jout.extract(sr, sbw, inJSON); - } finally { - tt.done(); - } - report.glean(trans,Env.JSON); - } while(report.go()); - - String result = sbw.toString(); - System.out.println(result); - Assert.assertEquals(result, str); - report.report(sbw); - System.out.println(sbw.toString()); - } - - @Test - public void parseJSON2JSON() throws Exception { - System.out.println("*** JSON -> (Intermediate Stream) -> Pretty JSON ***"); - System.out.println(str); + Out jout = new OutJson(); + Trans trans; + Report report = new Report(ITERATIONS,"JSON"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Reader sr = new StringReader(str); + TimeTaken tt = trans.start("Parse JSON", Env.JSON); + try { + jout.extract(sr, sbw, inJSON); + } finally { + tt.done(); + } + report.glean(trans,Env.JSON); + } while(report.go()); + + String result = sbw.toString(); + System.out.println(result); + Assert.assertEquals(result, str); + report.report(sbw); + System.out.println(sbw.toString()); + } + + @Test + public void parseJSON2JSON() throws Exception { + System.out.println("*** JSON -> (Intermediate Stream) -> Pretty JSON ***"); + System.out.println(str); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - - Out jout = new OutJson(); - Trans trans; - Report report = new Report(ITERATIONS,"JSON"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Reader sr = new StringReader(str); - TimeTaken tt = trans.start("Parse JSON", Env.JSON); - try { - jout.extract(sr, sbw, inJSON,true); - } finally { - tt.done(); - } - report.glean(trans,Env.JSON); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); - } + StringBuilderWriter sbw = new StringBuilderWriter(1024); + + Out jout = new OutJson(); + Trans trans; + Report report = new Report(ITERATIONS,"JSON"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Reader sr = new StringReader(str); + TimeTaken tt = trans.start("Parse JSON", Env.JSON); + try { + jout.extract(sr, sbw, inJSON,true); + } finally { + tt.done(); + } + report.glean(trans,Env.JSON); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); + } - @Test - public void parseJSON2XML() throws Exception { - System.out.println("*** PARSE JSON -> XML ***"); - System.out.println(str); + @Test + public void parseJSON2XML() throws Exception { + System.out.println("*** PARSE JSON -> XML ***"); + System.out.println(str); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - - Out xout = new OutXML("LargerData","xmlns=urn:s:xsd"); - Trans trans; - Report report = new Report(ITERATIONS,"JSON"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Reader sr = new StringReader(str); - TimeTaken tt = trans.start("Parse JSON", Env.JSON); - try { - xout.extract(sr, sbw, inJSON); - } finally { - tt.done(); - } - report.glean(trans,Env.JSON); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); - } + StringBuilderWriter sbw = new StringBuilderWriter(1024); + + Out xout = new OutXML("LargerData","xmlns=urn:s:xsd"); + Trans trans; + Report report = new Report(ITERATIONS,"JSON"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Reader sr = new StringReader(str); + TimeTaken tt = trans.start("Parse JSON", Env.JSON); + try { + xout.extract(sr, sbw, inJSON); + } finally { + tt.done(); + } + report.glean(trans,Env.JSON); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); + } - @Test - public void parseJSON2PrettyXML() throws Exception { - System.out.println("*** PARSE JSON -> Pretty XML ***"); - System.out.println(str); + @Test + public void parseJSON2PrettyXML() throws Exception { + System.out.println("*** PARSE JSON -> Pretty XML ***"); + System.out.println(str); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - IndentPrintWriter ipw = new IndentPrintWriter(sbw); - - Out xout = new OutXML("LargerData","xmlns=urn:s:xsd"); - Trans trans; - Report report = new Report(ITERATIONS,"JSON"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Reader sr = new StringReader(str); - TimeTaken tt = trans.start("Parse JSON", Env.JSON); - try { - xout.extract(sr, ipw, inJSON); - } finally { - tt.done(); - } - report.glean(trans,Env.JSON); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); - } - - - @Test - public void jaxbObj2XML() throws Exception { - System.out.println("*** JAXB Object -> XML ***"); + StringBuilderWriter sbw = new StringBuilderWriter(1024); + IndentPrintWriter ipw = new IndentPrintWriter(sbw); + + Out xout = new OutXML("LargerData","xmlns=urn:s:xsd"); + Trans trans; + Report report = new Report(ITERATIONS,"JSON"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Reader sr = new StringReader(str); + TimeTaken tt = trans.start("Parse JSON", Env.JSON); + try { + xout.extract(sr, ipw, inJSON); + } finally { + tt.done(); + } + report.glean(trans,Env.JSON); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); + } + + + @Test + public void jaxbObj2XML() throws Exception { + System.out.println("*** JAXB Object -> XML ***"); - LargerData ld = new LargerData(); - SampleData sd = new SampleData(); - sd.setDate(System.currentTimeMillis()); - sd.setId("sd object \"1\""); - sd.getItem().add("Item 1.1"); - sd.getItem().add("Item 1.2"); - ld.getSampleData().add(sd); - sd = new SampleData(); - sd.setDate(System.currentTimeMillis()); - sd.setId("sd object \"2\""); - sd.getItem().add("Item 2.1"); - sd.getItem().add("Item 2.2"); - ld.getSampleData().add(sd); - ld.setFluff("MyFluff"); - - JAXBmar jaxBmar = new JAXBmar(LargerData.class); - //jaxBmar.asFragment(true); - //jaxBmar.pretty(true); - StringBuilderWriter sbw = new StringBuilderWriter(1024); + LargerData ld = new LargerData(); + SampleData sd = new SampleData(); + sd.setDate(System.currentTimeMillis()); + sd.setId("sd object \"1\""); + sd.getItem().add("Item 1.1"); + sd.getItem().add("Item 1.2"); + ld.getSampleData().add(sd); + sd = new SampleData(); + sd.setDate(System.currentTimeMillis()); + sd.setId("sd object \"2\""); + sd.getItem().add("Item 2.1"); + sd.getItem().add("Item 2.2"); + ld.getSampleData().add(sd); + ld.setFluff("MyFluff"); + + JAXBmar jaxBmar = new JAXBmar(LargerData.class); + //jaxBmar.asFragment(true); + //jaxBmar.pretty(true); + StringBuilderWriter sbw = new StringBuilderWriter(1024); - Trans trans; - Report report = new Report(ITERATIONS,"XML"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - TimeTaken tt = trans.start("JAXB", Env.XML); - try { - jaxBmar.marshal(LogTarget.NULL, ld, sbw); - } finally { - tt.done(); - } - report.glean(trans,Env.XML); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); - } + Trans trans; + Report report = new Report(ITERATIONS,"XML"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + TimeTaken tt = trans.start("JAXB", Env.XML); + try { + jaxBmar.marshal(LogTarget.NULL, ld, sbw); + } finally { + tt.done(); + } + report.glean(trans,Env.XML); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); + } - @Test - public void jaxbObj2PrettyXML() throws Exception { - System.out.println("*** JAXB Object -> Pretty XML ***"); + @Test + public void jaxbObj2PrettyXML() throws Exception { + System.out.println("*** JAXB Object -> Pretty XML ***"); - LargerData ld = new LargerData(); - SampleData sd = new SampleData(); - sd.setDate(System.currentTimeMillis()); - sd.setId("sd object \"1\""); - sd.getItem().add("Item 1.1"); - sd.getItem().add("Item 1.2"); - ld.getSampleData().add(sd); - sd = new SampleData(); - sd.setDate(System.currentTimeMillis()); - sd.setId("sd object \"2\""); - sd.getItem().add("Item 2.1"); - sd.getItem().add("Item 2.2"); - ld.getSampleData().add(sd); - ld.setFluff("MyFluff"); - - JAXBmar jaxBmar = new JAXBmar(LargerData.class); - //jaxBmar.asFragment(true); - jaxBmar.pretty(true); - StringBuilderWriter sbw = new StringBuilderWriter(1024); + LargerData ld = new LargerData(); + SampleData sd = new SampleData(); + sd.setDate(System.currentTimeMillis()); + sd.setId("sd object \"1\""); + sd.getItem().add("Item 1.1"); + sd.getItem().add("Item 1.2"); + ld.getSampleData().add(sd); + sd = new SampleData(); + sd.setDate(System.currentTimeMillis()); + sd.setId("sd object \"2\""); + sd.getItem().add("Item 2.1"); + sd.getItem().add("Item 2.2"); + ld.getSampleData().add(sd); + ld.setFluff("MyFluff"); + + JAXBmar jaxBmar = new JAXBmar(LargerData.class); + //jaxBmar.asFragment(true); + jaxBmar.pretty(true); + StringBuilderWriter sbw = new StringBuilderWriter(1024); - Trans trans; - Report report = new Report(ITERATIONS,"XML"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - TimeTaken tt = trans.start("JAXB", Env.XML); - try { - jaxBmar.marshal(LogTarget.NULL, ld, sbw); - } finally { - tt.done(); - } - report.glean(trans,Env.XML); - } while(report.go()); + Trans trans; + Report report = new Report(ITERATIONS,"XML"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + TimeTaken tt = trans.start("JAXB", Env.XML); + try { + jaxBmar.marshal(LogTarget.NULL, ld, sbw); + } finally { + tt.done(); + } + report.glean(trans,Env.XML); + } while(report.go()); - report.report(sbw); - System.out.println(sbw.toString()); - } + report.report(sbw); + System.out.println(sbw.toString()); + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java index 58813621..2a4e3d2d 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java @@ -43,217 +43,217 @@ import org.onap.aaf.misc.rosetta.OutXML; import s.xsd.LargerData; public class JU_FromXML { - private static int ITERATIONS = 1; - ; - - private final static String xml = - "\n" + - "\n" + - " \n" + - " sd object 1\n" + - " 1346765355134\n" + - " Item 1.1\n" + - " Item 1.2\n" + - " \n" + - " \n" + - " sd object 2\n" + - " 1346765355134\n" + - " Item 2.1\n" + - " Item 2.2\n" + - " \n" + - " MyFluff\n" + - "\n"; - - - @Test - public void test() throws Exception { - InXML inXML = new InXML(LargerData.class); - - System.out.println(xml); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - - Reader rdr = new StringReader(xml); - - new OutRaw().extract(rdr, sbw, inXML); - System.out.println(sbw.getBuffer()); - } - + private static int ITERATIONS = 1; + ; + + private final static String xml = + "\n" + + "\n" + + " \n" + + " sd object 1\n" + + " 1346765355134\n" + + " Item 1.1\n" + + " Item 1.2\n" + + " \n" + + " \n" + + " sd object 2\n" + + " 1346765355134\n" + + " Item 2.1\n" + + " Item 2.2\n" + + " \n" + + " MyFluff\n" + + "\n"; + + + @Test + public void test() throws Exception { + InXML inXML = new InXML(LargerData.class); + + System.out.println(xml); + StringBuilderWriter sbw = new StringBuilderWriter(1024); + + Reader rdr = new StringReader(xml); + + new OutRaw().extract(rdr, sbw, inXML); + System.out.println(sbw.getBuffer()); + } + - @Test - public void xml2JSON() throws Exception { - System.out.println("*** XML -> JSON (No Warm up) ***"); - Out jout = new OutJson(); - InXML inXML = new InXML(LargerData.class); + @Test + public void xml2JSON() throws Exception { + System.out.println("*** XML -> JSON (No Warm up) ***"); + Out jout = new OutJson(); + InXML inXML = new InXML(LargerData.class); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - - Trans trans; - Report report = new Report(ITERATIONS,"XML"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Reader sr = new StringReader(xml); - TimeTaken tt = trans.start("Parse XML", Env.XML); - try { - jout.extract(sr, sbw, inXML); - } finally { - tt.done(); - } - report.glean(trans,Env.XML); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); - } + StringBuilderWriter sbw = new StringBuilderWriter(1024); + + Trans trans; + Report report = new Report(ITERATIONS,"XML"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Reader sr = new StringReader(xml); + TimeTaken tt = trans.start("Parse XML", Env.XML); + try { + jout.extract(sr, sbw, inXML); + } finally { + tt.done(); + } + report.glean(trans,Env.XML); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); + } - @Test - public void xml2XML() throws Exception { - System.out.println("*** XML -> (Event Queue) -> XML (No Warm up) ***"); - Out xout = new OutXML("LargerData"); - InXML inXML = new InXML(LargerData.class); + @Test + public void xml2XML() throws Exception { + System.out.println("*** XML -> (Event Queue) -> XML (No Warm up) ***"); + Out xout = new OutXML("LargerData"); + InXML inXML = new InXML(LargerData.class); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - - Trans trans; - Report report = new Report(ITERATIONS,"XML"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Reader sr = new StringReader(xml); - TimeTaken tt = trans.start("Parse XML", Env.XML); - try { - xout.extract(sr, sbw, inXML); - } finally { - tt.done(); - } - report.glean(trans,Env.XML); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); - } - - - @Test - public void warmup() throws Exception { - if(ITERATIONS>20) { - System.out.println("*** Warmup JAXB ***"); - - JAXBumar jaxbUmar = new JAXBumar(LargerData.class); - JAXBmar jaxBmar = new JAXBmar(LargerData.class); - //jaxBmar.asFragment(true); - //jaxBmar.pretty(true); - StringBuilderWriter sbw = new StringBuilderWriter(1024); - + StringBuilderWriter sbw = new StringBuilderWriter(1024); + + Trans trans; + Report report = new Report(ITERATIONS,"XML"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Reader sr = new StringReader(xml); + TimeTaken tt = trans.start("Parse XML", Env.XML); + try { + xout.extract(sr, sbw, inXML); + } finally { + tt.done(); + } + report.glean(trans,Env.XML); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); + } + + + @Test + public void warmup() throws Exception { + if(ITERATIONS>20) { + System.out.println("*** Warmup JAXB ***"); + + JAXBumar jaxbUmar = new JAXBumar(LargerData.class); + JAXBmar jaxBmar = new JAXBmar(LargerData.class); + //jaxBmar.asFragment(true); + //jaxBmar.pretty(true); + StringBuilderWriter sbw = new StringBuilderWriter(1024); + - LargerData ld; - Trans trans; - Report report = new Report(ITERATIONS,"XML"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - TimeTaken all = trans.start("Combo", Env.SUB); - try { - TimeTaken tt = trans.start("JAXB Unmarshal", Env.XML); - try { - ld = jaxbUmar.unmarshal(LogTarget.NULL, xml); - } finally { - tt.done(); - } - tt = trans.start("JAXB marshal", Env.XML); - try { - jaxBmar.marshal(LogTarget.NULL, ld, sbw); - } finally { - tt.done(); - } - } finally { - all.done(); - } - report.glean(trans,Env.XML); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); - } - } - @Test - public void xml2jaxb2xml() throws Exception { - System.out.println("*** XML -> JAXB Object -> XML ***"); - JAXBumar jaxbUmar = new JAXBumar(LargerData.class); - JAXBmar jaxBmar = new JAXBmar(LargerData.class); - //jaxBmar.asFragment(true); - //jaxBmar.pretty(true); - StringBuilderWriter sbw = new StringBuilderWriter(1024); + LargerData ld; + Trans trans; + Report report = new Report(ITERATIONS,"XML"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + TimeTaken all = trans.start("Combo", Env.SUB); + try { + TimeTaken tt = trans.start("JAXB Unmarshal", Env.XML); + try { + ld = jaxbUmar.unmarshal(LogTarget.NULL, xml); + } finally { + tt.done(); + } + tt = trans.start("JAXB marshal", Env.XML); + try { + jaxBmar.marshal(LogTarget.NULL, ld, sbw); + } finally { + tt.done(); + } + } finally { + all.done(); + } + report.glean(trans,Env.XML); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); + } + } + @Test + public void xml2jaxb2xml() throws Exception { + System.out.println("*** XML -> JAXB Object -> XML ***"); + JAXBumar jaxbUmar = new JAXBumar(LargerData.class); + JAXBmar jaxBmar = new JAXBmar(LargerData.class); + //jaxBmar.asFragment(true); + //jaxBmar.pretty(true); + StringBuilderWriter sbw = new StringBuilderWriter(1024); - LargerData ld; - Trans trans; - Report report = new Report(ITERATIONS,"XML"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - TimeTaken all = trans.start("Combo", Env.SUB); - try { - TimeTaken tt = trans.start("JAXB Unmarshal", Env.XML); - try { - ld = jaxbUmar.unmarshal(LogTarget.NULL, xml); - } finally { - tt.done(); - } - tt = trans.start("JAXB marshal", Env.XML); - try { - jaxBmar.marshal(LogTarget.NULL, ld, sbw); - } finally { - tt.done(); - } - } finally { - all.done(); - } - report.glean(trans,Env.XML); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); } + LargerData ld; + Trans trans; + Report report = new Report(ITERATIONS,"XML"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + TimeTaken all = trans.start("Combo", Env.SUB); + try { + TimeTaken tt = trans.start("JAXB Unmarshal", Env.XML); + try { + ld = jaxbUmar.unmarshal(LogTarget.NULL, xml); + } finally { + tt.done(); + } + tt = trans.start("JAXB marshal", Env.XML); + try { + jaxBmar.marshal(LogTarget.NULL, ld, sbw); + } finally { + tt.done(); + } + } finally { + all.done(); + } + report.glean(trans,Env.XML); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); } - @Test - public void xml2jaxb2PrettyXml() throws Exception { - System.out.println("*** XML -> JAXB Object -> Pretty XML ***"); - JAXBumar jaxbUmar = new JAXBumar(LargerData.class); - JAXBmar jaxBmar = new JAXBmar(LargerData.class); - //jaxBmar.asFragment(true); - jaxBmar.pretty(true); - StringBuilderWriter sbw = new StringBuilderWriter(1024); + @Test + public void xml2jaxb2PrettyXml() throws Exception { + System.out.println("*** XML -> JAXB Object -> Pretty XML ***"); + JAXBumar jaxbUmar = new JAXBumar(LargerData.class); + JAXBmar jaxBmar = new JAXBmar(LargerData.class); + //jaxBmar.asFragment(true); + jaxBmar.pretty(true); + StringBuilderWriter sbw = new StringBuilderWriter(1024); - Trans trans = EnvFactory.newTrans(); - LargerData ld; - for(int i=0;i20) { - m = trans.auditTrail(0,null); - } else { - m = trans.auditTrail(0, sbw.getBuffer()); - System.out.println(sbw.getBuffer()); - } - System.out.println(ITERATIONS + " entries, Total Time: " + m.total + "ms, Avg Time: " + m.total/ITERATIONS + "ms"); - } + Trans trans = EnvFactory.newTrans(); + LargerData ld; + for(int i=0;i20) { + m = trans.auditTrail(0,null); + } else { + m = trans.auditTrail(0, sbw.getBuffer()); + System.out.println(sbw.getBuffer()); + } + System.out.println(ITERATIONS + " entries, Total Time: " + m.total + "ms, Avg Time: " + m.total/ITERATIONS + "ms"); + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java index 080fc973..9ab06e7c 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java @@ -38,99 +38,99 @@ import org.onap.aaf.misc.rosetta.ParseException; public class JU_JSON { - @Test - public void test() throws IOException, ParseException { - InJson jin = new InJson(); - Out jout = new OutJson(); - - go(jin, jout, "{\"id\":\"Me, Myself\",\"date\":1353094689100}"); - - go(jin, jout, "{\"id\":\"My ID 1\",\"desc\":\"My Description 1\",\"comment\":[\"My Comment 1\"],\"utc\":1360418381310}"); - go(jin, jout, "{\"id\":\"My ID 1\",\"desc\":\"My Description 1\",\"comment\":[\"My Comment 1\",\"My Comment 2\"],\"utc\":1360418381310}"); - - go(jin, jout, "{\"SampleData\":[" + - "{\"id\":\"sd object \\\"1\\\"\",\"date\":1316084944213,\"item\":[\"Item 1.1\",\"Item 1.2\"]}," + - "{\"id\":\"sd object \\\"2\\\"\",\"date\":1316084945343,\"item\":[\"Item 2.1\",\"Item 2.2\"]}],\"fluff\":\"MyFluff\"}" - ); - - go(jin, jout, "{\"SampleData\":[{\"date\":1316084945343}],\"fluff\":\"MyFluff\"}"); - - go(jin, jout, "{\"id\":\"Me,[}[eg[)(:x,\\\" Myself\",\"date\":1353094689100}"); - - // TODO: Clean out AT&T specific data - go(jin,jout, "{\"userid\":\"xk3233\",\"timestamp\":1353097388531,\"item\":[{\"tag\":\"color\",\"value\":\"Mauve\"},{\"tag\":\"shirtsize\",\"value\":\"Xtra Large\"}]}"); - //go() - //"xk32331353082669667"); - - // 3/11/2015 Jonathan found a case with missing comma - go(jin,jout, "{\"start\":\"2015-03-11T18:18:05.580-05:00\",\"end\":\"2015-09-11-05:00\",\"force\":\"false\",\"perm\":{\"type\":\"org.osaaf.myns.mytype\",\"instance\":\"myInstance\",\"action\":\"myAction\"}" - + ",\"role\":\"org.osaaf.myns.myrole\"}"); - - // 3/12/2015 Jonathan Kurt Schurenberg noticed an issue of object names in an array. This is valid code. - go(jin,jout, "{\"role\":[{\"name\":\"org.osaaf.myns.myrole\",\"perms\":[{\"type\":\"org.osaaf.myns.mytype\",\"instance\":\"myAction\"},{\"type\":\"org.osaaf.myns.mytype\",\"instance\":\"myOtherAction\"}]}" - + ",{\"name\":\"org.osaaf.myns.myOtherRole\",\"perms\":[{\"type\":\"org.osaaf.myns.myOtherType\",\"instance\":\"myAction\"},{\"type\":\"org.osaaf.myns.myOthertype\",\"instance\":\"myOtherAction\"}]}]}"); - - // 3/13/2015 - discovered with complex Response - go(jin,jout, "{\"meth\":\"GET\",\"path\":\"/authz/perms/:type\",\"desc\":\"GetPermsByType\",\"comments\":[\"List All Permissions that match :type listed\"]," - + "\"contentType\":[\"application/Permissions+json;q=1.0;charset=utf-8;version=1.1,application/json;q=1.0;version=1.1\"" - + ",\"application/Perms+xml;q=1.0;charset=utf-8;version=2.0,text/xml;q=1.0;version=2.0\",\"application/Perms+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0\"" - + ",\"application/Permissions+xml;q=1.0;charset=utf-8;version=1.1,text/xml;q=1.0;version=1.1\"]}"); - - - // Test a Windoze "Pretty Print", validate skipping of Windoze characters as well as other odd control characters listed - // in json.org - StringWriter sw = new StringWriter(); - jout.extract(new StringReader( - "{\b\f\n\r\t \"id\"" - + ":\"Me, \b\f\n\r\tMyself\",\"date\":1353094689100" - + "\b\f\n\r\t }" - ),sw,jin); - Assert.assertEquals("{\"id\":\"Me, \b\f\n\r\tMyself\",\"date\":1353094689100}",sw.toString()); - System.out.println(sw.toString()); - - // 10/01/2015 Jonathan AAF-703 Ron Gallagher, this response is ok - go(jin,jout, "{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":\"myAction\",\"description\":\"something\"}]}"); - // but when description:"" causes extra comma at end - go(jin,jout, "{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":\"myAction\",\"description\":\"\"}]}","{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":\"myAction\"}]}"); - // Test other empty string scenarios - go(jin,jout, "{\"perm\":[{\"type\":\"\",\"action\":\"\",\"description\":\"\"}]}","{\"perm\":[{}]}"); - go(jin,jout, "{\"perm\":[{\"type\":\"\",\"action\":\"\",\"description\":\"hi\"}]}","{\"perm\":[{\"description\":\"hi\"}]}"); - go(jin,jout, "{\"perm\":[{\"type\":\"\",\"action\":\"myAction\",\"description\":\"\"}]}","{\"perm\":[{\"action\":\"myAction\"}]}"); - - - go(jin,jout, "{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":,\"description\":\"something\"}]}","{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"description\":\"something\"}]}"); - - go(jin, jout, "{\"name\":\"\\\"hello\\\"\"}"); - - go(jin, jout, "{\"name\":\"\\\\\"}"); - - go(jin, jout, "{\"role\":\"org.osaaf.scamper.UserStory0152 7_IT-00323-a-admin\",\"perm\":{\"type\":\"org.osaaf.scamper.application\",\"instance\":\"_()`!@#\\\\$%^=+][{}<>/.-valid.app.name-is_good\",\"action\":\"Administrator\"}}"); - - - } - - - private void go(Parse in, Out out, String str) throws IOException, ParseException { - go(in,out,str,str); - } - - - private void go(Parse in, Out out, String str, String cmp) throws IOException, ParseException { - - System.out.println(str); - StringWriter sw = new StringWriter(1024); - out.extract(new StringReader(str), sw, in); - System.out.println(sw); - String result = sw.toString(); - - if(!result.equals(cmp)) { - sw.getBuffer().setLength(0); - new OutRaw().extract(new StringReader(str), sw, in); - System.out.println(sw); - } - - Assert.assertEquals(cmp,result); - System.out.println(); - - } + @Test + public void test() throws IOException, ParseException { + InJson jin = new InJson(); + Out jout = new OutJson(); + + go(jin, jout, "{\"id\":\"Me, Myself\",\"date\":1353094689100}"); + + go(jin, jout, "{\"id\":\"My ID 1\",\"desc\":\"My Description 1\",\"comment\":[\"My Comment 1\"],\"utc\":1360418381310}"); + go(jin, jout, "{\"id\":\"My ID 1\",\"desc\":\"My Description 1\",\"comment\":[\"My Comment 1\",\"My Comment 2\"],\"utc\":1360418381310}"); + + go(jin, jout, "{\"SampleData\":[" + + "{\"id\":\"sd object \\\"1\\\"\",\"date\":1316084944213,\"item\":[\"Item 1.1\",\"Item 1.2\"]}," + + "{\"id\":\"sd object \\\"2\\\"\",\"date\":1316084945343,\"item\":[\"Item 2.1\",\"Item 2.2\"]}],\"fluff\":\"MyFluff\"}" + ); + + go(jin, jout, "{\"SampleData\":[{\"date\":1316084945343}],\"fluff\":\"MyFluff\"}"); + + go(jin, jout, "{\"id\":\"Me,[}[eg[)(:x,\\\" Myself\",\"date\":1353094689100}"); + + // TODO: Clean out AT&T specific data + go(jin,jout, "{\"userid\":\"xk3233\",\"timestamp\":1353097388531,\"item\":[{\"tag\":\"color\",\"value\":\"Mauve\"},{\"tag\":\"shirtsize\",\"value\":\"Xtra Large\"}]}"); + //go() + //"xk32331353082669667"); + + // 3/11/2015 Jonathan found a case with missing comma + go(jin,jout, "{\"start\":\"2015-03-11T18:18:05.580-05:00\",\"end\":\"2015-09-11-05:00\",\"force\":\"false\",\"perm\":{\"type\":\"org.osaaf.myns.mytype\",\"instance\":\"myInstance\",\"action\":\"myAction\"}" + + ",\"role\":\"org.osaaf.myns.myrole\"}"); + + // 3/12/2015 Jonathan Kurt Schurenberg noticed an issue of object names in an array. This is valid code. + go(jin,jout, "{\"role\":[{\"name\":\"org.osaaf.myns.myrole\",\"perms\":[{\"type\":\"org.osaaf.myns.mytype\",\"instance\":\"myAction\"},{\"type\":\"org.osaaf.myns.mytype\",\"instance\":\"myOtherAction\"}]}" + + ",{\"name\":\"org.osaaf.myns.myOtherRole\",\"perms\":[{\"type\":\"org.osaaf.myns.myOtherType\",\"instance\":\"myAction\"},{\"type\":\"org.osaaf.myns.myOthertype\",\"instance\":\"myOtherAction\"}]}]}"); + + // 3/13/2015 - discovered with complex Response + go(jin,jout, "{\"meth\":\"GET\",\"path\":\"/authz/perms/:type\",\"desc\":\"GetPermsByType\",\"comments\":[\"List All Permissions that match :type listed\"]," + + "\"contentType\":[\"application/Permissions+json;q=1.0;charset=utf-8;version=1.1,application/json;q=1.0;version=1.1\"" + + ",\"application/Perms+xml;q=1.0;charset=utf-8;version=2.0,text/xml;q=1.0;version=2.0\",\"application/Perms+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0\"" + + ",\"application/Permissions+xml;q=1.0;charset=utf-8;version=1.1,text/xml;q=1.0;version=1.1\"]}"); + + + // Test a Windoze "Pretty Print", validate skipping of Windoze characters as well as other odd control characters listed + // in json.org + StringWriter sw = new StringWriter(); + jout.extract(new StringReader( + "{\b\f\n\r\t \"id\"" + + ":\"Me, \b\f\n\r\tMyself\",\"date\":1353094689100" + + "\b\f\n\r\t }" + ),sw,jin); + Assert.assertEquals("{\"id\":\"Me, \b\f\n\r\tMyself\",\"date\":1353094689100}",sw.toString()); + System.out.println(sw.toString()); + + // 10/01/2015 Jonathan AAF-703 Ron Gallagher, this response is ok + go(jin,jout, "{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":\"myAction\",\"description\":\"something\"}]}"); + // but when description:"" causes extra comma at end + go(jin,jout, "{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":\"myAction\",\"description\":\"\"}]}","{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":\"myAction\"}]}"); + // Test other empty string scenarios + go(jin,jout, "{\"perm\":[{\"type\":\"\",\"action\":\"\",\"description\":\"\"}]}","{\"perm\":[{}]}"); + go(jin,jout, "{\"perm\":[{\"type\":\"\",\"action\":\"\",\"description\":\"hi\"}]}","{\"perm\":[{\"description\":\"hi\"}]}"); + go(jin,jout, "{\"perm\":[{\"type\":\"\",\"action\":\"myAction\",\"description\":\"\"}]}","{\"perm\":[{\"action\":\"myAction\"}]}"); + + + go(jin,jout, "{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"action\":,\"description\":\"something\"}]}","{\"perm\":[{\"type\":\"org.osaaf.myns.myPerm\",\"description\":\"something\"}]}"); + + go(jin, jout, "{\"name\":\"\\\"hello\\\"\"}"); + + go(jin, jout, "{\"name\":\"\\\\\"}"); + + go(jin, jout, "{\"role\":\"org.osaaf.scamper.UserStory0152 7_IT-00323-a-admin\",\"perm\":{\"type\":\"org.osaaf.scamper.application\",\"instance\":\"_()`!@#\\\\$%^=+][{}<>/.-valid.app.name-is_good\",\"action\":\"Administrator\"}}"); + + + } + + + private void go(Parse in, Out out, String str) throws IOException, ParseException { + go(in,out,str,str); + } + + + private void go(Parse in, Out out, String str, String cmp) throws IOException, ParseException { + + System.out.println(str); + StringWriter sw = new StringWriter(1024); + out.extract(new StringReader(str), sw, in); + System.out.println(sw); + String result = sw.toString(); + + if(!result.equals(cmp)) { + sw.getBuffer().setLength(0); + new OutRaw().extract(new StringReader(str), sw, in); + System.out.println(sw); + } + + Assert.assertEquals(cmp,result); + System.out.println(); + + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java index f72b6e69..229f1bf4 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java @@ -28,49 +28,49 @@ import static org.junit.Assert.*; public class JU_Ladder { - @Test - public void test() { - Ladder ladder = new Ladder(); - - for(int i=0;i<30;++i) { - for(int j=0;j ladder = new Ladder(); + + for(int i=0;i<30;++i) { + for(int j=0;j df = env.newDataFactory(LargerData.class); - df.out(Data.TYPE.JSON); - LargerData urr = new LargerData(); - SampleData sd = new SampleData(); - sd.setDate(1444125487798L); - sd.setId(null); - urr.getSampleData().add(sd); - urr.setFluff(null); - RosettaData data = df.newData(); -// StringWriter sw = new StringWriter(); -// df.direct(trans, urr, sw); -// System.out.println(sw.toString()); - data.load(urr); - System.out.println(data.asString()); - Assert.assertEquals("{\"SampleData\":[{\"date\":1444125487798}]}", data.asString()); - - System.out.println(data.out(Data.TYPE.RAW).asString()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } + @Test + public void test() { + RosettaEnv env = new RosettaEnv(); + try { + RosettaDF df = env.newDataFactory(LargerData.class); + df.out(Data.TYPE.JSON); + LargerData urr = new LargerData(); + SampleData sd = new SampleData(); + sd.setDate(1444125487798L); + sd.setId(null); + urr.getSampleData().add(sd); + urr.setFluff(null); + RosettaData data = df.newData(); +// StringWriter sw = new StringWriter(); +// df.direct(trans, urr, sw); +// System.out.println(sw.toString()); + data.load(urr); + System.out.println(data.asString()); + Assert.assertEquals("{\"SampleData\":[{\"date\":1444125487798}]}", data.asString()); + + System.out.println(data.out(Data.TYPE.RAW).asString()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java index 07c73196..1a5f86f3 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java @@ -41,122 +41,122 @@ import s.xsd.Multi; import s.xsd.SampleData; public class JU_RosettaDF { - public static int ITERATIONS = 1; - - @Test - public void testCached() throws Exception { - RosettaEnv env = new RosettaEnv(); - RosettaDF df = env.newDataFactory(LargerData.class); - JAXBmar jmar = new JAXBmar(LargerData.class); - - StringBuilderWriter sbw = new StringBuilderWriter(1024); - Trans trans = EnvFactory.newTrans(); - - Report report = new Report(ITERATIONS,"Load JSON","Extract JAXB", "JAXB Marshal", "Cached to XML", "Cached to JSON"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Data data; - TimeTaken tt = trans.start("Load JSON", 1); - try { - data = df.newData(trans).out(Data.TYPE.JSON).in(Data.TYPE.JSON).load(JU_FromJSON.str); - } finally { - tt.done(); - } - LargerData ld; - tt = trans.start("Extract JAXB", 2); - try { - ld = data.asObject(); - } finally { - tt.done(); - } - - tt = trans.start("JAXB marshal", 3); - try { - jmar.marshal(trans.debug(), ld, sbw); - } finally { - tt.done(); - } - sbw.append('\n'); - - tt = trans.start("To XML from Cache",4); - try { - data.out(Data.TYPE.XML).to(sbw); - } finally { - tt.done(); - } - - sbw.append('\n'); - - tt = trans.start("To JSON from Cache",5); - try { - data.out(Data.TYPE.JSON).to(sbw); - } finally { - tt.done(); - } - report.glean(trans, 1,2,3,4,5); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw); - - } - - @Test - public void testDirect() throws Exception { - RosettaEnv env = new RosettaEnv(); - RosettaDF df = env.newDataFactory(LargerData.class); - - StringBuilderWriter sbw = new StringBuilderWriter(1024); - Trans trans = EnvFactory.newTrans(); - - Report report = new Report(ITERATIONS); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - RosettaData data = df.newData(trans).in(Data.TYPE.JSON).out(Data.TYPE.XML); - data.direct(new StringReader(JU_FromJSON.str), sbw); - report.glean(trans); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw); - - } - - @Test - public void testMulti() throws Exception { - RosettaEnv env = new RosettaEnv(); - RosettaDF df = env.newDataFactory(Multi.class); - -// StringBuilderWriter sbw = new StringBuilderWriter(1024); -// Trans trans = EnvFactory.newTrans(); - - Multi m = new Multi(); - m.getF1().add("String1"); - m.getF2().add("String2"); - - System.out.println(df.newData().load(m).out(TYPE.RAW).asString()); - System.out.println(df.newData().load(m).out(TYPE.JSON).asString()); - - } - - @Test - public void testQuotes() throws Exception { - RosettaEnv env = new RosettaEnv(); - RosettaDF df = env.newDataFactory(SampleData.class); - - SampleData sd = new SampleData(); - sd.setId("\"AT&T Services, Inc.\""); - System.out.println(sd.getId()); - String out =df.newData().load(sd).out(TYPE.JSON).asString(); - System.out.println(out); - Assert.assertEquals( - "{\"id\":\"\\\"AT&T Services, Inc.\\\"\",\"date\":0}", - out); - - SampleData sd2 = df.newData().in(TYPE.JSON).load(out).asObject(); - System.out.println(sd2.getId()); - Assert.assertEquals(sd.getId(),sd2.getId()); - } + public static int ITERATIONS = 1; + + @Test + public void testCached() throws Exception { + RosettaEnv env = new RosettaEnv(); + RosettaDF df = env.newDataFactory(LargerData.class); + JAXBmar jmar = new JAXBmar(LargerData.class); + + StringBuilderWriter sbw = new StringBuilderWriter(1024); + Trans trans = EnvFactory.newTrans(); + + Report report = new Report(ITERATIONS,"Load JSON","Extract JAXB", "JAXB Marshal", "Cached to XML", "Cached to JSON"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Data data; + TimeTaken tt = trans.start("Load JSON", 1); + try { + data = df.newData(trans).out(Data.TYPE.JSON).in(Data.TYPE.JSON).load(JU_FromJSON.str); + } finally { + tt.done(); + } + LargerData ld; + tt = trans.start("Extract JAXB", 2); + try { + ld = data.asObject(); + } finally { + tt.done(); + } + + tt = trans.start("JAXB marshal", 3); + try { + jmar.marshal(trans.debug(), ld, sbw); + } finally { + tt.done(); + } + sbw.append('\n'); + + tt = trans.start("To XML from Cache",4); + try { + data.out(Data.TYPE.XML).to(sbw); + } finally { + tt.done(); + } + + sbw.append('\n'); + + tt = trans.start("To JSON from Cache",5); + try { + data.out(Data.TYPE.JSON).to(sbw); + } finally { + tt.done(); + } + report.glean(trans, 1,2,3,4,5); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw); + + } + + @Test + public void testDirect() throws Exception { + RosettaEnv env = new RosettaEnv(); + RosettaDF df = env.newDataFactory(LargerData.class); + + StringBuilderWriter sbw = new StringBuilderWriter(1024); + Trans trans = EnvFactory.newTrans(); + + Report report = new Report(ITERATIONS); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + RosettaData data = df.newData(trans).in(Data.TYPE.JSON).out(Data.TYPE.XML); + data.direct(new StringReader(JU_FromJSON.str), sbw); + report.glean(trans); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw); + + } + + @Test + public void testMulti() throws Exception { + RosettaEnv env = new RosettaEnv(); + RosettaDF df = env.newDataFactory(Multi.class); + +// StringBuilderWriter sbw = new StringBuilderWriter(1024); +// Trans trans = EnvFactory.newTrans(); + + Multi m = new Multi(); + m.getF1().add("String1"); + m.getF2().add("String2"); + + System.out.println(df.newData().load(m).out(TYPE.RAW).asString()); + System.out.println(df.newData().load(m).out(TYPE.JSON).asString()); + + } + + @Test + public void testQuotes() throws Exception { + RosettaEnv env = new RosettaEnv(); + RosettaDF df = env.newDataFactory(SampleData.class); + + SampleData sd = new SampleData(); + sd.setId("\"AT&T Services, Inc.\""); + System.out.println(sd.getId()); + String out =df.newData().load(sd).out(TYPE.JSON).asString(); + System.out.println(out); + Assert.assertEquals( + "{\"id\":\"\\\"AT&T Services, Inc.\\\"\",\"date\":0}", + out); + + SampleData sd2 = df.newData().in(TYPE.JSON).load(out).asObject(); + System.out.println(sd2.getId()); + Assert.assertEquals(sd.getId(),sd2.getId()); + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java index 47953007..de1b5500 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java @@ -38,67 +38,67 @@ import org.onap.aaf.misc.rosetta.Saved; import s.xsd.LargerData; public class JU_Saved { - private static int ITERATIONS = 100000; + private static int ITERATIONS = 100000; - @Test - public void test() throws Exception { - InJson inJSON = new InJson(); - OutDump dump = new OutDump(); - JaxInfo ji = JaxInfo.build(LargerData.class); - OutXML xml = new OutXML(ji);; - OutJson json = new OutJson(); - - Saved saved = new Saved(); - - StringBuilderWriter sbw = new StringBuilderWriter(1024); - - Trans trans; - Report report = new Report(ITERATIONS,"Save","Dump","XML ","JSON"); - do { - sbw.reset(); - trans = EnvFactory.newTrans(); - Reader sr = new StringReader(JU_FromJSON.str); - TimeTaken tt = trans.start("Parse Text, and Save", 1); - try { - saved.load(sr, inJSON); - } finally { - tt.done(); - } + @Test + public void test() throws Exception { + InJson inJSON = new InJson(); + OutDump dump = new OutDump(); + JaxInfo ji = JaxInfo.build(LargerData.class); + OutXML xml = new OutXML(ji);; + OutJson json = new OutJson(); + + Saved saved = new Saved(); + + StringBuilderWriter sbw = new StringBuilderWriter(1024); + + Trans trans; + Report report = new Report(ITERATIONS,"Save","Dump","XML ","JSON"); + do { + sbw.reset(); + trans = EnvFactory.newTrans(); + Reader sr = new StringReader(JU_FromJSON.str); + TimeTaken tt = trans.start("Parse Text, and Save", 1); + try { + saved.load(sr, inJSON); + } finally { + tt.done(); + } -// sbw.append("==== Start Direct Raw =====\n"); -// new OutRaw().extract(new StringReader(JU_FromJSON.str), sbw, inJSON); -// -// sbw.append("==== Start Raw from Saved =====\n"); -// new OutRaw().extract(null,sbw,saved); +// sbw.append("==== Start Direct Raw =====\n"); +// new OutRaw().extract(new StringReader(JU_FromJSON.str), sbw, inJSON); +// +// sbw.append("==== Start Raw from Saved =====\n"); +// new OutRaw().extract(null,sbw,saved); - sbw.append("==== Start Dump from Saved =====\n"); - tt = trans.start("Dump", 2); - try { - dump.extract(null,sbw,saved); - } finally { - tt.done(); - } - - sbw.append("\n==== Start XML =====\n"); - tt = trans.start("XML", 3); - try { - xml.extract(null,sbw,saved); - } finally { - tt.done(); - } - - sbw.append("\n==== Start JSON =====\n"); - tt = trans.start("JSON", 4); - try { - json.extract(null,sbw,saved); - } finally { - tt.done(); - } - report.glean(trans,1,2,3,4); - } while(report.go()); - - report.report(sbw); - System.out.println(sbw.toString()); + sbw.append("==== Start Dump from Saved =====\n"); + tt = trans.start("Dump", 2); + try { + dump.extract(null,sbw,saved); + } finally { + tt.done(); + } + + sbw.append("\n==== Start XML =====\n"); + tt = trans.start("XML", 3); + try { + xml.extract(null,sbw,saved); + } finally { + tt.done(); + } + + sbw.append("\n==== Start JSON =====\n"); + tt = trans.start("JSON", 4); + try { + json.extract(null,sbw,saved); + } finally { + tt.done(); + } + report.glean(trans,1,2,3,4); + } while(report.go()); + + report.report(sbw); + System.out.println(sbw.toString()); - } + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Stream2Obj.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Stream2Obj.java index 6047c03c..b0fc29a2 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Stream2Obj.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Stream2Obj.java @@ -46,78 +46,78 @@ import org.onap.aaf.misc.rosetta.ParseException; public class JU_Stream2Obj { - /* - - - - myDerivedA_1 - 1432 - mda_1 - value_1 - value_2 - - - - {"base":[{"__extension":"derivedA","name":"myDerivedA_1","num":1432,"shortName":"mda_1","value":["value_1","value_2"]}]} - */ - - @Test - public void json2Obj() throws APIException, SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException, IOException { - DerivedA da = new DerivedA(); - da.setName("myDerivedA_1"); - da.setNum((short)1432); - da.setShortName("mda_1"); - da.getValue().add("value_1"); - da.getValue().add("value_2"); - - Root root = new Root(); - root.getBase().add(da); - - da = new DerivedA(); - da.setName("myDerivedA_2"); - da.setNum((short)1432); - da.setShortName("mda_2"); - da.getValue().add("value_2.1"); - da.getValue().add("value_2.2"); - root.getBase().add(da); - - EnvJAXB env = new BasicEnv(); - DataFactory rootDF = env.newDataFactory(Root.class); - - String xml = rootDF.newData(env).out(Data.TYPE.XML).load(root).option(Data.PRETTY).asString(); - System.out.println(xml); - - InXML inXML; - Parse in = inXML = new InXML(Root.class); - Out out = new OutRaw(); - - StringWriter sw = new StringWriter(); - out.extract(new StringReader(xml), sw, in); - System.out.println(sw.toString()); - - - out = new OutJson(); - - sw = new StringWriter(); - out.extract(new StringReader(xml), sw, in); - String json; - System.out.println(json = sw.toString()); - - in = new InJson(); - out = new OutRaw(); - - sw = new StringWriter(); - out.extract(new StringReader(json), sw, in); - System.out.println(sw.toString()); - - out = new OutXML(inXML); - - sw = new StringWriter(); - out.extract(new StringReader(json), sw, in, true); - System.out.println(sw.toString()); - - System.out.flush(); - - } + /* + + + + myDerivedA_1 + 1432 + mda_1 + value_1 + value_2 + + + + {"base":[{"__extension":"derivedA","name":"myDerivedA_1","num":1432,"shortName":"mda_1","value":["value_1","value_2"]}]} + */ + + @Test + public void json2Obj() throws APIException, SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException, IOException { + DerivedA da = new DerivedA(); + da.setName("myDerivedA_1"); + da.setNum((short)1432); + da.setShortName("mda_1"); + da.getValue().add("value_1"); + da.getValue().add("value_2"); + + Root root = new Root(); + root.getBase().add(da); + + da = new DerivedA(); + da.setName("myDerivedA_2"); + da.setNum((short)1432); + da.setShortName("mda_2"); + da.getValue().add("value_2.1"); + da.getValue().add("value_2.2"); + root.getBase().add(da); + + EnvJAXB env = new BasicEnv(); + DataFactory rootDF = env.newDataFactory(Root.class); + + String xml = rootDF.newData(env).out(Data.TYPE.XML).load(root).option(Data.PRETTY).asString(); + System.out.println(xml); + + InXML inXML; + Parse in = inXML = new InXML(Root.class); + Out out = new OutRaw(); + + StringWriter sw = new StringWriter(); + out.extract(new StringReader(xml), sw, in); + System.out.println(sw.toString()); + + + out = new OutJson(); + + sw = new StringWriter(); + out.extract(new StringReader(xml), sw, in); + String json; + System.out.println(json = sw.toString()); + + in = new InJson(); + out = new OutRaw(); + + sw = new StringWriter(); + out.extract(new StringReader(json), sw, in); + System.out.println(sw.toString()); + + out = new OutXML(inXML); + + sw = new StringWriter(); + out.extract(new StringReader(json), sw, in, true); + System.out.println(sw.toString()); + + System.out.flush(); + + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java index 1209e77d..7e767e5d 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java @@ -27,47 +27,47 @@ import org.onap.aaf.misc.rosetta.JaxInfo; import s.xsd.LargerData; public class JU_Struct { - public final static String XML ="\n" + - "\n" + - "sd object 1\n" + - "1346439215932\n" + - "Item 1.1\n" + - "Item 1.2\n" + - "\n" + - "\n" + - "sd object 2\n" + - "1346439215932\n" + - "Item 2.1\n" + - "Item 2.2\n" + - "\n" + - "MyFluff\n" + - "\n"; - -// @Test -// public void test2() throws Exception { + public final static String XML ="\n" + + "\n" + + "sd object 1\n" + + "1346439215932\n" + + "Item 1.1\n" + + "Item 1.2\n" + + "\n" + + "\n" + + "sd object 2\n" + + "1346439215932\n" + + "Item 2.1\n" + + "Item 2.2\n" + + "\n" + + "MyFluff\n" + + "\n"; + +// @Test +// public void test2() throws Exception { // -// SampleData sd = new SampleData(); -// sd.setDate(new Date().getTime()); -// sd.setId("myId"); -// sd.getItem().add("Item 1.1"); -// -// InObj inObj = new InObj(SampleData.class); +// SampleData sd = new SampleData(); +// sd.setDate(new Date().getTime()); +// sd.setId("myId"); +// sd.getItem().add("Item 1.1"); +// +// InObj inObj = new InObj(SampleData.class); // -// JaxSet jaxSet = JaxSet.get(SampleData.class); -// Setter setter = jaxSet.setter("id"); -// setter.set(sd, "Your ID"); -// -// for(Entry> es : jaxSet.getters()) { -// System.out.print(es.getKey()); -// System.out.print(' '); -// System.out.println(es.getValue().get(sd)); -// } -// } - - @Test - public void test() throws Exception { - JaxInfo ji = JaxInfo.build(LargerData.class); - System.out.println(ji); - } +// JaxSet jaxSet = JaxSet.get(SampleData.class); +// Setter setter = jaxSet.setter("id"); +// setter.set(sd, "Your ID"); +// +// for(Entry> es : jaxSet.getters()) { +// System.out.print(es.getKey()); +// System.out.print(' '); +// System.out.println(es.getValue().get(sd)); +// } +// } + + @Test + public void test() throws Exception { + JaxInfo ji = JaxInfo.build(LargerData.class); + System.out.println(ji); + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java index 5d76e3cb..032f9f1c 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java @@ -51,251 +51,251 @@ import types.xsd.Multi.Single; public class JU_Types { - @Test - public void single() throws Exception { - Single single = setSData(); - SingleMarshal psingle = new SingleMarshal(); - - OutRaw raw = new OutRaw(); - OutJson json = new OutJson(); - OutXML xml = new OutXML("Single","xmlns=urn:types:xsd"); - - - System.out.println("===== RAW ====="); - raw.extract(single, System.out, psingle); + @Test + public void single() throws Exception { + Single single = setSData(); + SingleMarshal psingle = new SingleMarshal(); + + OutRaw raw = new OutRaw(); + OutJson json = new OutJson(); + OutXML xml = new OutXML("Single","xmlns=urn:types:xsd"); + + + System.out.println("===== RAW ====="); + raw.extract(single, System.out, psingle); - System.out.println("\n===== JSON ====="); - json.extract(single, System.out, psingle); - - System.out.println("\n\n===== Pretty JSON ====="); - json.extract(single, System.out, psingle, true); + System.out.println("\n===== JSON ====="); + json.extract(single, System.out, psingle); + + System.out.println("\n\n===== Pretty JSON ====="); + json.extract(single, System.out, psingle, true); - System.out.println("\n\n===== XML ====="); - xml.extract(single, System.out, psingle,false); + System.out.println("\n\n===== XML ====="); + xml.extract(single, System.out, psingle,false); - System.out.println("\n\n===== Pretty XML ====="); - xml.extract(single, System.out, psingle, true); + System.out.println("\n\n===== Pretty XML ====="); + xml.extract(single, System.out, psingle, true); - RosettaEnv env = new RosettaEnv(); - StringWriter sw = new StringWriter(); - xml.extract(single, sw, psingle, true); - JAXBumar jumar = new JAXBumar(single.getClass()); - JAXBmar jmar = new JAXBmar(new QName("Single","urn.types.xsd"),single.getClass()); - jmar.pretty(true); - sw = new StringWriter(); - jmar.marshal(env.info(), single, sw); - System.out.println(sw); - Single news = jumar.unmarshal(env.info(), sw.toString()); -// System.out.println(news.getDatetime()); -// sw = new StringWriter(); -// news.setDatetime(Chrono.timeStamp()); -// xml.extract(single, sw, psingle, true); - news = jumar.unmarshal(env.info(), sw.toString()); - System.out.println(sw.toString()); - - String sample = "" - + "\n" - + "\nMyString" - + "\n2147483647" - + "\n9223372036854775807" - + "\n2015-05-27-05:00" - + "\n2015-05-27T07:05:04.234-05:00" - + "\nFF00FF0E082507807F" - + "\nString 1" - + "\nString 2" - + "\n"; - System.out.println(sample); - news = jumar.unmarshal(env.info(), sample); + RosettaEnv env = new RosettaEnv(); + StringWriter sw = new StringWriter(); + xml.extract(single, sw, psingle, true); + JAXBumar jumar = new JAXBumar(single.getClass()); + JAXBmar jmar = new JAXBmar(new QName("Single","urn.types.xsd"),single.getClass()); + jmar.pretty(true); + sw = new StringWriter(); + jmar.marshal(env.info(), single, sw); + System.out.println(sw); + Single news = jumar.unmarshal(env.info(), sw.toString()); +// System.out.println(news.getDatetime()); +// sw = new StringWriter(); +// news.setDatetime(Chrono.timeStamp()); +// xml.extract(single, sw, psingle, true); + news = jumar.unmarshal(env.info(), sw.toString()); + System.out.println(sw.toString()); + + String sample = "" + + "\n" + + "\nMyString" + + "\n2147483647" + + "\n9223372036854775807" + + "\n2015-05-27-05:00" + + "\n2015-05-27T07:05:04.234-05:00" + + "\nFF00FF0E082507807F" + + "\nString 1" + + "\nString 2" + + "\n"; + System.out.println(sample); + news = jumar.unmarshal(env.info(), sample); - System.out.println(news.getDatetime()); + System.out.println(news.getDatetime()); - } - - @Test - public void multi() throws Exception { - OutRaw raw = new OutRaw(); - OutJson json = new OutJson(); - OutXML xml = new OutXML("Multi","xmlns=urn:types:xsd"); + } + + @Test + public void multi() throws Exception { + OutRaw raw = new OutRaw(); + OutJson json = new OutJson(); + OutXML xml = new OutXML("Multi","xmlns=urn:types:xsd"); - Multi multi = new Multi(); - MultiMarshal pmulti = new MultiMarshal(); - - for(int i=0;i<10;++i) { - System.out.println("===== Multi Iteration " + i + " ====="); - if(i>0) { - multi.getSingle().add(setSData()); - } - System.out.println(" ===== RAW ====="); - raw.extract(multi, System.out, pmulti); - - System.out.println("\n ===== JSON ====="); - json.extract(multi, System.out, pmulti); - - System.out.println("\n\n ===== Pretty JSON ====="); - json.extract(multi, System.out, pmulti, true); - - System.out.println("\n\n ===== XML ====="); - xml.extract(multi, System.out, pmulti,false); - - System.out.println("\n\n ===== Pretty XML ====="); - xml.extract(multi, System.out, pmulti, true); - } - } + Multi multi = new Multi(); + MultiMarshal pmulti = new MultiMarshal(); + + for(int i=0;i<10;++i) { + System.out.println("===== Multi Iteration " + i + " ====="); + if(i>0) { + multi.getSingle().add(setSData()); + } + System.out.println(" ===== RAW ====="); + raw.extract(multi, System.out, pmulti); + + System.out.println("\n ===== JSON ====="); + json.extract(multi, System.out, pmulti); + + System.out.println("\n\n ===== Pretty JSON ====="); + json.extract(multi, System.out, pmulti, true); + + System.out.println("\n\n ===== XML ====="); + xml.extract(multi, System.out, pmulti,false); + + System.out.println("\n\n ===== Pretty XML ====="); + xml.extract(multi, System.out, pmulti, true); + } + } - @Test - public void doc() throws Exception { - OutRaw raw = new OutRaw(); - OutJson json = new OutJson(); - OutXML xml = new OutXML("Multi","xmlns=urn:types:xsd"); + @Test + public void doc() throws Exception { + OutRaw raw = new OutRaw(); + OutJson json = new OutJson(); + OutXML xml = new OutXML("Multi","xmlns=urn:types:xsd"); - Multi multi = new Multi(); - DocMarshal doc = DocMarshal.root(new MultiMarshal()); - - for(int i=0;i<3;++i) { - System.out.println("===== Multi Iteration " + i + " ====="); - if(i>0) { - multi.getSingle().add(setSData()); - } - System.out.println(" ===== RAW ====="); - raw.extract(multi, System.out, doc); - - System.out.println("\n ===== JSON ====="); - json.extract(multi, System.out, doc); - - System.out.println("\n\n ===== Pretty JSON ====="); - json.extract(multi, System.out, doc, true); - - System.out.println("\n\n ===== XML ====="); - xml.extract(multi, System.out, doc,false); - - System.out.println("\n\n ===== Pretty XML ====="); - xml.extract(multi, System.out, doc, true); - } - } + Multi multi = new Multi(); + DocMarshal doc = DocMarshal.root(new MultiMarshal()); + + for(int i=0;i<3;++i) { + System.out.println("===== Multi Iteration " + i + " ====="); + if(i>0) { + multi.getSingle().add(setSData()); + } + System.out.println(" ===== RAW ====="); + raw.extract(multi, System.out, doc); + + System.out.println("\n ===== JSON ====="); + json.extract(multi, System.out, doc); + + System.out.println("\n\n ===== Pretty JSON ====="); + json.extract(multi, System.out, doc, true); + + System.out.println("\n\n ===== XML ====="); + xml.extract(multi, System.out, doc,false); + + System.out.println("\n\n ===== Pretty XML ====="); + xml.extract(multi, System.out, doc, true); + } + } -// @Test -// public void saved() throws Exception { -// Saved saved = new Saved(); -// saved.extract(in, ignore, parser, options); -// } - - @Test - public void df() throws Exception { - RosettaEnv env = new RosettaEnv(); - RosettaDF df = env.newDataFactory(Multi.class); - df.out(TYPE.JSON).option(Data.PRETTY); - - Multi multi = new Multi(); - multi.getSingle().add(setSData()); - +// @Test +// public void saved() throws Exception { +// Saved saved = new Saved(); +// saved.extract(in, ignore, parser, options); +// } + + @Test + public void df() throws Exception { + RosettaEnv env = new RosettaEnv(); + RosettaDF df = env.newDataFactory(Multi.class); + df.out(TYPE.JSON).option(Data.PRETTY); + + Multi multi = new Multi(); + multi.getSingle().add(setSData()); + - System.out.println("========== Original loading"); - Trans trans = env.newTrans(); - RosettaData data = df.newData(trans); - // Prime pump - for(int i=0;i<100;++i) { - data.load(multi); - } - trans = env.newTrans(); - data = df.newData(trans); - - int iters = 10000; - for(int i=0;i data = df.newData(trans); + // Prime pump + for(int i=0;i<100;++i) { + data.load(multi); + } + trans = env.newTrans(); + data = df.newData(trans); + + int iters = 10000; + for(int i=0;i jin = new InJson(); -// Out jout = new OutJson(); +// @Test +// public void jsonInOut() throws IOException, ParseException { +// Parse jin = new InJson(); +// Out jout = new OutJson(); // -//// go(jin, jout, "{\"id\":\"Me, Myself\",\"date\":1353094689100}"); -// -// } - - - /* - private void go(Parse in, Out out, String str) throws IOException, ParseException { - - System.out.println(str); - StringWriter sw = new StringWriter(1024); - out.extract(new StringReader(str), sw, in); - System.out.println(sw); - String result = sw.toString(); - - if(!result.equals(str)) { - sw.getBuffer().setLength(0); - new OutRaw().extract(new StringReader(str), sw, in); - System.out.println(sw); - } +//// go(jin, jout, "{\"id\":\"Me, Myself\",\"date\":1353094689100}"); +// +// } + + + /* + private void go(Parse in, Out out, String str) throws IOException, ParseException { + + System.out.println(str); + StringWriter sw = new StringWriter(1024); + out.extract(new StringReader(str), sw, in); + System.out.println(sw); + String result = sw.toString(); + + if(!result.equals(str)) { + sw.getBuffer().setLength(0); + new OutRaw().extract(new StringReader(str), sw, in); + System.out.println(sw); + } - Assert.assertEquals(str,result); - System.out.println(); + Assert.assertEquals(str,result); + System.out.println(); - } - */ + } + */ } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java index ab0c921a..6ebd07a3 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java @@ -32,60 +32,60 @@ import org.onap.aaf.misc.rosetta.Parsed; public class OutDump extends Out{ - @Override - public void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { - IndentPrintWriter ipw = writer instanceof IndentPrintWriter?(IndentPrintWriter)writer:new IndentPrintWriter(writer); + @Override + public void extract(IN in, Writer writer, Parse prs, boolean ... options) throws IOException, ParseException { + IndentPrintWriter ipw = writer instanceof IndentPrintWriter?(IndentPrintWriter)writer:new IndentPrintWriter(writer); - Parsed p = prs.newParsed(); - - while((p = prs.parse(in,p.reuse())).valid()) { - switch(p.event) { - case Parse.START_OBJ: - ipw.append("Start Object "); - ipw.append(p.name); - ipw.inc(); - break; - case Parse.END_OBJ: - printData(ipw,p); - ipw.dec(); - ipw.append("End Object "); - ipw.append(p.name); - break; - case Parse.START_ARRAY: - ipw.inc(); - ipw.append("Start Array "); - ipw.append(p.name); - ipw.append('\n'); - break; - case Parse.END_ARRAY: - printData(ipw,p); - ipw.dec(); - ipw.append("End Array "); - ipw.append('\n'); - break; - case Parse.NEXT: - printData(ipw,p); - break; - } - } - } - - private void printData(IndentPrintWriter ipw, Parsed parsed) { - if(parsed.hasData()) { - ipw.append("Data:["); - if(parsed.hasName()) { - ipw.append(parsed.name); - ipw.append(" : "); - } - ipw.append(parsed.sb); - ipw.append("]"); - ipw.append('\n'); - } - } + Parsed p = prs.newParsed(); + + while((p = prs.parse(in,p.reuse())).valid()) { + switch(p.event) { + case Parse.START_OBJ: + ipw.append("Start Object "); + ipw.append(p.name); + ipw.inc(); + break; + case Parse.END_OBJ: + printData(ipw,p); + ipw.dec(); + ipw.append("End Object "); + ipw.append(p.name); + break; + case Parse.START_ARRAY: + ipw.inc(); + ipw.append("Start Array "); + ipw.append(p.name); + ipw.append('\n'); + break; + case Parse.END_ARRAY: + printData(ipw,p); + ipw.dec(); + ipw.append("End Array "); + ipw.append('\n'); + break; + case Parse.NEXT: + printData(ipw,p); + break; + } + } + } + + private void printData(IndentPrintWriter ipw, Parsed parsed) { + if(parsed.hasData()) { + ipw.append("Data:["); + if(parsed.hasName()) { + ipw.append(parsed.name); + ipw.append(" : "); + } + ipw.append(parsed.sb); + ipw.append("]"); + ipw.append('\n'); + } + } - @Override - public String logName() { - return "Rosetta OutDump"; - } + @Override + public String logName() { + return "Rosetta OutDump"; + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java index 5c709adc..df4fec07 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java @@ -28,40 +28,40 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.env.Trans.Metric; public class Report { - float total; - float buckets[]; - String[] names; - private int iterations; - private int count; - - public Report(int iters, String ... names) { - iterations = iters; - buckets = new float[names.length]; - this.names = names; - total=0; - count = 0; - } - - public void glean(Trans trans, int ... type) { - Metric m = trans.auditTrail(0, null, type); - total+=m.total; - int min = Math.min(buckets.length, m.buckets.length); - for(int b=0;b { - public MultiMarshal() { - add(new ObjArray("single",new SingleMarshal()) { - @Override - protected List data(Multi t) { - return t.getSingle(); - } - }); - } + public MultiMarshal() { + add(new ObjArray("single",new SingleMarshal()) { + @Override + protected List data(Multi t) { + return t.getSingle(); + } + }); + } } \ No newline at end of file diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/obj/SingleMarshal.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/obj/SingleMarshal.java index 932277de..bde91c9e 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/obj/SingleMarshal.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/obj/SingleMarshal.java @@ -37,55 +37,55 @@ import org.onap.aaf.misc.rosetta.marshal.ObjMarshal; import types.xsd.Multi.Single; public class SingleMarshal extends ObjMarshal { - public SingleMarshal() { - add(new FieldString("str") { - @Override - protected String data(Single t) { - return t.getStr(); - } - }); - - add(new FieldNumeric("int") { - @Override - protected Integer data(Single t) { - return t.getInt(); - } - }); - - add(new FieldNumeric("long") { - @Override - protected Long data(Single t) { - return t.getLong(); - } - }); + public SingleMarshal() { + add(new FieldString("str") { + @Override + protected String data(Single t) { + return t.getStr(); + } + }); + + add(new FieldNumeric("int") { + @Override + protected Integer data(Single t) { + return t.getInt(); + } + }); + + add(new FieldNumeric("long") { + @Override + protected Long data(Single t) { + return t.getLong(); + } + }); - add(new FieldDate("date") { - @Override - protected XMLGregorianCalendar data(Single t) { - return t.getDate(); - } - }); + add(new FieldDate("date") { + @Override + protected XMLGregorianCalendar data(Single t) { + return t.getDate(); + } + }); - add(new FieldDateTime("datetime") { - @Override - protected XMLGregorianCalendar data(Single t) { - return t.getDate(); - } - }); - - add(new FieldHexBinary("binary") { - @Override - protected byte[] data(Single t) { - return t.getBinary(); - } - }); - - add(new FieldArray("array", DataWriter.STRING) { - @Override - protected List data(Single t) { - return t.getArray(); - } - }); + add(new FieldDateTime("datetime") { + @Override + protected XMLGregorianCalendar data(Single t) { + return t.getDate(); + } + }); + + add(new FieldHexBinary("binary") { + @Override + protected byte[] data(Single t) { + return t.getBinary(); + } + }); + + add(new FieldArray("array", DataWriter.STRING) { + @Override + protected List data(Single t) { + return t.getArray(); + } + }); - } + } } \ No newline at end of file diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Back.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Back.java index 342e3ace..5bd24b02 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Back.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Back.java @@ -22,13 +22,13 @@ package org.onap.aaf.misc.xgen; public class Back { - public String str; - public boolean dec; - public boolean cr; - - public Back(String string, boolean decrement, boolean newline) { - str = string; - dec = decrement; - cr = newline; - } + public String str; + public boolean dec; + public boolean cr; + + public Back(String string, boolean decrement, boolean newline) { + str = string; + dec = decrement; + cr = newline; + } } \ No newline at end of file diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Cache.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Cache.java index ce90bd13..0f6b0d9c 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Cache.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Cache.java @@ -23,15 +23,15 @@ package org.onap.aaf.misc.xgen; public interface Cache> { - public void dynamic(G hgen, Code code); - - public static class Null> implements Cache { - @Override - public void dynamic(N hgen, Code code) {} // NO_OP, no matter what type + public void dynamic(G hgen, Code code); + + public static class Null> implements Cache { + @Override + public void dynamic(N hgen, Code code) {} // NO_OP, no matter what type - @SuppressWarnings("rawtypes") - private static Null singleton = new Null(); - public static Null singleton() { return singleton;} - } + @SuppressWarnings("rawtypes") + private static Null singleton = new Null(); + public static Null singleton() { return singleton;} + } } \ No newline at end of file diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java index 417f80b7..3edf8b60 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java @@ -35,97 +35,97 @@ import org.onap.aaf.misc.xgen.html.Thematic; public abstract class CacheGen> { - public static final int NO_FLAGS = 0x0; - public final static int PRETTY = 0x1; - public final static int XML = 0x2; - public final static int HTML4 = 0x4; - public final static int HTML5 = 0x8; + public static final int NO_FLAGS = 0x0; + public final static int PRETTY = 0x1; + public final static int XML = 0x2; + public final static int HTML4 = 0x4; + public final static int HTML5 = 0x8; - - private ArrayList> sections = new ArrayList<>(); - private int flags; - private final Thematic thematic; + + private ArrayList> sections = new ArrayList<>(); + private int flags; + private final Thematic thematic; - public CacheGen(int flags, Code code) throws APIException, IOException { - this.flags = flags; - final XGenBuff buff = new XGenBuff(flags,this); - // Run to gather Strings and Code Class Segments - buff.run(new Cache() { - @Override - public void dynamic(G hgen, Code code) { - sections.add(buff.newSection()); - sections.add(new Dynamic(hgen.getIndent(),code)); - } - },code); - sections.add(buff.newSection()); - - // If Code implements thematic, set for later - thematic = code instanceof Thematic?(Thematic)code:null; + public CacheGen(int flags, Code code) throws APIException, IOException { + this.flags = flags; + final XGenBuff buff = new XGenBuff(flags,this); + // Run to gather Strings and Code Class Segments + buff.run(new Cache() { + @Override + public void dynamic(G hgen, Code code) { + sections.add(buff.newSection()); + sections.add(new Dynamic(hgen.getIndent(),code)); + } + },code); + sections.add(buff.newSection()); + + // If Code implements thematic, set for later + thematic = code instanceof Thematic?(Thematic)code:null; - } - - public abstract G create(int htmlStyle, Writer w); + } + + public abstract G create(int htmlStyle, Writer w); - public void replay(State state, Trans trans, OutputStream os, String theme) throws IOException, APIException { - replay(state, trans, new OutputStreamWriter(os), theme); - } - - public void replay(State state, Trans trans,Writer w, String theme) throws IOException, APIException { - if(thematic!=null) { - theme = thematic.themeResolve(theme); - } - /* Theme - trans.setTheme(theme); - int htmlStyle = state.htmlVer(theme); - */ - - XGenBuff buff = new XGenBuff(flags,this); - - // forward - int indent = 0; - Section s; - int i=0; - @SuppressWarnings("unchecked") - Section[] reverse = new Section[sections.size()]; - for(Section section : sections) { - s = section.use(state, trans, buff); // note, doesn't change cached, only dynamic, which is created for thread - int tempIndent = s.getIndent(); - s.setIndent(indent); - s.forward(w); - s.setIndent(tempIndent); - indent = tempIndent; - reverse[i++]=s; - } + public void replay(State state, Trans trans, OutputStream os, String theme) throws IOException, APIException { + replay(state, trans, new OutputStreamWriter(os), theme); + } + + public void replay(State state, Trans trans,Writer w, String theme) throws IOException, APIException { + if(thematic!=null) { + theme = thematic.themeResolve(theme); + } + /* Theme + trans.setTheme(theme); + int htmlStyle = state.htmlVer(theme); + */ + + XGenBuff buff = new XGenBuff(flags,this); + + // forward + int indent = 0; + Section s; + int i=0; + @SuppressWarnings("unchecked") + Section[] reverse = new Section[sections.size()]; + for(Section section : sections) { + s = section.use(state, trans, buff); // note, doesn't change cached, only dynamic, which is created for thread + int tempIndent = s.getIndent(); + s.setIndent(indent); + s.forward(w); + s.setIndent(tempIndent); + indent = tempIndent; + reverse[i++]=s; + } - for(--i;i>=0;--i) { - reverse[i].back(w); - } - w.flush(); - } - - private class Dynamic extends Section { - private Code code; - - public Dynamic(int indent, Code code) { - this.code = code; - this.indent = indent; - } + for(--i;i>=0;--i) { + reverse[i].back(w); + } + w.flush(); + } + + private class Dynamic extends Section { + private Code code; + + public Dynamic(int indent, Code code) { + this.code = code; + this.indent = indent; + } - @SuppressWarnings("unchecked") - public Section use(State state, Trans trans, XGenBuff buff) throws APIException, IOException { - // Clone Dynamic to make Thread Safe - Dynamic d = new Dynamic(indent,code); - buff.setIndent(indent); - if(code instanceof DynamicCode) { - buff.run(state,trans,Cache.Null.singleton(), (DynamicCode)code); - } else { - buff.run((Cache)Cache.Null.singleton(), code); - } - Section s = buff.newSection(); - d.indent = s.indent; - d.forward = s.forward; - d.backward = s.backward; - return d; - } - } + @SuppressWarnings("unchecked") + public Section use(State state, Trans trans, XGenBuff buff) throws APIException, IOException { + // Clone Dynamic to make Thread Safe + Dynamic d = new Dynamic(indent,code); + buff.setIndent(indent); + if(code instanceof DynamicCode) { + buff.run(state,trans,Cache.Null.singleton(), (DynamicCode)code); + } else { + buff.run((Cache)Cache.Null.singleton(), code); + } + Section s = buff.newSection(); + d.indent = s.indent; + d.forward = s.forward; + d.backward = s.backward; + return d; + } + } } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Code.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Code.java index 68048431..971a56e4 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Code.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Code.java @@ -26,5 +26,5 @@ import java.io.IOException; import org.onap.aaf.misc.env.APIException; public interface Code> { - public void code(Cache cache, G xgen) throws APIException, IOException; + public void code(Cache cache, G xgen) throws APIException, IOException; } \ No newline at end of file diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/DynamicCode.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/DynamicCode.java index a4194b97..8d4f4eec 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/DynamicCode.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/DynamicCode.java @@ -35,10 +35,10 @@ import org.onap.aaf.misc.xgen.html.State; * */ public abstract class DynamicCode, AS extends State, TRANS extends Trans> implements Code { - public abstract void code(final AS state, final TRANS trans, final Cache cache, final G xgen) throws APIException, IOException; - - // We expect not to have this section of the code engaged at any time - public void code(final Cache cache, final G xgen) throws APIException, IOException { - code(null, null,cache,xgen); - } + public abstract void code(final AS state, final TRANS trans, final Cache cache, final G xgen) throws APIException, IOException; + + // We expect not to have this section of the code engaged at any time + public void code(final Cache cache, final G xgen) throws APIException, IOException { + code(null, null,cache,xgen); + } } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Mark.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Mark.java index 80b0680d..f9c06c40 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Mark.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Mark.java @@ -22,19 +22,19 @@ package org.onap.aaf.misc.xgen; public class Mark { - // package on purpose - int spot = 0; - public String comment; - - public Mark() { - comment = null; - } - - public Mark(String string) { - comment = string; - } + // package on purpose + int spot = 0; + public String comment; + + public Mark() { + comment = null; + } + + public Mark(String string) { + comment = string; + } - public void spot(int spot) { - this.spot = spot; - } + public void spot(int spot) { + this.spot = spot; + } } \ No newline at end of file diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Section.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Section.java index e73512c3..9f1f2a38 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Section.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/Section.java @@ -30,32 +30,32 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.xgen.html.State; public class Section> { - protected int indent; - protected String forward; - protected String backward; - - // Default is to use the set Strings (static) - public Section use(State state, Trans trans, XGenBuff buff) throws APIException, IOException { - return this; - } - - public int getIndent() { - return indent; - } + protected int indent; + protected String forward; + protected String backward; + + // Default is to use the set Strings (static) + public Section use(State state, Trans trans, XGenBuff buff) throws APIException, IOException { + return this; + } + + public int getIndent() { + return indent; + } - public void setIndent(int indent) { - this.indent = indent; - } + public void setIndent(int indent) { + this.indent = indent; + } - public void forward(Writer w) throws IOException { - w.write(forward); - } - - public void back(Writer w) throws IOException { - w.write(backward); - } - - public String toString() { - return forward; - } + public void forward(Writer w) throws IOException { + w.write(forward); + } + + public void back(Writer w) throws IOException { + w.write(backward); + } + + public String toString() { + return forward; + } } \ No newline at end of file diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java index 4bb6ee28..7b0a4263 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java @@ -30,267 +30,267 @@ import org.onap.aaf.misc.env.util.StringBuilderWriter; public class XGen> { - private static final int COMMENT_COLUMN = 40; - private StringBuilder backSB = new StringBuilder(); - private Stack backStack = new Stack(); - - protected XGen(Writer w) { - forward = new IndentPrintWriter(w); - } - - public int pushBack(Back b) { - int rv = backStack.size(); - backStack.push(b); - return rv; - } - - public boolean pretty = false; - protected IndentPrintWriter forward; - - public IndentPrintWriter getWriter() { - return forward; - } - - protected PrintWriter back = new PrintWriter( - new StringBuilderWriter(backSB)); - - @SuppressWarnings("unchecked") - public RT pretty() { - pretty = true; - return (RT) this; - } - - protected void prettyln(PrintWriter pw) { - if(pretty)pw.println(); - } - - public RT leaf(Mark mark, String tag, String ... args) { - mark.spot = backStack.size(); - return leaf(tag, args); - } - - @SuppressWarnings("unchecked") - public RT leaf(String tag, String ... attrs) { - forward.append('<'); - forward.append(tag); - addAttrs(attrs); - forward.append('>'); - back.append("'); - backStack.push(new Back(backSB.toString(), false, true)); - backSB.setLength(0); - return (RT)this; - } - - public RT incr(String tag, String ... args) { - return incr(null, tag, false, args); - } - - public RT incr(String tag, boolean oneLine, String ... args) { - return incr(null, tag, oneLine, args); - } - - public RT incr(Mark mark) { - return incr(mark,mark.comment, false, new String[0]); - } - - public RT incr(Mark mark, String tag, String ... attrs) { - return incr(mark, tag, false, attrs); - } - - @SuppressWarnings("unchecked") - public RT incr(Mark mark, String tag, boolean oneLine, String ... attrs) { - forward.append('<'); - forward.append(tag); - addAttrs(attrs); - forward.append('>'); - - back.append("'); - - if(pretty) { - if(mark!=null && mark.comment!=null) { - int fi = forward.getIndent()*IndentPrintWriter.INDENT_MULTIPLIER; - for(int i = fi+backSB.length();i<=COMMENT_COLUMN;++i) { - back.append(' '); - } - back.append(""); - - forward.toCol(COMMENT_COLUMN); - forward.append(""); - } - forward.inc(); - if(!oneLine) { - forward.println(); - } - back.println(); - } - if(mark!=null)mark.spot = backStack.size(); - backStack.push(new Back(backSB.toString(),true, false)); - backSB.setLength(0); - return (RT)this; - } - - @SuppressWarnings("unchecked") - public RT tagOnly(String tag, String ... attrs) { - forward.append('<'); - forward.append(tag); - addAttrs(attrs); - forward.append(" />"); - if(pretty) { - forward.println(); - } - return (RT)this; - } - - @SuppressWarnings("unchecked") - public RT text(String txt) { - forward.append(txt); - return (RT)this; - } - - @SuppressWarnings("unchecked") - public RT xml(String txt) { - for(int i=0; i': - forward.append(">"); - break; - case '&': - forward.append("&"); - break; - default: - forward.append(c); - } - } - return (RT)this; - } - - - @SuppressWarnings("unchecked") - public RT textCR(int tabs, String txt) { - for(int i=0;i0) { - forward.append(' '); - String[] split = attr.split("=",2); - switch(split.length) { - case 0: - break; - case 1: - forward.append(split[0]); -// forward.append("=\"\""); - break; - default: - forward.append(split[0]); - forward.append("=\""); - forward.append(split[1]); - forward.append('"'); - break; - } - } - } - } - } - - @SuppressWarnings("unchecked") - public RT comment(String string) { - if(pretty) { - forward.print(""); - } - return (RT)this; - } - - public void setIndent(int indent) { - forward.setIndent(indent); - forward.toIndent(); - } - - public int getIndent() { - return forward.getIndent(); - } + private static final int COMMENT_COLUMN = 40; + private StringBuilder backSB = new StringBuilder(); + private Stack backStack = new Stack(); + + protected XGen(Writer w) { + forward = new IndentPrintWriter(w); + } + + public int pushBack(Back b) { + int rv = backStack.size(); + backStack.push(b); + return rv; + } + + public boolean pretty = false; + protected IndentPrintWriter forward; + + public IndentPrintWriter getWriter() { + return forward; + } + + protected PrintWriter back = new PrintWriter( + new StringBuilderWriter(backSB)); + + @SuppressWarnings("unchecked") + public RT pretty() { + pretty = true; + return (RT) this; + } + + protected void prettyln(PrintWriter pw) { + if(pretty)pw.println(); + } + + public RT leaf(Mark mark, String tag, String ... args) { + mark.spot = backStack.size(); + return leaf(tag, args); + } + + @SuppressWarnings("unchecked") + public RT leaf(String tag, String ... attrs) { + forward.append('<'); + forward.append(tag); + addAttrs(attrs); + forward.append('>'); + back.append("'); + backStack.push(new Back(backSB.toString(), false, true)); + backSB.setLength(0); + return (RT)this; + } + + public RT incr(String tag, String ... args) { + return incr(null, tag, false, args); + } + + public RT incr(String tag, boolean oneLine, String ... args) { + return incr(null, tag, oneLine, args); + } + + public RT incr(Mark mark) { + return incr(mark,mark.comment, false, new String[0]); + } + + public RT incr(Mark mark, String tag, String ... attrs) { + return incr(mark, tag, false, attrs); + } + + @SuppressWarnings("unchecked") + public RT incr(Mark mark, String tag, boolean oneLine, String ... attrs) { + forward.append('<'); + forward.append(tag); + addAttrs(attrs); + forward.append('>'); + + back.append("'); + + if(pretty) { + if(mark!=null && mark.comment!=null) { + int fi = forward.getIndent()*IndentPrintWriter.INDENT_MULTIPLIER; + for(int i = fi+backSB.length();i<=COMMENT_COLUMN;++i) { + back.append(' '); + } + back.append(""); + + forward.toCol(COMMENT_COLUMN); + forward.append(""); + } + forward.inc(); + if(!oneLine) { + forward.println(); + } + back.println(); + } + if(mark!=null)mark.spot = backStack.size(); + backStack.push(new Back(backSB.toString(),true, false)); + backSB.setLength(0); + return (RT)this; + } + + @SuppressWarnings("unchecked") + public RT tagOnly(String tag, String ... attrs) { + forward.append('<'); + forward.append(tag); + addAttrs(attrs); + forward.append(" />"); + if(pretty) { + forward.println(); + } + return (RT)this; + } + + @SuppressWarnings("unchecked") + public RT text(String txt) { + forward.append(txt); + return (RT)this; + } + + @SuppressWarnings("unchecked") + public RT xml(String txt) { + for(int i=0; i': + forward.append(">"); + break; + case '&': + forward.append("&"); + break; + default: + forward.append(c); + } + } + return (RT)this; + } + + + @SuppressWarnings("unchecked") + public RT textCR(int tabs, String txt) { + for(int i=0;i0) { + forward.append(' '); + String[] split = attr.split("=",2); + switch(split.length) { + case 0: + break; + case 1: + forward.append(split[0]); +// forward.append("=\"\""); + break; + default: + forward.append(split[0]); + forward.append("=\""); + forward.append(split[1]); + forward.append('"'); + break; + } + } + } + } + } + + @SuppressWarnings("unchecked") + public RT comment(String string) { + if(pretty) { + forward.print(""); + } + return (RT)this; + } + + public void setIndent(int indent) { + forward.setIndent(indent); + forward.toIndent(); + } + + public int getIndent() { + return forward.getIndent(); + } } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGenBuff.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGenBuff.java index d2578a34..5f11e4db 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGenBuff.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGenBuff.java @@ -30,57 +30,57 @@ import org.onap.aaf.misc.env.util.StringBuilderWriter; import org.onap.aaf.misc.xgen.html.State; public class XGenBuff> { - private G xgen; - private StringBuilder sb; - // private String forward, backward; - - public XGenBuff(int flags, CacheGen cg) { - sb = new StringBuilder(); - xgen = cg.create(flags, new StringBuilderWriter(sb)); - } + private G xgen; + private StringBuilder sb; + // private String forward, backward; + + public XGenBuff(int flags, CacheGen cg) { + sb = new StringBuilder(); + xgen = cg.create(flags, new StringBuilderWriter(sb)); + } - /** - * Normal case of building up Cached HTML without transaction info - * - * @param cache - * @param code - * @throws APIException - * @throws IOException - */ - public void run(Cache cache, Code code) throws APIException, IOException { - code.code(cache, xgen); - } + /** + * Normal case of building up Cached HTML without transaction info + * + * @param cache + * @param code + * @throws APIException + * @throws IOException + */ + public void run(Cache cache, Code code) throws APIException, IOException { + code.code(cache, xgen); + } - /** - * Special Case where code is dynamic, so give access to State and Trans info - * - * @param state - * @param trans - * @param cache - * @param code - * @throws APIException - * @throws IOException - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void run(State state, Trans trans, Cache cache, DynamicCode code) throws APIException, IOException { - code.code(state, trans, cache, xgen); - } - - public int getIndent() { - return xgen.getIndent(); - } + /** + * Special Case where code is dynamic, so give access to State and Trans info + * + * @param state + * @param trans + * @param cache + * @param code + * @throws APIException + * @throws IOException + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void run(State state, Trans trans, Cache cache, DynamicCode code) throws APIException, IOException { + code.code(state, trans, cache, xgen); + } + + public int getIndent() { + return xgen.getIndent(); + } - public void setIndent(int indent) { - xgen.setIndent(indent); - } + public void setIndent(int indent) { + xgen.setIndent(indent); + } - public Section newSection() { - Section s = new Section(); - s.indent = xgen.getIndent(); - s.forward = sb.toString(); - sb.setLength(0); - s.backward = sb.toString(); - sb.setLength(0); - return s; - } + public Section newSection() { + Section s = new Section(); + s.indent = xgen.getIndent(); + s.forward = sb.toString(); + sb.setLength(0); + s.backward = sb.toString(); + sb.setLength(0); + return s; + } } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java index 34d798d5..16ac60ae 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java @@ -26,118 +26,118 @@ import java.io.Writer; import org.onap.aaf.misc.xgen.Mark; public class HTML4Gen extends HTMLGen { - private final static String DOCTYPE = - /* - ""; - ""; - */ - ""; + private final static String DOCTYPE = + /* + ""; + ""; + */ + ""; - public HTML4Gen(Writer w) { - super(w); - } + public HTML4Gen(Writer w) { + super(w); + } - @Override - public HTMLGen html(String ... attrib) { - forward.println(DOCTYPE); - return incr("html","xmlns=http://www.w3.org/1999/xhtml","xml:lang=en","lang=en"); - - } + @Override + public HTMLGen html(String ... attrib) { + forward.println(DOCTYPE); + return incr("html","xmlns=http://www.w3.org/1999/xhtml","xml:lang=en","lang=en"); + + } - @Override - public Mark head() { - Mark head = new Mark("head"); - incr(head); - return head; - } + @Override + public Mark head() { + Mark head = new Mark("head"); + incr(head); + return head; + } - @Override - public Mark body(String ... attrs) { - Mark body = new Mark("body"); - incr(body,"body",attrs); - return body; - } - - @Override - public HTML4Gen charset(String charset) { - forward.append(""); - prettyln(forward); - return this; - } + @Override + public Mark body(String ... attrs) { + Mark body = new Mark("body"); + incr(body,"body",attrs); + return body; + } + + @Override + public HTML4Gen charset(String charset) { + forward.append(""); + prettyln(forward); + return this; + } - @Override - public Mark header(String ... attribs) { - String[] a = new String[attribs.length+1]; - a[0]="header"; - System.arraycopy(attribs, 0, a, 1, attribs.length); - return divID(a); - } + @Override + public Mark header(String ... attribs) { + String[] a = new String[attribs.length+1]; + a[0]="header"; + System.arraycopy(attribs, 0, a, 1, attribs.length); + return divID(a); + } - @Override - public Mark footer(String ... attribs) { - String[] a = new String[attribs.length+1]; - a[0]="footer"; - System.arraycopy(attribs, 0, a, 1, attribs.length); - return divID(a); - } + @Override + public Mark footer(String ... attribs) { + String[] a = new String[attribs.length+1]; + a[0]="footer"; + System.arraycopy(attribs, 0, a, 1, attribs.length); + return divID(a); + } - @Override - public Mark section(String ... attribs) { - String[] a = new String[attribs.length+1]; - a[0]="section"; - System.arraycopy(attribs, 0, a, 1, attribs.length); - return divID(a); - } + @Override + public Mark section(String ... attribs) { + String[] a = new String[attribs.length+1]; + a[0]="section"; + System.arraycopy(attribs, 0, a, 1, attribs.length); + return divID(a); + } - @Override - public Mark article(String ... attribs) { - String[] a = new String[attribs.length+1]; - a[0]="attrib"; - System.arraycopy(attribs, 0, a, 1, attribs.length); - return divID(a); - } + @Override + public Mark article(String ... attribs) { + String[] a = new String[attribs.length+1]; + a[0]="attrib"; + System.arraycopy(attribs, 0, a, 1, attribs.length); + return divID(a); + } - @Override - public Mark aside(String ... attribs) { - String[] a = new String[attribs.length+1]; - a[0]="aside"; - System.arraycopy(attribs, 0, a, 1, attribs.length); - return divID(a); - } + @Override + public Mark aside(String ... attribs) { + String[] a = new String[attribs.length+1]; + a[0]="aside"; + System.arraycopy(attribs, 0, a, 1, attribs.length); + return divID(a); + } - @Override - public Mark nav(String ... attribs) { - String[] a = new String[attribs.length+1]; - a[0]="nav"; - System.arraycopy(attribs, 0, a, 1, attribs.length); - return divID(a); - } + @Override + public Mark nav(String ... attribs) { + String[] a = new String[attribs.length+1]; + a[0]="nav"; + System.arraycopy(attribs, 0, a, 1, attribs.length); + return divID(a); + } -// @Override -// protected void importCSS(Imports imports) { -// if(imports.css.size()==1) { -// cssInline(imports.css.get(0)); -// } else { -// text(""); -// prettyln(forward); -// } -// } - +// @Override +// protected void importCSS(Imports imports) { +// if(imports.css.size()==1) { +// cssInline(imports.css.get(0)); +// } else { +// text(""); +// prettyln(forward); +// } +// } + } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java index f155a65e..5e4cee7e 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java @@ -26,130 +26,130 @@ import java.io.Writer; import org.onap.aaf.misc.xgen.Mark; public class HTML5Gen extends HTMLGen { - public HTML5Gen(Writer w) { - super(w); - } - - @Override - public HTMLGen html(String ... attrib) { - //forward.println(""); - incr("html",attrib); - return this; - } - - @Override - public Mark head() { - Mark head = new Mark("head"); - incr(head).directive("meta","charset=utf-8"); - return head; - } - - @Override - public Mark body(String ... attrs) { - Mark body = new Mark("body"); - incr(body,"body",attrs); - //chromeFrame(); - return body; - } - - @Override - public HTML5Gen charset(String charset) { - forward.append(""); - prettyln(forward); - return this; - } - - @Override - public Mark header(String ... attribs) { - Mark mark = new Mark("header"); - incr(mark, mark.comment, attribs); - return mark; - } - - @Override - public Mark footer(String ... attribs) { - Mark mark = new Mark("footer"); - incr(mark, mark.comment, attribs); - return mark; - } - - @Override - public Mark section(String ... attribs) { - Mark mark = new Mark("section"); - incr(mark, mark.comment,attribs); - return mark; - } - - @Override - public Mark article(String ... attribs) { - Mark mark = new Mark("article"); - incr(mark, mark.comment,attribs); - return mark; - } - - @Override - public Mark aside(String ... attribs) { - Mark mark = new Mark("aside"); - incr(mark, mark.comment,attribs); - return mark; - } - - @Override - public Mark nav(String ... attribs) { - Mark mark = new Mark("nav"); - incr(mark, mark.comment,attribs); - return mark; - } - - -// @Override -// protected void importCSS(Imports imports) { -// if(imports.css.size() == 1) { -// cssInline(imports.css.get(0)); -// } else { -// for(String str : imports.css) { -// forward.print(""); -// } -// } -// } + public HTML5Gen(Writer w) { + super(w); + } + + @Override + public HTMLGen html(String ... attrib) { + //forward.println(""); + incr("html",attrib); + return this; + } + + @Override + public Mark head() { + Mark head = new Mark("head"); + incr(head).directive("meta","charset=utf-8"); + return head; + } + + @Override + public Mark body(String ... attrs) { + Mark body = new Mark("body"); + incr(body,"body",attrs); + //chromeFrame(); + return body; + } + + @Override + public HTML5Gen charset(String charset) { + forward.append(""); + prettyln(forward); + return this; + } + + @Override + public Mark header(String ... attribs) { + Mark mark = new Mark("header"); + incr(mark, mark.comment, attribs); + return mark; + } + + @Override + public Mark footer(String ... attribs) { + Mark mark = new Mark("footer"); + incr(mark, mark.comment, attribs); + return mark; + } + + @Override + public Mark section(String ... attribs) { + Mark mark = new Mark("section"); + incr(mark, mark.comment,attribs); + return mark; + } + + @Override + public Mark article(String ... attribs) { + Mark mark = new Mark("article"); + incr(mark, mark.comment,attribs); + return mark; + } + + @Override + public Mark aside(String ... attribs) { + Mark mark = new Mark("aside"); + incr(mark, mark.comment,attribs); + return mark; + } + + @Override + public Mark nav(String ... attribs) { + Mark mark = new Mark("nav"); + incr(mark, mark.comment,attribs); + return mark; + } + + +// @Override +// protected void importCSS(Imports imports) { +// if(imports.css.size() == 1) { +// cssInline(imports.css.get(0)); +// } else { +// for(String str : imports.css) { +// forward.print(""); +// } +// } +// } // - /* - public void chromeFrame() { - this.textCR(0,""); - } - */ + /* + public void chromeFrame() { + this.textCR(0,""); + } + */ } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLCacheGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLCacheGen.java index 74c5a000..0c94d837 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLCacheGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLCacheGen.java @@ -29,31 +29,31 @@ import org.onap.aaf.misc.xgen.CacheGen; import org.onap.aaf.misc.xgen.Code; public class HTMLCacheGen extends CacheGen { - protected int flags; - - public HTMLCacheGen(int flags, Code code) throws APIException,IOException { - super(flags, code); - this.flags = flags; - } - - @Override - public HTMLGen create(int htmlStyle, Writer w) { - HTMLGen hg; - switch(htmlStyle&(CacheGen.HTML4|CacheGen.HTML5)) { - case CacheGen.HTML4: - hg = new HTML4Gen(w); - break; - case CacheGen.HTML5: - default: - hg = new HTML5Gen(w); - break; - - } - hg.pretty = (htmlStyle&CacheGen.PRETTY)>0; - return hg; - } - - protected HTMLGen clone(Writer w) { - return create(flags,w); - } + protected int flags; + + public HTMLCacheGen(int flags, Code code) throws APIException,IOException { + super(flags, code); + this.flags = flags; + } + + @Override + public HTMLGen create(int htmlStyle, Writer w) { + HTMLGen hg; + switch(htmlStyle&(CacheGen.HTML4|CacheGen.HTML5)) { + case CacheGen.HTML4: + hg = new HTML4Gen(w); + break; + case CacheGen.HTML5: + default: + hg = new HTML5Gen(w); + break; + + } + hg.pretty = (htmlStyle&CacheGen.PRETTY)>0; + return hg; + } + + protected HTMLGen clone(Writer w) { + return create(flags,w); + } } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java index c3359745..b2fb81d1 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java @@ -27,214 +27,214 @@ import org.onap.aaf.misc.xgen.Mark; import org.onap.aaf.misc.xgen.XGen; public abstract class HTMLGen extends XGen { - public static final String A = "a"; - public static final String P = "p"; - public static final String LI = "li"; - public static final String OL = "ol"; - public static final String UL = "ul"; - - - public static final String TABLE = "table"; - public static final String THEAD = "thead"; - public static final String TBODY = "tbody"; - public static final String TR = "tr"; - public static final String TH = "th"; - public static final String TD = "td"; - - public static final String TITLE = "title"; - public static final String H1 = "h1"; - public static final String H2 = "h2"; - public static final String H3 = "h3"; - public static final String H4 = "h4"; - public static final String H5 = "h5"; - - - - // --------------------------- HTML Version Specific ----------------------- - public abstract HTMLGen html(String ... attributes); - public abstract HTMLGen charset(String charset); - public abstract Mark head(); - public abstract Mark body(String ... attribs); - - - // HTML 5 has simplified sectioning - public abstract Mark header(String ... attribs); - public abstract Mark footer(String ... attribs); - public abstract Mark section(String ... attribs); - public abstract Mark article(String ... attribs); - public abstract Mark aside(String ... attribs); - public abstract Mark nav(String ... attribs); - - // --------------------------- HTML Version Specific ----------------------- - - public HTMLGen imports(Imports imports) { - //this.imports=imports; - for(String str : imports.css) { - forward.print(""); - } - - for(String str : imports.js) { - forward.print(""); - } - return this; - } - - public HTMLGen jsVars(String ... attrs) { - forward.println(""); - return this; - } - - public HTMLGen(Writer w) { - super(w); - } - - /** - * Use "directive" to handle non-ended HTML tags like and - * @param tag - * @param attrs - * @return - */ - public HTMLGen directive(String tag, String ... attrs) { - forward.append('<'); - forward.append(tag); - addAttrs(attrs); - forward.append('>'); - if(pretty) { - forward.println(); - } - return this; - } - - public Mark divID(String ... attrs) { - Mark div; - if(attrs.length>0) { - div = new Mark(attrs[0]); - attrs[0]="id="+attrs[0]; - } else { - div = new Mark(); - } - incr(div, "div", attrs); - return div; - } - - public HTMLGen img(String ... attrs) { - return tagOnly("img", attrs); - } - - /** - * Input Cheesecake... creates a Label and Field in the form of Table Rows. - * Make sure you create a table first, ie. incr(HTMLGen.TABLE); - * - * Setting Required to "true" will add required Attribute to both Label and Field. In HTML5, "required" in the input will - * validate there is data in the fields before submitting. "required" does nothing for label, but allows for - * easy CSS coding... "label[required] { ... }", so that colors can be changed - * - * @param id - * @param label - * @param required - * @param attrs - * @return - */ - public HTMLGen input(String id, String label, boolean required, String ... attrs) { - Mark mtr = new Mark(TR); - Mark mtd = new Mark(TD); - incr(mtr); - incr(mtd); - incr("label",true, "for="+id,required?"required":null).text(label).end(); - end(mtd); - String nattrs[] = new String[attrs.length+(required?3:2)]; - nattrs[0]="id="+id; - nattrs[1]="name="+id; - System.arraycopy(attrs, 0, nattrs, 2, attrs.length); - if(required) { - nattrs[nattrs.length-1]="required"; - } - incr(mtd); - tagOnly("input",nattrs); - end(mtr); - return this; - } - - // Common tags that do not have standard endings. These are here to help people who don't know to pick directive - public HTMLGen br() { - forward.append("
    "); - if(pretty) { - forward.println(); - } - return this; - } - - public HTMLGen p(String ... text) { - forward.append("

    "); - for(String s : text) { - forward.append(s); - } - if(pretty) { - forward.println(); - } - return this; - } - - public HTMLGen hr() { - forward.append("


    "); - if(pretty) { - forward.println(); - } - return this; - } - - public JSGen js(Mark mark) { - return new JSGen(mark, this); - } - - public JSGen js() { - return js(null); - } + public static final String A = "a"; + public static final String P = "p"; + public static final String LI = "li"; + public static final String OL = "ol"; + public static final String UL = "ul"; + + + public static final String TABLE = "table"; + public static final String THEAD = "thead"; + public static final String TBODY = "tbody"; + public static final String TR = "tr"; + public static final String TH = "th"; + public static final String TD = "td"; + + public static final String TITLE = "title"; + public static final String H1 = "h1"; + public static final String H2 = "h2"; + public static final String H3 = "h3"; + public static final String H4 = "h4"; + public static final String H5 = "h5"; + + + + // --------------------------- HTML Version Specific ----------------------- + public abstract HTMLGen html(String ... attributes); + public abstract HTMLGen charset(String charset); + public abstract Mark head(); + public abstract Mark body(String ... attribs); + + + // HTML 5 has simplified sectioning + public abstract Mark header(String ... attribs); + public abstract Mark footer(String ... attribs); + public abstract Mark section(String ... attribs); + public abstract Mark article(String ... attribs); + public abstract Mark aside(String ... attribs); + public abstract Mark nav(String ... attribs); + + // --------------------------- HTML Version Specific ----------------------- + + public HTMLGen imports(Imports imports) { + //this.imports=imports; + for(String str : imports.css) { + forward.print(""); + } + + for(String str : imports.js) { + forward.print(""); + } + return this; + } + + public HTMLGen jsVars(String ... attrs) { + forward.println(""); + return this; + } + + public HTMLGen(Writer w) { + super(w); + } + + /** + * Use "directive" to handle non-ended HTML tags like and + * @param tag + * @param attrs + * @return + */ + public HTMLGen directive(String tag, String ... attrs) { + forward.append('<'); + forward.append(tag); + addAttrs(attrs); + forward.append('>'); + if(pretty) { + forward.println(); + } + return this; + } + + public Mark divID(String ... attrs) { + Mark div; + if(attrs.length>0) { + div = new Mark(attrs[0]); + attrs[0]="id="+attrs[0]; + } else { + div = new Mark(); + } + incr(div, "div", attrs); + return div; + } + + public HTMLGen img(String ... attrs) { + return tagOnly("img", attrs); + } + + /** + * Input Cheesecake... creates a Label and Field in the form of Table Rows. + * Make sure you create a table first, ie. incr(HTMLGen.TABLE); + * + * Setting Required to "true" will add required Attribute to both Label and Field. In HTML5, "required" in the input will + * validate there is data in the fields before submitting. "required" does nothing for label, but allows for + * easy CSS coding... "label[required] { ... }", so that colors can be changed + * + * @param id + * @param label + * @param required + * @param attrs + * @return + */ + public HTMLGen input(String id, String label, boolean required, String ... attrs) { + Mark mtr = new Mark(TR); + Mark mtd = new Mark(TD); + incr(mtr); + incr(mtd); + incr("label",true, "for="+id,required?"required":null).text(label).end(); + end(mtd); + String nattrs[] = new String[attrs.length+(required?3:2)]; + nattrs[0]="id="+id; + nattrs[1]="name="+id; + System.arraycopy(attrs, 0, nattrs, 2, attrs.length); + if(required) { + nattrs[nattrs.length-1]="required"; + } + incr(mtd); + tagOnly("input",nattrs); + end(mtr); + return this; + } + + // Common tags that do not have standard endings. These are here to help people who don't know to pick directive + public HTMLGen br() { + forward.append("
    "); + if(pretty) { + forward.println(); + } + return this; + } + + public HTMLGen p(String ... text) { + forward.append("

    "); + for(String s : text) { + forward.append(s); + } + if(pretty) { + forward.println(); + } + return this; + } + + public HTMLGen hr() { + forward.append("


    "); + if(pretty) { + forward.println(); + } + return this; + } + + public JSGen js(Mark mark) { + return new JSGen(mark, this); + } + + public JSGen js() { + return js(null); + } // -// protected void cssInline(String filename) { -// File file = new File(imports.webDir,filename); -// try { -// String line; -// BufferedReader br = new BufferedReader(new FileReader(file)); -// try { -// forward.print(""); -// prettyln(forward); -// br.close(); -// } -// } catch (IOException e) { -// e.printStackTrace(); -// // Can't read, suffice to import normally? -// // for now, just skip -// } -// } - +// protected void cssInline(String filename) { +// File file = new File(imports.webDir,filename); +// try { +// String line; +// BufferedReader br = new BufferedReader(new FileReader(file)); +// try { +// forward.print(""); +// prettyln(forward); +// br.close(); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// // Can't read, suffice to import normally? +// // for now, just skip +// } +// } + } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java index 17678b3f..00e7f30f 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java @@ -25,73 +25,73 @@ import java.util.ArrayList; import java.util.List; public class Imports implements Thematic{ - List css; - List js; - public final int backdots; - private String theme; - - public Imports(int backdots) { - - css = new ArrayList<>(); - js = new ArrayList<>(); - this.backdots = backdots; - theme = ""; - } - - public Imports css(String str) { - css.add(str); - return this; - } - - public Imports js(String str) { - js.add(str); - return this; - } + List css; + List js; + public final int backdots; + private String theme; + + public Imports(int backdots) { + + css = new ArrayList<>(); + js = new ArrayList<>(); + this.backdots = backdots; + theme = ""; + } + + public Imports css(String str) { + css.add(str); + return this; + } + + public Imports js(String str) { + js.add(str); + return this; + } - public Imports theme(String str) { - theme = str==null?"":str; - return this; - } + public Imports theme(String str) { + theme = str==null?"":str; + return this; + } - /** - * Pass in a possible Theme. If it is "" or null, it will resolve to default Theme set in Imports - * - * @param theTheme - * @return - */ - @Override - public String themePath(String theTheme) { - StringBuilder src = dots(new StringBuilder()); - if(theTheme==null||theTheme.length()==0) { - src.append(theme); - if(theme.length()>0)src.append('/'); - } else { - src.append(theTheme); - src.append('/'); - } + /** + * Pass in a possible Theme. If it is "" or null, it will resolve to default Theme set in Imports + * + * @param theTheme + * @return + */ + @Override + public String themePath(String theTheme) { + StringBuilder src = dots(new StringBuilder()); + if(theTheme==null||theTheme.length()==0) { + src.append(theme); + if(theme.length()>0)src.append('/'); + } else { + src.append(theTheme); + src.append('/'); + } - return src.toString(); - } - - /** - * Pass in a possible Theme. If it is "" or null, it will resolve to default Theme set in Imports - * - * @param theTheme - * @return - */ - @Override - public String themeResolve(String theTheme) { - return (theTheme==null||theTheme.length()==0) - ?theme - :theTheme; - } + return src.toString(); + } + + /** + * Pass in a possible Theme. If it is "" or null, it will resolve to default Theme set in Imports + * + * @param theTheme + * @return + */ + @Override + public String themeResolve(String theTheme) { + return (theTheme==null||theTheme.length()==0) + ?theme + :theTheme; + } - public StringBuilder dots(StringBuilder src) { - for(int i=0;i0) ipw.print(' '); - ipw.print(el); - } - } - ipw.println(); - } else { - ipw.print(line.trim()); - } - } - } finally { - htmlGen.setIndent(indent); - try { - br.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return this; - } - - public JSGen pst(String ... lines) { - return pst(null, lines); - } - - public JSGen pst(Mark jm, String ... lines) { - if(lines.length>0) ipw.append(lines[0]); - ipw.append('('); - for(int i=1;i0) ipw.print(' '); + ipw.print(el); + } + } + ipw.println(); + } else { + ipw.print(line.trim()); + } + } + } finally { + htmlGen.setIndent(indent); + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return this; + } + + public JSGen pst(String ... lines) { + return pst(null, lines); + } + + public JSGen pst(Mark jm, String ... lines) { + if(lines.length>0) ipw.append(lines[0]); + ipw.append('('); + for(int i=1;i0)ipw.println(); - ipw.print(lines[i]); - } - ipw.setIndent(current); - ipw.append(';'); - if(htmlGen.pretty)ipw.println(); - return this; - } - - public JSGen text(String text) { - ipw.append(text); - if(htmlGen.pretty)ipw.println(); - return this; - } + if(htmlGen.pretty) { + back = new Back(");\n",false,false); + } else { + back = new Back(");",false,false); + } + int spot = htmlGen.pushBack(back); + if(jm!=null)jm.spot(spot); + return this; + } + + public JSGen li(String ... lines) { + int current = ipw.getIndent(); + for(int i=0;i0)ipw.println(); + ipw.print(lines[i]); + } + ipw.setIndent(current); + ipw.append(';'); + if(htmlGen.pretty)ipw.println(); + return this; + } + + public JSGen text(String text) { + ipw.append(text); + if(htmlGen.pretty)ipw.println(); + return this; + } - public JSGen function(String name, String ... params) { - return function(null, name, params); - } - - public JSGen jqfunc(Mark mark, String name, String ... params) { - pst(mark,"$").function(name, params); - return this; - } - - public JSGen function(Mark jm, String name, String ... params) { - ipw.print("function "); - ipw.print(name); - ipw.print('('); - for(int i=0;i0)ipw.println(); - ipw.print(lines[i]); - } - ipw.setIndent(current); - ipw.print('{'); - if(htmlGen.pretty) { - ipw.println(); - ipw.inc(); - } - int spot = htmlGen.pushBack(new Back("}",true,true)); - if(jm!=null)jm.spot(spot); - return this; + public JSGen cb(Mark jm, String ... lines) { + int current = ipw.getIndent(); + for(int i=0;i0)ipw.println(); + ipw.print(lines[i]); + } + ipw.setIndent(current); + ipw.print('{'); + if(htmlGen.pretty) { + ipw.println(); + ipw.inc(); + } + int spot = htmlGen.pushBack(new Back("}",true,true)); + if(jm!=null)jm.spot(spot); + return this; - } + } - - public JSGen comment(String ... lines) { - if(htmlGen.pretty) { - for(int i=0;i { - public XMLCacheGen(int flags, Code code) throws APIException, - IOException { - super(flags, code); - } + public XMLCacheGen(int flags, Code code) throws APIException, + IOException { + super(flags, code); + } - @Override - public XMLGen create(int style, Writer w) { - XMLGen xg = new XMLGen(w); - xg.pretty = (style & PRETTY)==PRETTY; - return xg; - } + @Override + public XMLGen create(int style, Writer w) { + XMLGen xg = new XMLGen(w); + xg.pretty = (style & PRETTY)==PRETTY; + return xg; + } } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/xml/XMLGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/xml/XMLGen.java index 6683c627..a5d75453 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/xml/XMLGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/xml/XMLGen.java @@ -26,19 +26,19 @@ import java.io.Writer; import org.onap.aaf.misc.xgen.XGen;; public class XMLGen extends XGen { - private final String XML_TAG; - - public XMLGen(Writer w) { - this(w,"UTF-8"); - } - - public XMLGen(Writer w, String encoding) { - super(w); - XML_TAG=""; - } + private final String XML_TAG; + + public XMLGen(Writer w) { + this(w,"UTF-8"); + } + + public XMLGen(Writer w, String encoding) { + super(w); + XML_TAG=""; + } - public XMLGen xml() { - forward.println(XML_TAG); - return this; - } + public XMLGen xml() { + forward.println(XML_TAG); + return this; + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_BackTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_BackTest.java index 6a3eb15e..aa877966 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_BackTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_BackTest.java @@ -26,12 +26,12 @@ import org.junit.Test; public class JU_BackTest { - @Test - public void testBackConstructor() { - Back back = new Back("String", true, false); + @Test + public void testBackConstructor() { + Back back = new Back("String", true, false); - assertEquals(back.str, "String"); - assertEquals(back.dec, true); - assertEquals(back.cr, false); - } + assertEquals(back.str, "String"); + assertEquals(back.dec, true); + assertEquals(back.cr, false); + } } \ No newline at end of file diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_DynamicCodeTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_DynamicCodeTest.java index 5aead073..2a66f851 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_DynamicCodeTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_DynamicCodeTest.java @@ -37,29 +37,29 @@ import org.onap.aaf.misc.xgen.html.State; public class JU_DynamicCodeTest { - @Test - public void test() throws APIException, IOException { - final Cache cache1 = new Cache() { + @Test + public void test() throws APIException, IOException { + final Cache cache1 = new Cache() { - @Override - public void dynamic(HTMLGen hgen, Code code) { - } - }; + @Override + public void dynamic(HTMLGen hgen, Code code) { + } + }; - final HTMLGen xgen1 = new HTML4Gen(new PrintWriter(System.out)); - DynamicCode, Trans> g = new DynamicCode, Trans>() { + final HTMLGen xgen1 = new HTML4Gen(new PrintWriter(System.out)); + DynamicCode, Trans> g = new DynamicCode, Trans>() { - @Override - public void code(State state, Trans trans, Cache cache, HTMLGen xgen) - throws APIException, IOException { - assertNull(state); - assertNull(trans); - assertEquals(cache, cache1); - assertEquals(xgen, xgen1); - } - }; + @Override + public void code(State state, Trans trans, Cache cache, HTMLGen xgen) + throws APIException, IOException { + assertNull(state); + assertNull(trans); + assertEquals(cache, cache1); + assertEquals(xgen, xgen1); + } + }; - g.code(cache1, xgen1); - } + g.code(cache1, xgen1); + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_MarkTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_MarkTest.java index 200bde6e..9a5378a7 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_MarkTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_MarkTest.java @@ -26,16 +26,16 @@ import org.junit.Test; public class JU_MarkTest { - @Test - public void testMark() { - Mark mark = new Mark(); - assertEquals(mark.spot, 0); - assertEquals(mark.comment, null); + @Test + public void testMark() { + Mark mark = new Mark(); + assertEquals(mark.spot, 0); + assertEquals(mark.comment, null); - mark = new Mark("New Comment"); - mark.spot(10); - assertEquals(mark.spot, 10); - assertEquals(mark.comment, "New Comment"); + mark = new Mark("New Comment"); + mark.spot(10); + assertEquals(mark.spot, 10); + assertEquals(mark.comment, "New Comment"); - } + } } \ No newline at end of file diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_NullCacheTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_NullCacheTest.java index 5b5f816a..0f996d5c 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_NullCacheTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_NullCacheTest.java @@ -27,9 +27,9 @@ import org.onap.aaf.misc.xgen.Cache.Null; public class JU_NullCacheTest { - @Test - public void testNullIsSingleton() { - Null singleton = Cache.Null.singleton(); - assertEquals(singleton, Cache.Null.singleton()); - } + @Test + public void testNullIsSingleton() { + Null singleton = Cache.Null.singleton(); + assertEquals(singleton, Cache.Null.singleton()); + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_SectionTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_SectionTest.java index a45ea158..44ca3a14 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_SectionTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/JU_SectionTest.java @@ -34,31 +34,31 @@ import org.onap.aaf.misc.env.APIException; public class JU_SectionTest { - @Mock - private Writer writer; + @Mock + private Writer writer; - @Before - public void setup() { - writer = mock(Writer.class); - } + @Before + public void setup() { + writer = mock(Writer.class); + } - @Test - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void test() throws APIException, IOException { - Section section = new Section(); - section.forward = "Forward"; - section.backward = "Backward"; + @Test + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void test() throws APIException, IOException { + Section section = new Section(); + section.forward = "Forward"; + section.backward = "Backward"; - section.setIndent(10); - section.forward(writer); - section.back(writer); + section.setIndent(10); + section.forward(writer); + section.back(writer); - assertEquals(section.use(null, null, null), section); - assertEquals(section.getIndent(), 10); - assertEquals(section.toString(), "Forward"); + assertEquals(section.use(null, null, null), section); + assertEquals(section.getIndent(), 10); + assertEquals(section.toString(), "Forward"); - verify(writer).write("Forward"); - verify(writer).write("Backward"); - } + verify(writer).write("Forward"); + verify(writer).write("Backward"); + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML4GenTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML4GenTest.java index 9160095d..6fa2afb8 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML4GenTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML4GenTest.java @@ -36,280 +36,280 @@ import org.mockito.Mock; public class JU_HTML4GenTest { - private final static String DOCTYPE = ""; + private final static String DOCTYPE = ""; - private String charset = "utf-8"; + private String charset = "utf-8"; - private final String CHARSET_LINE = ""; + private final String CHARSET_LINE = ""; - @Mock - Writer w; + @Mock + Writer w; - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - w = mock(Writer.class); - } + w = mock(Writer.class); + } - @Test - public void testHTML() throws IOException { + @Test + public void testHTML() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.html("attributes"); + gen.html("attributes"); - Map map = new TreeMap<>(); - for (char ch : DOCTYPE.toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + Map map = new TreeMap<>(); + for (char ch : DOCTYPE.toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "html".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "html".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - verify(w, atLeast(1)).write(anyInt()); - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + verify(w, atLeast(1)).write(anyInt()); + } - @Test - public void testHead() throws IOException { + @Test + public void testHead() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.head(); + gen.head(); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "head".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "head".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testBody() throws IOException { + @Test + public void testBody() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.body("attributes"); + gen.body("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "body".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "body".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testCharSet() throws IOException { + @Test + public void testCharSet() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.charset(charset); + gen.charset(charset); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : CHARSET_LINE.toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : CHARSET_LINE.toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testHeader() throws IOException { + @Test + public void testHeader() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.header("attributes"); + gen.header("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "header".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "header".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "div".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "div".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testFooter() throws IOException { + @Test + public void testFooter() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.footer("attributes"); + gen.footer("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "footer".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "footer".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "div".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "div".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testSection() throws IOException { + @Test + public void testSection() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.section("attributes"); + gen.section("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "section".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "section".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "div".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "div".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testArticle() throws IOException { + @Test + public void testArticle() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.article("attributes"); + gen.article("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "attrib".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "attrib".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "div".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "div".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testAside() throws IOException { + @Test + public void testAside() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.aside("attributes"); + gen.aside("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "aside".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "aside".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "div".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "div".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testNav() throws IOException { + @Test + public void testNav() throws IOException { - HTML4Gen gen = new HTML4Gen(w); + HTML4Gen gen = new HTML4Gen(w); - gen.nav("attributes"); + gen.nav("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "nav".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "nav".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "div".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "div".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML5GenTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML5GenTest.java index 69ebf89b..6426fae5 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML5GenTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_HTML5GenTest.java @@ -36,100 +36,100 @@ import org.mockito.Mock; public class JU_HTML5GenTest { -// private final static String DOCTYPE = ""; +// private final static String DOCTYPE = ""; - private String charset = "utf-8"; + private String charset = "utf-8"; - private final String CHARSET_LINE = ""; + private final String CHARSET_LINE = ""; - @Mock - Writer w; + @Mock + Writer w; - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - w = mock(Writer.class); - } + w = mock(Writer.class); + } - @Test - public void testHTML() throws IOException { + @Test + public void testHTML() throws IOException { - HTML5Gen gen = new HTML5Gen(w); + HTML5Gen gen = new HTML5Gen(w); - gen.html("attributes"); + gen.html("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "html".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "html".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - verify(w, atLeast(1)).write(anyInt()); - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + verify(w, atLeast(1)).write(anyInt()); + } - @Test - public void testHead() throws IOException { + @Test + public void testHead() throws IOException { - HTML5Gen gen = new HTML5Gen(w); + HTML5Gen gen = new HTML5Gen(w); - gen.head(); + gen.head(); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "head".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "head".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testBody() throws IOException { + @Test + public void testBody() throws IOException { - HTML5Gen gen = new HTML5Gen(w); + HTML5Gen gen = new HTML5Gen(w); - gen.body("attributes"); + gen.body("attributes"); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : "body".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } - for (char ch : "attributes".toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : "body".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } + for (char ch : "attributes".toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } - @Test - public void testCharSet() throws IOException { + @Test + public void testCharSet() throws IOException { - HTML5Gen gen = new HTML5Gen(w); + HTML5Gen gen = new HTML5Gen(w); - gen.charset(charset); + gen.charset(charset); - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - for (char ch : CHARSET_LINE.toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : CHARSET_LINE.toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(w, atLeast(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(w, atLeast(map.get(ch))).write(ch); + } + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_ImportsTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_ImportsTest.java index 4a6ce6b8..c9de2d14 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_ImportsTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_ImportsTest.java @@ -27,28 +27,28 @@ import org.junit.Test; public class JU_ImportsTest { - @Before - public void setUp() throws Exception { - } - - @Test - public void test() { - Imports imports = new Imports(2); - imports.css("styles.css"); - imports.js("main.js"); - imports.theme("New Theme"); - - assertEquals("New Theme", imports.themeResolve(null)); - assertEquals("New Theme", imports.themeResolve("")); - assertEquals("The Theme", imports.themeResolve("The Theme")); - - assertEquals("build/../../", imports.dots(new StringBuilder("build/")).toString()); - assertEquals("../../Theme/", imports.themePath("Theme")); - assertEquals("../../New Theme/", imports.themePath("")); - assertEquals("../../New Theme/", imports.themePath(null)); - - imports.theme(null); - assertEquals("../../", imports.themePath(null)); - } + @Before + public void setUp() throws Exception { + } + + @Test + public void test() { + Imports imports = new Imports(2); + imports.css("styles.css"); + imports.js("main.js"); + imports.theme("New Theme"); + + assertEquals("New Theme", imports.themeResolve(null)); + assertEquals("New Theme", imports.themeResolve("")); + assertEquals("The Theme", imports.themeResolve("The Theme")); + + assertEquals("build/../../", imports.dots(new StringBuilder("build/")).toString()); + assertEquals("../../Theme/", imports.themePath("Theme")); + assertEquals("../../New Theme/", imports.themePath("")); + assertEquals("../../New Theme/", imports.themePath(null)); + + imports.theme(null); + assertEquals("../../", imports.themePath(null)); + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_JSGenTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_JSGenTest.java index 8bf811be..a52dae3d 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_JSGenTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/html/JU_JSGenTest.java @@ -39,176 +39,176 @@ import org.onap.aaf.misc.xgen.Mark; public class JU_JSGenTest { - @Mock - private HTMLGen hg; - @Mock - private Mark mark; - @Mock - private IndentPrintWriter writer; - @Mock - private Mark jm; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testFileNotFoundException() { - JSGen gen = new JSGen(mark, hg); - - try { - gen.inline("JSScript", 2); - fail("This file should not be found."); - } catch (Exception e) { - - } - } - - @Test - public void testJSRead() throws IOException { - when(hg.getWriter()).thenReturn(writer); - JSGen gen = new JSGen(mark, hg); - - gen.inline("./sampletest.js", 2); - - verify(writer).print("function myFunction() {"); - verify(writer).print("document.getElementById(\"demo\").innerHTML = \"Paragraph changed.\";"); - verify(writer).print("}"); - verify(writer, times(0)).println(); - } - - @Test - public void testJSReadPrettyPrint() throws IOException { - when(hg.getWriter()).thenReturn(writer); - hg.pretty = true; - JSGen gen = new JSGen(mark, hg); - - gen.inline("./sampletest.js", 2); - - verify(writer).print("function myFunction() {"); - verify(writer).print("document.getElementById(\"demo\").innerHTML = \"Paragraph changed.\";"); - verify(writer).print("}"); - verify(writer, times(3)).println(); - verify(hg).setIndent(0); - } - - @Test - public void testPst() throws IOException { - when(hg.getWriter()).thenReturn(writer); - when(hg.pushBack(any(Back.class))).thenReturn(3); - hg.pretty = true; - JSGen gen = new JSGen(mark, hg); - - gen.pst("line 1", "line 2"); - - verify(writer).append('('); - verify(writer).append("line 1"); - verify(writer).print("line 2"); - verify(writer, times(1)).print(", "); - } - - @Test - public void testPstWithMark() throws IOException { - when(hg.getWriter()).thenReturn(writer); - when(hg.pushBack(any(Back.class))).thenReturn(3); - JSGen gen = new JSGen(mark, hg); - - gen.pst(jm, "line 1", "line 2"); - - verify(writer).append('('); - verify(writer).append("line 1"); - verify(writer).print("line 2"); - verify(writer, times(1)).print(", "); - } - - @Test - public void testPstWithNoLines() throws IOException { - when(hg.getWriter()).thenReturn(writer); - when(hg.pushBack(any(Back.class))).thenReturn(3); - JSGen gen = new JSGen(mark, hg); - - gen.pst(jm); - - verify(writer).append('('); - } - - @Test - public void testLi() throws IOException { - when(hg.getWriter()).thenReturn(writer); - when(writer.getIndent()).thenReturn(3); - - JSGen gen = new JSGen(mark, hg); - - gen.li("line 1", "line 2"); - - verify(writer).setIndent(3); - verify(writer).inc(); - verify(writer).println(); - verify(writer).print("line 1"); - verify(writer).print("line 2"); - - hg.pretty = true; - gen.li("line 1", "line 2"); - verify(writer, times(3)).println(); - } - - @Test - public void testText() throws IOException { - when(hg.getWriter()).thenReturn(writer); - hg.pretty = true; - JSGen gen = new JSGen(mark, hg); - - gen.text("line 1"); - - verify(writer).append("line 1"); - verify(writer).println(); - - hg.pretty = false; - gen.text("line 1"); - - verify(writer, times(2)).append("line 1"); - } - - @Test - public void testFunction() throws IOException { - when(hg.getWriter()).thenReturn(writer); - when(hg.pushBack(any(Back.class))).thenReturn(3); - hg.pretty = true; - JSGen gen = new JSGen(mark, hg); - - gen.function("line 1", "line 2", "line 3"); - - verify(writer).print("function "); - verify(writer).print("line 1"); - verify(writer).print('('); - - verify(writer).print("line 2"); - verify(writer).print("line 3"); - verify(writer, times(1)).print(", "); - verify(writer).print(") {"); - verify(writer).inc(); - verify(writer).println(); - } - - @Test - public void testFunctionWithMark() throws IOException { - when(hg.getWriter()).thenReturn(writer); - when(hg.pushBack(any(Back.class))).thenReturn(3); - JSGen gen = new JSGen(mark, hg); - - gen.function(jm, "line 1", "line 2", "line 3"); - - verify(writer).print("function "); - verify(writer).print("line 1"); - verify(writer).print('('); - - verify(writer).print("line 2"); - verify(writer).print("line 3"); - verify(writer, times(1)).print(", "); - verify(writer).print(") {"); - verify(writer, times(0)).inc(); - verify(writer, times(0)).println(); - } + @Mock + private HTMLGen hg; + @Mock + private Mark mark; + @Mock + private IndentPrintWriter writer; + @Mock + private Mark jm; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testFileNotFoundException() { + JSGen gen = new JSGen(mark, hg); + + try { + gen.inline("JSScript", 2); + fail("This file should not be found."); + } catch (Exception e) { + + } + } + + @Test + public void testJSRead() throws IOException { + when(hg.getWriter()).thenReturn(writer); + JSGen gen = new JSGen(mark, hg); + + gen.inline("./sampletest.js", 2); + + verify(writer).print("function myFunction() {"); + verify(writer).print("document.getElementById(\"demo\").innerHTML = \"Paragraph changed.\";"); + verify(writer).print("}"); + verify(writer, times(0)).println(); + } + + @Test + public void testJSReadPrettyPrint() throws IOException { + when(hg.getWriter()).thenReturn(writer); + hg.pretty = true; + JSGen gen = new JSGen(mark, hg); + + gen.inline("./sampletest.js", 2); + + verify(writer).print("function myFunction() {"); + verify(writer).print("document.getElementById(\"demo\").innerHTML = \"Paragraph changed.\";"); + verify(writer).print("}"); + verify(writer, times(3)).println(); + verify(hg).setIndent(0); + } + + @Test + public void testPst() throws IOException { + when(hg.getWriter()).thenReturn(writer); + when(hg.pushBack(any(Back.class))).thenReturn(3); + hg.pretty = true; + JSGen gen = new JSGen(mark, hg); + + gen.pst("line 1", "line 2"); + + verify(writer).append('('); + verify(writer).append("line 1"); + verify(writer).print("line 2"); + verify(writer, times(1)).print(", "); + } + + @Test + public void testPstWithMark() throws IOException { + when(hg.getWriter()).thenReturn(writer); + when(hg.pushBack(any(Back.class))).thenReturn(3); + JSGen gen = new JSGen(mark, hg); + + gen.pst(jm, "line 1", "line 2"); + + verify(writer).append('('); + verify(writer).append("line 1"); + verify(writer).print("line 2"); + verify(writer, times(1)).print(", "); + } + + @Test + public void testPstWithNoLines() throws IOException { + when(hg.getWriter()).thenReturn(writer); + when(hg.pushBack(any(Back.class))).thenReturn(3); + JSGen gen = new JSGen(mark, hg); + + gen.pst(jm); + + verify(writer).append('('); + } + + @Test + public void testLi() throws IOException { + when(hg.getWriter()).thenReturn(writer); + when(writer.getIndent()).thenReturn(3); + + JSGen gen = new JSGen(mark, hg); + + gen.li("line 1", "line 2"); + + verify(writer).setIndent(3); + verify(writer).inc(); + verify(writer).println(); + verify(writer).print("line 1"); + verify(writer).print("line 2"); + + hg.pretty = true; + gen.li("line 1", "line 2"); + verify(writer, times(3)).println(); + } + + @Test + public void testText() throws IOException { + when(hg.getWriter()).thenReturn(writer); + hg.pretty = true; + JSGen gen = new JSGen(mark, hg); + + gen.text("line 1"); + + verify(writer).append("line 1"); + verify(writer).println(); + + hg.pretty = false; + gen.text("line 1"); + + verify(writer, times(2)).append("line 1"); + } + + @Test + public void testFunction() throws IOException { + when(hg.getWriter()).thenReturn(writer); + when(hg.pushBack(any(Back.class))).thenReturn(3); + hg.pretty = true; + JSGen gen = new JSGen(mark, hg); + + gen.function("line 1", "line 2", "line 3"); + + verify(writer).print("function "); + verify(writer).print("line 1"); + verify(writer).print('('); + + verify(writer).print("line 2"); + verify(writer).print("line 3"); + verify(writer, times(1)).print(", "); + verify(writer).print(") {"); + verify(writer).inc(); + verify(writer).println(); + } + + @Test + public void testFunctionWithMark() throws IOException { + when(hg.getWriter()).thenReturn(writer); + when(hg.pushBack(any(Back.class))).thenReturn(3); + JSGen gen = new JSGen(mark, hg); + + gen.function(jm, "line 1", "line 2", "line 3"); + + verify(writer).print("function "); + verify(writer).print("line 1"); + verify(writer).print('('); + + verify(writer).print("line 2"); + verify(writer).print("line 3"); + verify(writer, times(1)).print(", "); + verify(writer).print(") {"); + verify(writer, times(0)).inc(); + verify(writer, times(0)).println(); + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLCacheGenTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLCacheGenTest.java index c8014dda..5e15fa67 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLCacheGenTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLCacheGenTest.java @@ -34,30 +34,30 @@ import org.onap.aaf.misc.xgen.Code; public class JU_XMLCacheGenTest { - @Mock - Writer writer; + @Mock + Writer writer; - @Mock - Code code; + @Mock + Code code; - @Before - public void setup() { + @Before + public void setup() { - code = mock(Code.class); - writer = mock(Writer.class); - } + code = mock(Code.class); + writer = mock(Writer.class); + } - @Test - public void test() throws APIException, IOException { - XMLCacheGen cacheGen = new XMLCacheGen(0, code); - assertEquals(cacheGen.PRETTY, 1); + @Test + public void test() throws APIException, IOException { + XMLCacheGen cacheGen = new XMLCacheGen(0, code); + assertEquals(cacheGen.PRETTY, 1); - XMLGen xgen = cacheGen.create(1, writer); - assertEquals(0, xgen.getIndent()); + XMLGen xgen = cacheGen.create(1, writer); + assertEquals(0, xgen.getIndent()); - xgen.setIndent(10); - assertEquals(10, xgen.getIndent()); - xgen.comment("Comment"); - } + xgen.setIndent(10); + assertEquals(10, xgen.getIndent()); + xgen.comment("Comment"); + } } diff --git a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLGenTest.java b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLGenTest.java index 1c00b452..18b82393 100644 --- a/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLGenTest.java +++ b/misc/xgen/src/test/java/org/onap/aaf/misc/xgen/xml/JU_XMLGenTest.java @@ -36,31 +36,31 @@ import org.mockito.Mock; public class JU_XMLGenTest { - @Mock - private Writer writer; + @Mock + private Writer writer; - String XML_TAG = ""; + String XML_TAG = ""; - Map map = new TreeMap<>(); + Map map = new TreeMap<>(); - @Before - public void setUp() throws Exception { - writer = mock(Writer.class); - } + @Before + public void setUp() throws Exception { + writer = mock(Writer.class); + } - @Test - public void testXMLGenWriter() throws IOException { - XMLGen xmlGen = new XMLGen(writer); + @Test + public void testXMLGenWriter() throws IOException { + XMLGen xmlGen = new XMLGen(writer); - xmlGen.xml(); + xmlGen.xml(); - for (char ch : XML_TAG.toCharArray()) { - Integer times = map.get(ch); - map.put(ch, (times == null ? 0 : times) + 1); - } + for (char ch : XML_TAG.toCharArray()) { + Integer times = map.get(ch); + map.put(ch, (times == null ? 0 : times) + 1); + } - for (char ch : map.keySet()) { - verify(writer, times(map.get(ch))).write(ch); - } - } + for (char ch : map.keySet()) { + verify(writer, times(map.get(ch))).write(ch); + } + } } \ No newline at end of file -- 2.16.6